You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@polygene.apache.org by pa...@apache.org on 2017/03/13 10:34:53 UTC
[01/50] [abbrv] polygene-java git commit: Add node_modules to
.gitignore [Forced Update!]
Repository: polygene-java
Updated Branches:
refs/heads/serialization-3.0 2ca8c9a69 -> 37c31d4a0 (forced update)
Add node_modules to .gitignore
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/46e26e66
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/46e26e66
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/46e26e66
Branch: refs/heads/serialization-3.0
Commit: 46e26e66527a9e2dbd06cc1925b3aefda1a98976
Parents: 4bca3d7
Author: Paul Merlin <pa...@apache.org>
Authored: Mon Mar 6 12:34:55 2017 +0100
Committer: Paul Merlin <pa...@apache.org>
Committed: Mon Mar 6 12:34:55 2017 +0100
----------------------------------------------------------------------
.gitignore | 1 +
1 file changed, 1 insertion(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/46e26e66/.gitignore
----------------------------------------------------------------------
diff --git a/.gitignore b/.gitignore
index 9a8a6de..b1c086c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,3 +16,4 @@ derby.log
.nb-gradle
.gradletasknamecache
private/cache
+node_modules
[17/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl
index 37eecfa..7aee6a8 100644
--- a/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl
@@ -25,7 +25,6 @@ import org.apache.polygene.bootstrap.LayerAssembly;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.bootstrap.layered.ModuleAssembler;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
-import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
public class ConfigModule
implements ModuleAssembler
@@ -35,7 +34,6 @@ public class ConfigModule
throws AssemblyException
{
module.services( MemoryEntityStoreService.class ).visibleIn( Visibility.layer );
- new JacksonValueSerializationAssembler().visibleIn( Visibility.layer ).assemble( module );
return module;
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl
index f75dc3a..7ff8b96 100644
--- a/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl
@@ -24,9 +24,9 @@ import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.LayerAssembly;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.bootstrap.layered.ModuleAssembler;
-import org.apache.polygene.valueserialization.<%- polygene.serialization.toLowerCase() %>.assembly.<%- polygene.serialization %>ValueSerializationAssembler;
+import org.apache.polygene.serialization.<%- polygene.serialization.toLowerCase() %>.assembly.<%- polygene.serialization %>SerializationAssembler;
-public class <%- polygene.serialization %>ValueSerializationModule
+public class <%- polygene.serialization %>SerializationModule
implements ModuleAssembler
{
public static final String NAME = "<%- polygene.serialization %> Serialization Module";
@@ -35,7 +35,7 @@ public class <%- polygene.serialization %>ValueSerializationModule
public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
throws AssemblyException
{
- new <%- polygene.serialization %>ValueSerializationAssembler()
+ new <%- polygene.serialization %>SerializationAssembler()
.visibleIn( Visibility.application )
.assemble( module );
return module;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/module.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/module.js b/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/module.js
index 7e60e99..4264bd4 100644
--- a/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/module.js
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/module.js
@@ -3,6 +3,6 @@ module.exports = {
write: function (p) {
p.copyTemplate(p.ctx,
'InfrastructureLayer/SerializationModule/bootstrap.tmpl',
- 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/infrastructure/' + p.serialization + 'ValueSerializationModule.java');
+ 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/infrastructure/' + p.serialization + 'SerializationModule.java');
}
};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/tools/generator-polygene/app/templates/InfrastructureLayer/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/bootstrap.tmpl
index cead6b3..1ba3098 100644
--- a/tools/generator-polygene/app/templates/InfrastructureLayer/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/bootstrap.tmpl
@@ -41,7 +41,7 @@ public class InfrastructureLayer extends LayeredLayerAssembler
throws AssemblyException
{
createModule( layer, FileConfigurationModule.class );
- createModule( layer, <%= polygene.serialization %>ValueSerializationModule.class );
+ createModule( layer, <%= polygene.serialization %>SerializationModule.class );
<% if( polygene.metrics !== "None" ) { %>
createModule( layer, <%= polygene.metrics %>MetricsModule.class );
<% } %>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/tools/generator-polygene/app/templates/buildtool/gradle-bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/buildtool/gradle-bootstrap.tmpl b/tools/generator-polygene/app/templates/buildtool/gradle-bootstrap.tmpl
index fa3630a..5815660 100644
--- a/tools/generator-polygene/app/templates/buildtool/gradle-bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/buildtool/gradle-bootstrap.tmpl
@@ -31,7 +31,7 @@ dependencies {
<% } %>
compile "org.apache.polygene.extensions:org.apache.polygene.extension.entitystore-<%= polygene.entitystore.toLowerCase() %>:$polygeneVersion"
compile "org.apache.polygene.extensions:org.apache.polygene.extension.indexing-<%= polygene.indexing.toLowerCase() %>:$polygeneVersion"
- compile "org.apache.polygene.extensions:org.apache.polygene.extension.valueserialization-<%= polygene.serialization.toLowerCase() %>:$polygeneVersion"
+ compile "org.apache.polygene.extensions:org.apache.polygene.extension.serialization-<%= polygene.serialization.toLowerCase() %>:$polygeneVersion"
<% if( polygene.caching !== "None" ) { %>
compile "org.apache.polygene.extensions:org.apache.polygene.extension.cache-<%= polygene.caching.toLowerCase() %>:$polygeneVersion"
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/tools/generator-polygene/test/generator_test.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/test/generator_test.js b/tools/generator-polygene/test/generator_test.js
index d5f2b58..0d0b938 100644
--- a/tools/generator-polygene/test/generator_test.js
+++ b/tools/generator-polygene/test/generator_test.js
@@ -38,9 +38,8 @@ var cachings = [
];
var serializations = [
- 'Jackson',
- // 'Johnzon',
- 'Stax'
+ 'JavaxJson',
+ 'JavaxXml'
];
var metricses = [
@@ -56,11 +55,11 @@ var featuresset = [
];
entityStores.forEach(function (entityStore) {
- test(entityStore, "Rdf", "Jackson", "Memcache", "Codahale", "[]");
+ test(entityStore, "Rdf", "JavaxJson", "Memcache", "Codahale", "[]");
});
indexings.forEach(function (indexing) {
- test("Memory", indexing, "Jackson", "Memcache", "Codahale", "[]");
+ test("Memory", indexing, "JavaxJson", "Memcache", "Codahale", "[]");
});
serializations.forEach(function (serialization) {
@@ -68,15 +67,15 @@ serializations.forEach(function (serialization) {
});
cachings.forEach(function (caching) {
- test("Memory", "Rdf", "Jackson", caching, "Codahale", "[]");
+ test("Memory", "Rdf", "JavaxJson", caching, "Codahale", "[]");
});
metricses.forEach(function (metrics) {
- test("Memory", "Rdf", "Jackson", "Memcache", metrics, "[]");
+ test("Memory", "Rdf", "JavaxJson", "Memcache", metrics, "[]");
});
featuresset.forEach(function (feature) {
- test("Memory", "Rdf", "Jackson", "Memcache", "Codahale", feature);
+ test("Memory", "Rdf", "JavaxJson", "Memcache", "Codahale", feature);
});
// All Tests !!!!
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/tools/model-detail/src/test/java/org/apache/polygene/tools/model/VisitableDetailTest.java
----------------------------------------------------------------------
diff --git a/tools/model-detail/src/test/java/org/apache/polygene/tools/model/VisitableDetailTest.java b/tools/model-detail/src/test/java/org/apache/polygene/tools/model/VisitableDetailTest.java
index d6af619..d06bc96 100644
--- a/tools/model-detail/src/test/java/org/apache/polygene/tools/model/VisitableDetailTest.java
+++ b/tools/model-detail/src/test/java/org/apache/polygene/tools/model/VisitableDetailTest.java
@@ -22,6 +22,7 @@ package org.apache.polygene.tools.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import org.apache.polygene.api.service.ServiceActivation;
import org.apache.polygene.tools.model.descriptor.ServiceDetailDescriptor;
import org.apache.polygene.tools.model.descriptor.TransientDetailDescriptor;
import org.junit.Test;
@@ -82,6 +83,7 @@ public class VisitableDetailTest
// Module
"visitEnter( ModuleName )",
"visit( " + ModuleActivator.class.getName() + " )",
+ "visit( " + ServiceActivation.ServiceActivator.class.getName() + " )",
// Leaving Structure
"visitLeave( ModuleName )",
"visitLeave( LayerName )",
[28/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueSerializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueSerializer.java b/core/spi/src/main/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueSerializer.java
deleted file mode 100644
index dbe658f..0000000
--- a/core/spi/src/main/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueSerializer.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.orgjson;
-
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.Writer;
-import org.json.JSONWriter;
-import org.apache.polygene.spi.value.ValueSerializerAdapter;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializer.OrgJsonOutput;
-
-/**
- * ValueSerializer producing Values state as JSON documents using org.json.
- */
-public class OrgJsonValueSerializer
- extends ValueSerializerAdapter<OrgJsonOutput>
-{
-
- /**
- * Helper to pass around the Writer alongside the JSONWriter so we can flush it onSerializationEnd.
- *
- * This is needed because the org.json package do not allow to get a handle on the Writer from a JSONWriter.
- */
- public static class OrgJsonOutput
- {
-
- private final Writer writer;
- private final JSONWriter json;
-
- private OrgJsonOutput( Writer writer, JSONWriter json )
- {
- this.writer = writer;
- this.json = json;
- }
- }
-
- //
- // Serialization
- //
- @Override
- protected OrgJsonOutput adaptOutput( OutputStream output )
- throws Exception
- {
- Writer writer = new OutputStreamWriter( output, "UTF-8" );
- JSONWriter json = new JSONWriter( writer );
- return new OrgJsonOutput( writer, json );
- }
-
- @Override
- protected void onSerializationEnd( Object object, OrgJsonOutput output )
- throws Exception
- {
- output.writer.flush();
- }
-
- @Override
- protected void onArrayStart( OrgJsonOutput output )
- throws Exception
- {
- output.json.array();
- }
-
- @Override
- protected void onArrayEnd( OrgJsonOutput output )
- throws Exception
- {
- output.json.endArray();
- }
-
- @Override
- protected void onObjectStart( OrgJsonOutput output )
- throws Exception
- {
- output.json.object();
- }
-
- @Override
- protected void onObjectEnd( OrgJsonOutput output )
- throws Exception
- {
- output.json.endObject();
- }
-
- @Override
- protected void onFieldStart( OrgJsonOutput output, String fieldName )
- throws Exception
- {
- output.json.key( fieldName );
- }
-
- @Override
- protected void onValue( OrgJsonOutput output, Object value )
- throws Exception
- {
- output.json.value( value );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/valueserialization/orgjson/package.html
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/valueserialization/orgjson/package.html b/core/spi/src/main/java/org/apache/polygene/valueserialization/orgjson/package.html
deleted file mode 100644
index 4799b58..0000000
--- a/core/spi/src/main/java/org/apache/polygene/valueserialization/orgjson/package.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one
- ~ or more contributor license agreements. See the NOTICE file
- ~ distributed with this work for additional information
- ~ regarding copyright ownership. The ASF licenses this file
- ~ to you under the Apache License, Version 2.0 (the
- ~ "License"); you may not use this file except in compliance
- ~ with the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- ~
- ~
- -->
-<html>
- <body>
- <h2>org.json Value Serialization.</h2>
- </body>
-</html>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/test/java/org/apache/polygene/spi/entitystore/Polygene142Test.java
----------------------------------------------------------------------
diff --git a/core/spi/src/test/java/org/apache/polygene/spi/entitystore/Polygene142Test.java b/core/spi/src/test/java/org/apache/polygene/spi/entitystore/Polygene142Test.java
index 718e3b7..831cc45 100644
--- a/core/spi/src/test/java/org/apache/polygene/spi/entitystore/Polygene142Test.java
+++ b/core/spi/src/test/java/org/apache/polygene/spi/entitystore/Polygene142Test.java
@@ -23,10 +23,10 @@ import org.apache.polygene.api.identity.StringIdentity;
import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.property.Property;
import org.apache.polygene.api.service.qualifier.Tagged;
+import org.apache.polygene.api.serialization.Serialization;
import org.apache.polygene.api.unitofwork.UnitOfWork;
import org.apache.polygene.api.usecase.UsecaseBuilder;
import org.apache.polygene.api.value.ValueBuilder;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.test.AbstractPolygeneTest;
import org.apache.polygene.test.EntityTestAssembler;
@@ -43,20 +43,13 @@ public class Polygene142Test extends AbstractPolygeneTest
}
@Service
- @Tagged( ValueSerialization.Formats.JSON )
- private ValueSerialization serialization;
+ @Tagged( Serialization.Formats.JSON )
+ private Serialization serialization;
@Test
public void polygene142RegressionTest()
throws Exception
{
- if( getClass().getName().equals(
- "org.apache.polygene.valueserialization.stax.StaxPlainValueSerializationTest" ) )
- {
- // This test is disabled, as this test expect a JSON capable serializer as it uses
- // the JSONMapEntityStoreMixin in MemoryEntityStore.
- return;
- }
Regression142Type value;
{
ValueBuilder<Regression142Type> builder = valueBuilderFactory.newValueBuilder( Regression142Type.class );
@@ -85,7 +78,7 @@ public class Polygene142Test extends AbstractPolygeneTest
}
}
{
- try( UnitOfWork uow = unitOfWorkFactory.newUnitOfWork( UsecaseBuilder.newUsecase( "create" ) ) )
+ try( UnitOfWork uow = unitOfWorkFactory.newUnitOfWork( UsecaseBuilder.newUsecase( "read" ) ) )
{
value = uow.get( Regression142Type.class, valueId );
System.out.println( value.price().get() );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/test/java/org/apache/polygene/spi/entitystore/helpers/JSONManyAssociationStateTest.java
----------------------------------------------------------------------
diff --git a/core/spi/src/test/java/org/apache/polygene/spi/entitystore/helpers/JSONManyAssociationStateTest.java b/core/spi/src/test/java/org/apache/polygene/spi/entitystore/helpers/JSONManyAssociationStateTest.java
index 9538042..67af1f8 100644
--- a/core/spi/src/test/java/org/apache/polygene/spi/entitystore/helpers/JSONManyAssociationStateTest.java
+++ b/core/spi/src/test/java/org/apache/polygene/spi/entitystore/helpers/JSONManyAssociationStateTest.java
@@ -21,12 +21,12 @@ package org.apache.polygene.spi.entitystore.helpers;
import java.util.ArrayList;
import java.util.List;
+import javax.json.Json;
+import javax.json.JsonObject;
+import javax.json.JsonObjectBuilder;
import org.apache.polygene.api.entity.EntityReference;
import org.apache.polygene.api.time.SystemTime;
import org.apache.polygene.spi.entity.EntityStatus;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
@@ -39,14 +39,14 @@ public class JSONManyAssociationStateTest
@Test
public void givenEmptyJSONManyAssociationStateWhenAddingTwoRefsAtZeroIndexExpectCorrectOrder()
- throws JSONException
{
// Fake JSONManyAssociationState
- JSONObject state = new JSONObject();
- state.put( JSONKeys.PROPERTIES, new JSONObject() );
- state.put( JSONKeys.ASSOCIATIONS, new JSONObject() );
- state.put( JSONKeys.MANY_ASSOCIATIONS, new JSONObject() );
- state.put( JSONKeys.NAMED_ASSOCIATIONS, new JSONObject() );
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ builder.add( JSONKeys.PROPERTIES, Json.createObjectBuilder().build() );
+ builder.add( JSONKeys.ASSOCIATIONS, Json.createObjectBuilder().build() );
+ builder.add( JSONKeys.MANY_ASSOCIATIONS, Json.createObjectBuilder().build() );
+ builder.add( JSONKeys.NAMED_ASSOCIATIONS, Json.createObjectBuilder().build() );
+ JsonObject state = builder.build();
JSONEntityState entityState = new JSONEntityState( null,
null,
"0",
@@ -55,7 +55,7 @@ public class JSONManyAssociationStateTest
EntityStatus.NEW,
null,
state );
- JSONManyAssociationState jsonState = new JSONManyAssociationState( entityState, new JSONArray() );
+ JSONManyAssociationState jsonState = new JSONManyAssociationState( entityState, "under-test" );
jsonState.add( 0, EntityReference.parseEntityReference( "first" ) );
jsonState.add( 0, EntityReference.parseEntityReference( "second" ) );
@@ -65,14 +65,14 @@ public class JSONManyAssociationStateTest
@Test
public void givenJSONManyAssociationStateWhenChangingReferencesExpectCorrectBehavior()
- throws JSONException
{
// Fake JSONManyAssociationState
- JSONObject state = new JSONObject();
- state.put( JSONKeys.PROPERTIES, new JSONObject() );
- state.put( JSONKeys.ASSOCIATIONS, new JSONObject() );
- state.put( JSONKeys.MANY_ASSOCIATIONS, new JSONObject() );
- state.put( JSONKeys.NAMED_ASSOCIATIONS, new JSONObject() );
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ builder.add( JSONKeys.PROPERTIES, Json.createObjectBuilder().build() );
+ builder.add( JSONKeys.ASSOCIATIONS, Json.createObjectBuilder().build() );
+ builder.add( JSONKeys.MANY_ASSOCIATIONS, Json.createObjectBuilder().build() );
+ builder.add( JSONKeys.NAMED_ASSOCIATIONS, Json.createObjectBuilder().build() );
+ JsonObject state = builder.build();
JSONEntityState entityState = new JSONEntityState( null,
null,
"0",
@@ -81,7 +81,7 @@ public class JSONManyAssociationStateTest
EntityStatus.NEW,
null,
state );
- JSONManyAssociationState jsonState = new JSONManyAssociationState( entityState, new JSONArray() );
+ JSONManyAssociationState jsonState = new JSONManyAssociationState( entityState, "under-test" );
assertThat( jsonState.contains( EntityReference.parseEntityReference( "NOT_PRESENT" ) ), is( false ) );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/test/java/org/apache/polygene/spi/entitystore/helpers/JsonNamedAssociationStateTest.java
----------------------------------------------------------------------
diff --git a/core/spi/src/test/java/org/apache/polygene/spi/entitystore/helpers/JsonNamedAssociationStateTest.java b/core/spi/src/test/java/org/apache/polygene/spi/entitystore/helpers/JsonNamedAssociationStateTest.java
new file mode 100644
index 0000000..8a4b7db
--- /dev/null
+++ b/core/spi/src/test/java/org/apache/polygene/spi/entitystore/helpers/JsonNamedAssociationStateTest.java
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.spi.entitystore.helpers;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import javax.json.Json;
+import javax.json.JsonObject;
+import javax.json.JsonObjectBuilder;
+import org.apache.polygene.api.entity.EntityReference;
+import org.apache.polygene.api.time.SystemTime;
+import org.apache.polygene.spi.entity.EntityStatus;
+import org.junit.Test;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.hasItems;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+public class JsonNamedAssociationStateTest
+{
+ @Test
+ public void givenJsonNamedAssociationStateWhenChangingReferencesExpectCorrectBehavior()
+ {
+ // Fake JsonNamedAssociationState
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ builder.add( JSONKeys.PROPERTIES, Json.createObjectBuilder().build() );
+ builder.add( JSONKeys.ASSOCIATIONS, Json.createObjectBuilder().build() );
+ builder.add( JSONKeys.MANY_ASSOCIATIONS, Json.createObjectBuilder().build() );
+ builder.add( JSONKeys.NAMED_ASSOCIATIONS, Json.createObjectBuilder().build() );
+ JsonObject state = builder.build();
+ JSONEntityState entityState = new JSONEntityState( null,
+ null,
+ "0",
+ SystemTime.now(),
+ EntityReference.parseEntityReference( "123" ),
+ EntityStatus.NEW,
+ null,
+ state );
+ JSONNamedAssociationState jsonState = new JSONNamedAssociationState( entityState, "under-test" );
+
+
+ assertThat( jsonState.containsName( "foo" ), is( false ) );
+
+ jsonState.put( "foo", EntityReference.parseEntityReference( "0" ) );
+ jsonState.put( "bar", EntityReference.parseEntityReference( "1" ) );
+ jsonState.put( "bazar", EntityReference.parseEntityReference( "2" ) );
+
+ assertThat( jsonState.containsName( "bar" ), is( true ) );
+
+ assertThat( jsonState.get( "foo" ).identity().toString(), equalTo( "0" ) );
+ assertThat( jsonState.get( "bar" ).identity().toString(), equalTo( "1" ) );
+ assertThat( jsonState.get( "bazar" ).identity().toString(), equalTo( "2" ) );
+
+ assertThat( jsonState.count(), equalTo( 3 ) );
+
+ jsonState.remove( "bar" );
+
+ assertThat( jsonState.count(), equalTo( 2 ) );
+ assertThat( jsonState.containsName( "bar" ), is( false ) );
+ assertThat( jsonState.get( "foo" ).identity().toString(), equalTo( "0" ) );
+ assertThat( jsonState.get( "bazar" ).identity().toString(), equalTo( "2" ) );
+
+ jsonState.put( "bar", EntityReference.parseEntityReference( "1" ) );
+
+ assertThat( jsonState.count(), equalTo( 3 ) );
+
+ jsonState.put( "oof", EntityReference.parseEntityReference( "A" ) );
+ jsonState.put( "rab", EntityReference.parseEntityReference( "B" ) );
+ jsonState.put( "razab", EntityReference.parseEntityReference( "C" ) );
+
+ assertThat( jsonState.count(), equalTo( 6 ) );
+
+ assertThat( jsonState.get( "razab" ).identity().toString(), equalTo( "C" ) );
+ assertThat( jsonState.get( "rab" ).identity().toString(), equalTo( "B" ) );
+ assertThat( jsonState.get( "oof" ).identity().toString(), equalTo( "A" ) );
+
+ Map<String, String> refMap = new LinkedHashMap<>();
+ for( String name : jsonState )
+ {
+ refMap.put( name, jsonState.get( name ).identity().toString() );
+ }
+ assertThat( refMap.isEmpty(), is( false ) );
+ assertThat( refMap.keySet(), hasItems( "foo", "bar", "bazar", "oof", "rab", "razab" ) );
+ assertThat( refMap.values(), hasItems( "0", "1", "2", "A", "B", "C" ) );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/testsupport/src/main/java/org/apache/polygene/test/EntityTestAssembler.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/EntityTestAssembler.java b/core/testsupport/src/main/java/org/apache/polygene/test/EntityTestAssembler.java
index 945ea47..ec7237b 100644
--- a/core/testsupport/src/main/java/org/apache/polygene/test/EntityTestAssembler.java
+++ b/core/testsupport/src/main/java/org/apache/polygene/test/EntityTestAssembler.java
@@ -19,16 +19,14 @@
*/
package org.apache.polygene.test;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.Assemblers;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.bootstrap.ServiceDeclaration;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
/**
- * Helper assembler that adds an in-memory EntityStore, a UUID generator, and an Entity type registry to the module
+ * Helper assembler that adds an in-memory EntityStore to the module
*/
public class EntityTestAssembler
extends Assemblers.VisibilityIdentity<EntityTestAssembler>
@@ -42,6 +40,5 @@ public class EntityTestAssembler
{
service.identifiedBy( identity() );
}
- module.services( OrgJsonValueSerializationService.class ).taggedWith( ValueSerialization.Formats.JSON );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/testsupport/src/main/java/org/apache/polygene/test/entity/AbstractConfigurationDeserializationTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/entity/AbstractConfigurationDeserializationTest.java b/core/testsupport/src/main/java/org/apache/polygene/test/entity/AbstractConfigurationDeserializationTest.java
index b50d96d..f8877c0 100644
--- a/core/testsupport/src/main/java/org/apache/polygene/test/entity/AbstractConfigurationDeserializationTest.java
+++ b/core/testsupport/src/main/java/org/apache/polygene/test/entity/AbstractConfigurationDeserializationTest.java
@@ -20,7 +20,6 @@
package org.apache.polygene.test.entity;
-import org.junit.Test;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.api.configuration.Configuration;
import org.apache.polygene.api.identity.HasIdentity;
@@ -28,12 +27,11 @@ import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.property.Property;
import org.apache.polygene.api.service.ServiceReference;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
import org.apache.polygene.test.AbstractPolygeneTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
+import org.junit.Test;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNull.notNullValue;
@@ -45,14 +43,11 @@ public abstract class AbstractConfigurationDeserializationTest extends AbstractP
public void assemble( ModuleAssembly module )
throws AssemblyException
{
-// ModuleAssembly storageModule = module.layer().module( "storage" );
- @SuppressWarnings( "UnnecessaryLocalVariable" )
- ModuleAssembly storageModule = module; // Disable the more complex set up. The entire value serialization has gotten the deserialization type lookup problem wrong.
+ ModuleAssembly storageModule = module.layer().module( "storage" );
module.configurations( ConfigSerializationConfig.class );
module.values( Host.class );
module.services( MyService.class ).identifiedBy( "configtest" );
storageModule.services( MemoryEntityStoreService.class ).visibleIn( Visibility.layer );
- storageModule.services( OrgJsonValueSerializationService.class ).taggedWith( ValueSerialization.Formats.JSON );
}
@Test
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/testsupport/src/main/java/org/apache/polygene/test/indexing/layered/assembly/PersistenceModule.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/indexing/layered/assembly/PersistenceModule.java b/core/testsupport/src/main/java/org/apache/polygene/test/indexing/layered/assembly/PersistenceModule.java
index 30f4be7..b0121c7 100644
--- a/core/testsupport/src/main/java/org/apache/polygene/test/indexing/layered/assembly/PersistenceModule.java
+++ b/core/testsupport/src/main/java/org/apache/polygene/test/indexing/layered/assembly/PersistenceModule.java
@@ -21,13 +21,11 @@
package org.apache.polygene.test.indexing.layered.assembly;
import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.LayerAssembly;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.bootstrap.layered.ModuleAssembler;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
class PersistenceModule
implements ModuleAssembler
@@ -37,7 +35,6 @@ class PersistenceModule
public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
throws AssemblyException
{
- module.services( OrgJsonValueSerializationService.class ).taggedWith( ValueSerialization.Formats.JSON );
module.services( MemoryEntityStoreService.class ).visibleIn( Visibility.application );
return module;
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractCollectionSerializationTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractCollectionSerializationTest.java b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractCollectionSerializationTest.java
new file mode 100644
index 0000000..474ed1a
--- /dev/null
+++ b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractCollectionSerializationTest.java
@@ -0,0 +1,481 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.test.serialization;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.EnumMap;
+import java.util.EnumSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.polygene.api.common.Optional;
+import org.apache.polygene.api.injection.scope.Service;
+import org.apache.polygene.api.property.Property;
+import org.apache.polygene.api.serialization.Serialization;
+import org.apache.polygene.api.type.CollectionType;
+import org.apache.polygene.api.type.EnumType;
+import org.apache.polygene.api.type.MapType;
+import org.apache.polygene.api.type.ValueCompositeType;
+import org.apache.polygene.api.type.ValueType;
+import org.apache.polygene.api.value.ValueBuilder;
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.test.AbstractPolygeneTest;
+import org.junit.Test;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Assert that ValueSerialization behaviour on Collections and Maps is correct.
+ */
+public class AbstractCollectionSerializationTest
+ extends AbstractPolygeneTest
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ throws AssemblyException
+ {
+ module.values( SomeValue.class );
+ }
+
+ @Service
+ @SuppressWarnings( "ProtectedField" )
+ protected Serialization stateSerialization;
+
+ @Test
+ public void givenPrimitiveArrayWithIntsWhenSerializingAndDeserializingExpectEquals()
+ throws Exception
+ {
+ int[] primitiveArray = new int[]
+ {
+ 23, 42, -23, -42
+ };
+ String output = stateSerialization.serialize( primitiveArray );
+ System.out.println( output );
+ int[] deserialized = stateSerialization.deserialize( module, int[].class, output );
+ assertArrayEquals( primitiveArray, deserialized );
+ }
+
+ @Test
+ public void givenArrayWithByteAndNullElementWhenSerializingAndDeserializingExpectEquals()
+ throws Exception
+ {
+ Byte[] array = new Byte[]
+ {
+ 9, null, -12, -12, 127, -128, 73
+ };
+ String output = stateSerialization.serialize( array );
+ System.out.println( output );
+ Byte[] deserialized = stateSerialization.deserialize( module, Byte[].class, output );
+ assertArrayEquals( array, deserialized );
+ }
+
+ @Test
+ public void givenIterableTypeWithByteAndNullElementWhenSerializingAndDeserializingExpectEquals()
+ throws Exception
+ {
+ String output = stateSerialization.serialize( new AdHocIterable<>( byteCollection() ) );
+ System.out.println( output );
+ CollectionType collectionType = CollectionType.listOf( ValueType.BYTE );
+ List<Byte> list = stateSerialization.deserialize( module, collectionType, output );
+ assertEquals( byteCollection(), list );
+ }
+
+ @Test
+ public void givenCollectionTypeWithByteAndNullElementWhenSerializingAndDeserializingExpectEquals()
+ throws Exception
+ {
+ String output = stateSerialization.serialize( byteCollection() );
+ System.out.println( output );
+ CollectionType collectionType = CollectionType.setOf( ValueType.BYTE );
+ Set<Byte> list = stateSerialization.deserialize( module, collectionType, output );
+ assertEquals( new LinkedHashSet<>( byteCollection() ), list );
+ }
+
+ @Test
+ public void givenCollectionTypeWithCharacterAndNullElementWhenSerializingAndDeserializingExpectEquals()
+ throws Exception
+ {
+ String output = stateSerialization.serialize( characterCollection() );
+ System.out.println( output );
+ CollectionType collectionType = CollectionType.listOf( ValueType.CHARACTER );
+ List<Character> list = stateSerialization.deserialize( module, collectionType, output );
+ assertEquals( characterCollection(), list );
+ }
+
+ @Test
+ public void givenCollectionTypeWithShortAndNullElementWhenSerializingAndDeserializingExpectEquals()
+ throws Exception
+ {
+ String output = stateSerialization.serialize( shortCollection() );
+ System.out.println( output );
+ CollectionType collectionType = CollectionType.listOf( ValueType.SHORT );
+ List<Short> list = stateSerialization.deserialize( module, collectionType, output );
+ assertEquals( shortCollection(), list );
+ }
+
+ @Test
+ public void givenCollectionTypeWithIntegerAndNullElementWhenSerializingAndDeserializingExpectEquals()
+ throws Exception
+ {
+ String output = stateSerialization.serialize( integerCollection() );
+ System.out.println( output );
+ CollectionType collectionType = CollectionType.listOf( ValueType.INTEGER );
+ List<Integer> list = stateSerialization.deserialize( module, collectionType, output );
+ assertEquals( integerCollection(), list );
+ }
+
+ @Test
+ public void givenCollectionTypeWithLongAndNullElementWhenSerializingAndDeserializingExpectEquals()
+ throws Exception
+ {
+ String output = stateSerialization.serialize( longCollection() );
+ System.out.println( output );
+ CollectionType collectionType = CollectionType.listOf( ValueType.LONG );
+ List<Long> list = stateSerialization.deserialize( module, collectionType, output );
+ assertEquals( longCollection(), list );
+ }
+
+ @Test
+ public void givenCollectionTypeWithFloatAndNullElementWhenSerializingAndDeserializingExpectEquals()
+ throws Exception
+ {
+ String output = stateSerialization.serialize( floatCollection() );
+ System.out.println( output );
+ CollectionType collectionType = CollectionType.listOf( ValueType.FLOAT );
+ List<Float> list = stateSerialization.deserialize( module, collectionType, output );
+ assertEquals( floatCollection(), list );
+ }
+
+ @Test
+ public void givenCollectionTypeWithDoubleAndNullElementWhenSerializingExpectCorrectJsonOutput()
+ throws Exception
+ {
+ String output = stateSerialization.serialize( doubleCollection() );
+ System.out.println( output );
+ CollectionType collectionType = CollectionType.listOf( ValueType.DOUBLE );
+ List<Double> list = stateSerialization.deserialize( module, collectionType, output );
+ assertEquals( doubleCollection(), list );
+ }
+
+ @Test
+ public void givenCollectionTypeWithBigIntegerAndNullElementWhenSerializingAndDeserializingExpectEquals()
+ throws Exception
+ {
+ String output = stateSerialization.serialize( bigIntegerCollection() );
+ System.out.println( output );
+ CollectionType collectionType = CollectionType.listOf( ValueType.BIG_INTEGER );
+ List<BigInteger> list = stateSerialization.deserialize( module, collectionType, output );
+ assertEquals( bigIntegerCollection(), list );
+ }
+
+ @Test
+ public void givenCollectionTypeWithBigDecimalAndNullElementWhenSerializingAndDeserializingExpectEquals()
+ throws Exception
+ {
+ String output = stateSerialization.serialize( bigDecimalCollection() );
+ System.out.println( output );
+ CollectionType collectionType = CollectionType.collectionOf( ValueType.BIG_DECIMAL );
+ Collection<BigDecimal> collection = stateSerialization.deserialize( module, collectionType, output );
+ assertEquals( bigDecimalCollection(), collection );
+ }
+
+ @Test
+ public void givenMapOfStringByteAndNullElementWhenSerializingAndDeserializingExpectEquals()
+ throws Exception
+ {
+ String output = stateSerialization.serialize( stringByteMap() );
+ System.out.println( output );
+ MapType mapType = MapType.of( ValueType.STRING, ValueType.BYTE );
+ Map<String, Byte> value = stateSerialization.deserialize( module, mapType, output );
+ assertEquals( stringByteMap(), value );
+ }
+
+ @Test
+ public void givenMapOfStringListStringAndNullElementWhenSerializingAndDeserializingExpectEquals()
+ throws Exception
+ {
+ String output = stateSerialization.serialize( stringMultiMap() );
+ System.out.println( output );
+ CollectionType collectionType = CollectionType.listOf( ValueType.STRING );
+ MapType mapType = MapType.of( ValueType.STRING, collectionType );
+ Map<String, List<String>> value = stateSerialization.deserialize( module, mapType, output );
+ assertEquals( stringMultiMap(), value );
+ }
+
+ @Test
+ public void givenListOfMapStringStringAndNullElementWhenSerializingAndDeserializingExpectEquals()
+ throws Exception
+ {
+ String output = stateSerialization.serialize( stringListOfMaps() );
+ System.out.println( output );
+ CollectionType collectionType = CollectionType.listOf( MapType.of( ValueType.STRING, ValueType.STRING ) );
+ List<Map<String, String>> value = stateSerialization.deserialize( module, collectionType, output );
+ assertEquals( stringListOfMaps(), value );
+ }
+
+ @Test
+ public void givenListOfValueCompositesAndNullElementWhenSerializingAndDeserializingExpectEquals()
+ throws Exception
+ {
+ String output = stateSerialization.serialize( valueCompositesList() );
+ System.out.println( output );
+ ValueCompositeType valueType = module.valueDescriptor( SomeValue.class.getName() ).valueType();
+ CollectionType collectionType = CollectionType.listOf( valueType );
+ List<SomeValue> value = stateSerialization.deserialize( module, collectionType, output );
+ assertEquals( valueCompositesList(), value );
+ }
+
+ @Test
+ public void givenEnumSetWhenSerializingAndDeserializingExpectEquals()
+ {
+ Set<SomeEnum> enumSet = EnumSet.allOf( SomeEnum.class );
+ String output = stateSerialization.serialize( enumSet );
+ System.out.println( output );
+ CollectionType valueType = CollectionType.setOf( EnumType.of( SomeEnum.class ) );
+ Set<SomeEnum> value = stateSerialization.deserialize( module, valueType, output );
+ assertEquals( enumSet, value );
+ }
+
+ @Test
+ public void givenEnumMapWhenSerializingAndDeserializingExpectEquals()
+ {
+ EnumMap<SomeEnum, Number> enumMap = new EnumMap<>( SomeEnum.class );
+ for( SomeEnum value : SomeEnum.values() )
+ {
+ enumMap.put( value, 23 );
+ }
+ String output = stateSerialization.serialize( enumMap );
+ System.out.println( output );
+ MapType valueType = MapType.of( EnumType.of( SomeEnum.class ), ValueType.of( Integer.class ) );
+ Map<SomeEnum, Number> value = stateSerialization.deserialize( module, valueType, output );
+ assertEquals( enumMap, value );
+ }
+
+ private ArrayList<Byte> byteCollection()
+ {
+ ArrayList<Byte> value = new ArrayList<>();
+ value.add( (byte) 9 );
+ value.add( null );
+ value.add( (byte) -12 );
+ value.add( (byte) -12 );
+ value.add( (byte) 127 );
+ value.add( (byte) -128 );
+ value.add( (byte) 73 );
+ return value;
+ }
+
+ private List<Character> characterCollection()
+ {
+ List<Character> value = new ArrayList<>();
+ value.add( 'Q' );
+ value.add( 'i' );
+ value.add( null );
+ value.add( '4' );
+ value.add( 'j' );
+ return value;
+ }
+
+ private Collection<Short> shortCollection()
+ {
+ Collection<Short> value = new ArrayList<>();
+ value.add( (short) -32768 );
+ value.add( (short) 32767 );
+ value.add( (short) -82 );
+ value.add( null );
+ return value;
+ }
+
+ private Collection<Integer> integerCollection()
+ {
+ Collection<Integer> value = new ArrayList<>();
+ value.add( Integer.MAX_VALUE );
+ value.add( -283 );
+ value.add( null );
+ value.add( Integer.MIN_VALUE );
+ value.add( 238 );
+ return value;
+ }
+
+ private Collection<Long> longCollection()
+ {
+ Collection<Long> value = new ArrayList<>();
+ value.add( 98239723L );
+ value.add( -1298233L );
+ value.add( -1L );
+ value.add( 0L );
+ value.add( null );
+ value.add( 1L );
+ value.add( Long.MAX_VALUE );
+ value.add( Long.MIN_VALUE );
+ return value;
+ }
+
+ private Collection<Float> floatCollection()
+ {
+ Collection<Float> value = new ArrayList<>();
+ value.add( -1f );
+ value.add( 1f );
+ value.add( 1f );
+ value.add( 0f );
+ value.add( Float.MAX_VALUE );
+ value.add( Float.MIN_VALUE );
+ value.add( null );
+ value.add( 0.123456f );
+ value.add( -0.232321f );
+ return value;
+ }
+
+ private Collection<Double> doubleCollection()
+ {
+ Collection<Double> value = new ArrayList<>();
+ value.add( -1.0 );
+ value.add( 1.0 );
+ value.add( 0.0 );
+ value.add( Double.MAX_VALUE );
+ value.add( null );
+ value.add( Double.MIN_VALUE );
+ value.add( 0.123456 );
+ value.add( -0.232321 );
+ return value;
+ }
+
+ private Collection<BigInteger> bigIntegerCollection()
+ {
+ Collection<BigInteger> value = new ArrayList<>();
+ value.add( new BigInteger( "-1" ) );
+ value.add( BigInteger.ZERO );
+ value.add( BigInteger.ONE );
+ value.add( null );
+ value.add( BigInteger.TEN );
+ value.add( new BigInteger( "-1827368263823729372397239829332" ) );
+ value.add( new BigInteger( "2398723982982379827373972398723" ) );
+ return value;
+ }
+
+ private Collection<BigDecimal> bigDecimalCollection()
+ {
+ Collection<BigDecimal> value = new ArrayList<>();
+ value.add( new BigDecimal( "1.2" ) );
+ value.add( new BigDecimal( "3.4" ) );
+ value.add( null );
+ value.add( new BigDecimal( "5.6" ) );
+ return value;
+ }
+
+ private Map<String, Byte> stringByteMap()
+ {
+ Map<String, Byte> value = new LinkedHashMap<>();
+ value.put( "a", (byte) 9 );
+ value.put( "b", null );
+ value.put( "c", (byte) -12 );
+ return value;
+ }
+
+ private Map<String, List<String>> stringMultiMap()
+ {
+ Map<String, List<String>> value = new LinkedHashMap<>();
+ List<String> list = new ArrayList<>();
+ list.add( "foo" );
+ list.add( "bar" );
+ list.add( null );
+ list.add( "cathedral" );
+ list.add( "bazar" );
+ value.put( "alpha", list );
+ value.put( "beta", null );
+ value.put( "gamma", Collections.emptyList() );
+ return value;
+ }
+
+ private List<Map<String, String>> stringListOfMaps()
+ {
+ List<Map<String, String>> value = new ArrayList<>();
+ Map<String, String> map = new LinkedHashMap<>();
+ map.put( "foo", "bar" );
+ map.put( "cathedral", "bazar" );
+ map.put( "yield", null );
+ map.put( "42", "23" );
+ value.add( map );
+ value.add( null );
+ value.add( Collections.emptyMap() );
+ return value;
+ }
+
+ private List<SomeValue> valueCompositesList()
+ {
+ List<SomeValue> list = new ArrayList<>();
+ list.add( newSomeValue( "", "bazar" ) );
+ list.add( null );
+ list.add( newSomeValue( "bar", null ) );
+ return list;
+ }
+
+ public interface SomeValue
+ {
+ Property<String> foo();
+
+ @Optional
+ Property<String> cathedral();
+ }
+
+ private SomeValue newSomeValue( String foo, String cathedral )
+ {
+ ValueBuilder<SomeValue> builder = module.instance().newValueBuilder( SomeValue.class );
+ SomeValue value = builder.prototype();
+ value.foo().set( foo );
+ if( cathedral != null )
+ {
+ value.cathedral().set( cathedral );
+ }
+ return builder.newInstance();
+ }
+
+ private static class AdHocIterable<T> implements Iterable<T>
+ {
+ private final Iterable<T> delegate;
+
+ private AdHocIterable( Iterable<T> delegate )
+ {
+ this.delegate = delegate;
+ }
+
+ @Override
+ public Iterator<T> iterator()
+ {
+ return delegate.iterator();
+ }
+ }
+
+ private enum SomeEnum
+ {
+ FOO,
+ BAR,
+ BAZAR,
+ CATHEDRAL
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractDateFormatSerializationTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractDateFormatSerializationTest.java b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractDateFormatSerializationTest.java
new file mode 100644
index 0000000..27b5289
--- /dev/null
+++ b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractDateFormatSerializationTest.java
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.test.serialization;
+
+import java.time.Duration;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.OffsetDateTime;
+import java.time.Period;
+import java.time.ZoneId;
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
+import java.util.List;
+import org.apache.polygene.api.injection.scope.Service;
+import org.apache.polygene.api.serialization.Serialization;
+import org.apache.polygene.api.type.CollectionType;
+import org.apache.polygene.api.type.ValueType;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.test.AbstractPolygeneTest;
+import org.junit.Test;
+
+import static org.hamcrest.core.IsEqual.equalTo;
+import static org.junit.Assert.assertThat;
+
+/**
+ * Assert that a serialization support various date formats.
+ */
+@SuppressWarnings( "ProtectedField" )
+public class AbstractDateFormatSerializationTest
+ extends AbstractPolygeneTest
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ }
+
+ @Service
+ protected Serialization stateSerialization;
+
+ @Test
+ public void givenLocalDateTimeFormatWhenConvertingFromSerializedStateExpectValidDate()
+ throws Exception
+ {
+ CollectionType collectionType = CollectionType.listOf( ValueType.LOCAL_DATE_TIME );
+ List<LocalDateTime> value = stateSerialization.deserialize( module, collectionType,
+ "[\"2009-08-12T14:54:27\"]" );
+ LocalDateTime expected = LocalDateTime.of( 2009, 8, 12, 14, 54, 27 );
+ assertThat( value.get( 0 ), equalTo( expected ) );
+ }
+
+ @Test
+ public void givenLocalDateFormatWhenConvertingFromSerializedStateExpectValidDate()
+ throws Exception
+ {
+ CollectionType collectionType = CollectionType.listOf( ValueType.LOCAL_DATE );
+ List<LocalDate> value = stateSerialization.deserialize( module, collectionType, "[\"2009-08-12\"]" );
+ LocalDate expected = LocalDate.of( 2009, 8, 12 );
+ assertThat( value.get( 0 ), equalTo( expected ) );
+ }
+
+ @Test
+ public void givenLocalTimeFormatWhenConvertingFromSerializedStateExpectValidDate()
+ throws Exception
+ {
+ CollectionType collectionType = CollectionType.listOf( ValueType.LOCAL_TIME );
+ List<LocalTime> value = stateSerialization.deserialize( module, collectionType, "[\"14:54:27\"]" );
+ LocalTime expected = LocalTime.of( 14, 54, 27 );
+ assertThat( value.get( 0 ), equalTo( expected ) );
+ }
+
+ @Test
+ public void givenOffsetDateTimeFormatWhenConvertingFromSerializedStateExpectValidDate()
+ throws Exception
+ {
+ CollectionType collectionType = CollectionType.listOf( ValueType.OFFSET_DATE_TIME );
+ List<OffsetDateTime> value = stateSerialization.deserialize( module, collectionType,
+ "[\"2009-08-12T14:54:27.895+08:00\"]" );
+ OffsetDateTime expected = OffsetDateTime.of( 2009, 8, 12, 14, 54, 27, 895000000, ZoneOffset.ofHours( 8 ) );
+ assertThat( value.get( 0 ), equalTo( expected ) );
+ }
+
+ @Test
+ public void givenZonedDateTimeFormatWhenConvertingFromSerializedStateExpectValidDate()
+ throws Exception
+ {
+ CollectionType collectionType = CollectionType.listOf( ValueType.ZONED_DATE_TIME );
+ List<ZonedDateTime> value = stateSerialization.deserialize( module, collectionType,
+ "[\"2009-08-12T14:54:27.895+02:00[CET]\"]" );
+ ZonedDateTime expected = ZonedDateTime.of( 2009, 8, 12, 14, 54, 27, 895000000, ZoneId.of( "CET" ) );
+ assertThat( value.get( 0 ), equalTo( expected ) );
+ }
+
+ @Test
+ public void givenInstantFormatWhenConvertingFromSerializedStateExpectValidDate()
+ throws Exception
+ {
+ CollectionType collectionType = CollectionType.listOf( ValueType.INSTANT );
+ List<Instant> value = stateSerialization.deserialize( module, collectionType,
+ "[\"2016-06-11T08:47:12.620Z\"]" );
+ Instant expected = Instant.parse( "2016-06-11T08:47:12.620Z" );
+ assertThat( value.get( 0 ), equalTo( expected ) );
+ }
+
+ @Test
+ public void givenDurationFormatWhenConvertingFromSerializedStateExpectValidDate()
+ throws Exception
+ {
+ CollectionType collectionType = CollectionType.listOf( ValueType.DURATION );
+ List<Duration> value = stateSerialization.deserialize( module, collectionType, "[\"PT3.5S\"]" );
+ Duration expected = Duration.ofMillis( 3500 );
+ assertThat( value.get( 0 ), equalTo( expected ) );
+ }
+
+ @Test
+ public void givenPeriodFormatWhenConvertingFromSerializedStateExpectValidDate()
+ throws Exception
+ {
+ CollectionType collectionType = CollectionType.listOf( ValueType.PERIOD );
+ List<Period> value = stateSerialization.deserialize( module, collectionType, "[\"P3Y5M13D\"]" );
+ Period expected = Period.of( 3, 5, 13 );
+ assertThat( value.get( 0 ), equalTo( expected ) );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractPlainValueSerializationTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractPlainValueSerializationTest.java b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractPlainValueSerializationTest.java
new file mode 100644
index 0000000..7e72ff1
--- /dev/null
+++ b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractPlainValueSerializationTest.java
@@ -0,0 +1,259 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.test.serialization;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
+import org.apache.polygene.api.entity.EntityReference;
+import org.apache.polygene.api.injection.scope.Service;
+import org.apache.polygene.api.serialization.Serialization;
+import org.apache.polygene.api.type.EnumType;
+import org.apache.polygene.api.type.ValueType;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.test.AbstractPolygeneTest;
+import org.junit.Test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.core.IsEqual.equalTo;
+import static org.hamcrest.core.IsNot.not;
+import static org.junit.Assert.assertThat;
+
+/**
+ * Assert that ValueSerialization behaviour on plain values is correct.
+ */
+public abstract class AbstractPlainValueSerializationTest
+ extends AbstractPolygeneTest
+{
+ @Service
+ protected Serialization stateSerialization;
+
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ }
+
+ @Test
+ public void givenEmptyStateStringWhenDeserializingExpectSuccesses()
+ {
+ assertThat( stateSerialization.deserialize( module, ValueType.of( Integer.class ), "" ), is( 0 ) );
+ assertThat( stateSerialization.deserialize( module, ValueType.of( String.class ), "" ), equalTo( "" ) );
+ }
+
+ @Test
+ public void givenNullValueWhenSerializingAndDeserializingExpectNull()
+ {
+ String output = stateSerialization.serialize( null );
+ System.out.println( output );
+ assertThat( stateSerialization.deserialize( module, ValueType.of( Integer.class ), output ), nullValue() );
+ assertThat( stateSerialization.deserialize( module, ValueType.of( String.class ), output ), nullValue() );
+ assertThat( stateSerialization.deserialize( module, ValueType.of( SomeEnum.class ), output ), nullValue() );
+ }
+
+ @Test
+ public void givenEnumValueWhenSerializingAndDeserializingExpectEquals()
+ {
+ String output = stateSerialization.serialize( SomeEnum.B�R );
+ System.out.println( output );
+ SomeEnum value = stateSerialization.deserialize( module, EnumType.of( SomeEnum.class ), output );
+ assertThat( value, is( SomeEnum.B�R ) );
+ }
+
+ @Test
+ public void givenCharacterValueWhenSerializingAndDeserializingExpectEquals()
+ {
+ String serialized = stateSerialization.serialize( '\u222b' );
+ System.out.println(serialized);
+ assertThat( "Serialized", serialized, equalTo( "\u222b" ) );
+
+ Character deserialized = stateSerialization.deserialize( module, Character.class, serialized );
+ assertThat( "Deserialized", deserialized, equalTo( '\u222b' ) );
+
+ deserialized = stateSerialization.deserialize( module, char.class, serialized );
+ assertThat( "Deserialized", deserialized, equalTo( '\u222b' ) );
+ }
+
+ @Test
+ public void givenEmptyStringValueWhenSerializingAndDeserializingExpectEquals()
+ {
+ String serialized = stateSerialization.serialize( "" );
+ assertThat( "Serialized", serialized, equalTo( "" ) );
+
+ String deserialized = stateSerialization.deserialize( module, String.class, serialized );
+ assertThat( "Deserialized", deserialized, equalTo( "" ) );
+ }
+
+ @Test
+ public void givenStringValueWhenSerializingAndDeserializingExpectEquals()
+ {
+ String serialized = stateSerialization.serialize( "�\u222b" );
+ assertThat( serialized, equalTo( "�\u222b" ) );
+
+ String deserialized = stateSerialization.deserialize( module, String.class, serialized );
+ assertThat( deserialized, equalTo( "�\u222b" ) );
+ }
+
+ @Test
+ public void givenBooleanValueWhenSerializingAndDeserializingExpectEquals()
+ {
+ String serialized = stateSerialization.serialize( true );
+ assertThat( serialized, equalTo( "true" ) );
+
+ Boolean deserialized = stateSerialization.deserialize( module, Boolean.class, serialized );
+ assertThat( deserialized, equalTo( Boolean.TRUE ) );
+ }
+
+ @Test
+ public void givenIntegerValueWhenSerializingAndDeserializingExpectEquals()
+ {
+ String serialized = stateSerialization.serialize( 42 );
+ assertThat( serialized, equalTo( "42" ) );
+ Integer deserialized = stateSerialization.deserialize( module, Integer.class, serialized );
+ assertThat( deserialized, equalTo( 42 ) );
+ }
+
+ @Test
+ public void givenLongValueWhenSerializingAndDeserializingExpectEquals()
+ {
+ String serialized = stateSerialization.serialize( 42L );
+ assertThat( serialized, equalTo( "42" ) );
+
+ Long deserialized = stateSerialization.deserialize( module, Long.class, serialized );
+ assertThat( deserialized, equalTo( 42L ) );
+ }
+
+ @Test
+ public void givenShortValueWhenSerializingAndDeserializingExpectEquals()
+ {
+ String serialized = stateSerialization.serialize( (short) 42 );
+ assertThat( serialized, equalTo( "42" ) );
+
+ Short deserialized = stateSerialization.deserialize( module, Short.class, serialized );
+ assertThat( deserialized, equalTo( (short) 42 ) );
+ }
+
+ @Test
+ public void givenByteValueWhenSerializingAndDeserializingExpectEquals()
+ {
+ String serialized = stateSerialization.serialize( (byte) 42 );
+ assertThat( serialized, equalTo( "42" ) );
+ Byte deserialized = stateSerialization.deserialize( module, Byte.class, serialized );
+ assertThat( deserialized, equalTo( (byte) 42 ) );
+ }
+
+ @Test
+ public void givenFloatValueWhenSerializingAndDeserializingExpectEquals()
+ {
+ String serialized = stateSerialization.serialize( 42F );
+ assertThat( serialized, equalTo( "42.0" ) );
+
+ Float deserialized = stateSerialization.deserialize( module, Float.class, serialized );
+ assertThat( deserialized, equalTo( 42F ) );
+ }
+
+ @Test
+ public void givenDoubleValueWhenSerializingAndDeserializingExpectEquals()
+ {
+ String serialized = stateSerialization.serialize( 42D );
+ assertThat( serialized, equalTo( "42.0" ) );
+
+ Double deserialized = stateSerialization.deserialize( module, Double.class, serialized );
+ assertThat( deserialized, equalTo( 42D ) );
+ }
+
+ @Test
+ public void givenBigIntegerValueWhenSerializingAndDeserializingExpectEquals()
+ {
+ BigInteger bigInteger = new BigInteger( "42424242424242424242424242" );
+ assertThat( bigInteger, not( equalTo( BigInteger.valueOf( bigInteger.longValue() ) ) ) );
+
+ String serialized = stateSerialization.serialize( bigInteger );
+ assertThat( serialized, equalTo( "42424242424242424242424242" ) );
+
+ BigInteger deserialized = stateSerialization.deserialize( module, BigInteger.class, serialized );
+ assertThat( deserialized, equalTo( bigInteger ) );
+ }
+
+ @Test
+ public void givenBigDecimalValueWhenSerializingAndDeserializingExpectEquals()
+ {
+ BigDecimal bigDecimal = new BigDecimal( "42.2376931348623157e+309" );
+ assertThat( bigDecimal.doubleValue(), equalTo( Double.POSITIVE_INFINITY ) );
+
+ String serialized = stateSerialization.serialize( bigDecimal );
+ assertThat( serialized, equalTo( "4.22376931348623157E+310" ) );
+
+ BigDecimal deserialized = stateSerialization.deserialize( module, BigDecimal.class, serialized );
+ assertThat( deserialized, equalTo( bigDecimal ) );
+ }
+
+ @Test
+ public void givenDateTimeValueWhenSerializingAndDeserializingExpectEquals()
+ {
+ String serialized = stateSerialization.serialize(
+ OffsetDateTime.of( 2020, 3, 4, 13, 24, 35, 123000000, ZoneOffset.ofHours( 1 ) ) );
+ assertThat( serialized, equalTo( "2020-03-04T13:24:35.123+01:00" ) );
+ ZonedDateTime deserialized = stateSerialization.deserialize( module, ZonedDateTime.class, serialized );
+ assertThat( deserialized,
+ equalTo( ZonedDateTime.of( 2020, 3, 4, 13, 24, 35, 123000000, ZoneOffset.ofHours( 1 ) ) ) );
+ }
+
+ @Test
+ public void givenLocalDateTimeValueWhenSerializingAndDeserializingExpectEquals()
+ {
+ // Serialized without TimeZone
+ String serialized = stateSerialization.serialize( LocalDateTime.of( 2020, 3, 4, 13, 23, 12 ) );
+ assertThat( serialized, equalTo( "2020-03-04T13:23:12" ) );
+
+ LocalDateTime deserialized = stateSerialization.deserialize( module, LocalDateTime.class, serialized );
+ assertThat( deserialized, equalTo( LocalDateTime.of( 2020, 3, 4, 13, 23, 12 ) ) );
+ }
+
+ @Test
+ public void givenLocalDateValueWhenSerializingAndDeserializingExpectEquals()
+ {
+ String serialized = stateSerialization.serialize( LocalDate.of( 2020, 3, 4 ) );
+ assertThat( serialized, equalTo( "2020-03-04" ) );
+
+ LocalDate deserialized = stateSerialization.deserialize( module, LocalDate.class, serialized );
+ assertThat( deserialized, equalTo( LocalDate.of( 2020, 3, 4 ) ) );
+ }
+
+ @Test
+ public void givenEntityReferenceValueWhenSerializingAndDeserializingExpectEquals()
+ {
+ String serialized = stateSerialization.serialize( EntityReference.parseEntityReference( "ABCD-1234" ) );
+ assertThat( serialized, equalTo( "ABCD-1234" ) );
+
+ EntityReference deserialized = stateSerialization.deserialize( module, EntityReference.class, serialized );
+ assertThat( deserialized, equalTo( EntityReference.parseEntityReference( "ABCD-1234" ) ) );
+ }
+
+ private enum SomeEnum
+ {
+ B�R,
+ BAZAR
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
new file mode 100644
index 0000000..121fe21
--- /dev/null
+++ b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
@@ -0,0 +1,521 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.test.serialization;
+
+import java.io.Serializable;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import org.apache.polygene.api.association.Association;
+import org.apache.polygene.api.association.ManyAssociation;
+import org.apache.polygene.api.association.NamedAssociation;
+import org.apache.polygene.api.common.Optional;
+import org.apache.polygene.api.common.UseDefaults;
+import org.apache.polygene.api.common.Visibility;
+import org.apache.polygene.api.entity.EntityBuilder;
+import org.apache.polygene.api.entity.EntityComposite;
+import org.apache.polygene.api.entity.EntityReference;
+import org.apache.polygene.api.identity.HasIdentity;
+import org.apache.polygene.api.identity.Identity;
+import org.apache.polygene.api.identity.StringIdentity;
+import org.apache.polygene.api.injection.scope.Service;
+import org.apache.polygene.api.injection.scope.Structure;
+import org.apache.polygene.api.injection.scope.This;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.property.Property;
+import org.apache.polygene.api.serialization.Serialization;
+import org.apache.polygene.api.structure.Module;
+import org.apache.polygene.api.unitofwork.UnitOfWork;
+import org.apache.polygene.api.value.ValueBuilder;
+import org.apache.polygene.api.value.ValueComposite;
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.test.AbstractPolygeneTest;
+import org.apache.polygene.test.EntityTestAssembler;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestName;
+
+import static org.apache.polygene.api.usecase.UsecaseBuilder.newUsecase;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+/**
+ * Assert that ValueSerialization behaviour on ValueComposites is correct.
+ */
+// TODO Assert Arrays behaviour!
+// TODO Assert Generics behaviour!
+public abstract class AbstractValueCompositeSerializationTest
+ extends AbstractPolygeneTest
+{
+ @Rule
+ public TestName testName = new TestName();
+
+ @Before
+ public void before()
+ {
+ System.out.println( "# BEGIN " + testName.getMethodName() );
+ }
+
+ @After
+ public void after()
+ {
+ System.out.println( "# END " + testName.getMethodName() );
+ }
+
+ @Structure
+ protected Module moduleInstance;
+
+ @Override
+ public void assemble( ModuleAssembly module )
+ throws AssemblyException
+ {
+ module.values( Some.class, AnotherValue.class, FooValue.class, CustomFooValue.class,
+ SpecificCollection.class /*, SpecificValue.class, GenericValue.class */ );
+
+ new EntityTestAssembler().visibleIn( Visibility.layer ).assemble( module.layer().module( "persistence" ) );
+ module.entities( Some.class, BarEntity.class );
+ }
+
+ @Service
+ protected Serialization serialization;
+
+ @Test
+ public void givenValueCompositeWhenSerializingAndDeserializingExpectEquals()
+ throws Exception
+ {
+ try( UnitOfWork uow = unitOfWorkFactory.newUnitOfWork() )
+ {
+ Some some = buildSomeValue( moduleInstance, uow, "23" );
+
+ // Serialize using injected service
+ String stateString = serialization.serialize( some );
+ System.out.println( stateString );
+
+ // Deserialize using Module API
+ Some some2 = moduleInstance.newValueFromSerializedState( Some.class, stateString );
+
+ assertThat( "Map<String, Integer>",
+ some2.stringIntMap().get().get( "foo" ),
+ equalTo( 42 ) );
+ assertThat( "Map<String, Value>",
+ some2.stringValueMap().get().get( "foo" ).internalVal(),
+ equalTo( "Bar" ) );
+
+ assertThat( "Nested Entities",
+ some2.barAssociation().get().cathedral().get(),
+ equalTo( "bazar in barAssociation" ) );
+
+ assertThat( "Polymorphic deserialization of value type NOT extending ValueComposite",
+ some.customFoo().get() instanceof CustomFooValue,
+ is( true ) );
+ assertThat( "Polymorphic deserialization of value type extending ValueComposite",
+ some.customFooValue().get() instanceof CustomFooValue,
+ is( true ) );
+
+ assertThat( "Value equality", some, equalTo( some2 ) );
+ }
+ }
+
+ @Test
+ @Ignore( "JSONEntityState cannot handle polymorphic deserialization" )
+ // TODO Entity == Identity + Value
+ // JSONEntityState does not allow for polymorphic serialization
+ public void valueAndEntityTypeEquality()
+ {
+ Identity identity = StringIdentity.fromString( "42" );
+ Some createdValue, loadedValue;
+
+ try( UnitOfWork uow = unitOfWorkFactory.newUnitOfWork( newUsecase( "create" ) ) )
+ {
+ Some entity = buildSomeEntity( moduleInstance, uow, identity );
+ createdValue = uow.toValue( Some.class, entity );
+ System.out.println( "Created Entity\n\t" + entity + "\nCreated Value\n\t" + createdValue );
+ uow.complete();
+ }
+ try( UnitOfWork uow = unitOfWorkFactory.newUnitOfWork( newUsecase( "load" ) ) )
+ {
+ Some entity = uow.get( Some.class, identity );
+ loadedValue = uow.toValue( Some.class, entity );
+ System.out.println( "Loaded Entity\n\t" + entity + "\nLoaded Value\n\t" + loadedValue );
+ }
+
+ assertThat( "Create/Read equality",
+ createdValue, equalTo( loadedValue ) );
+
+ try( UnitOfWork uow = unitOfWorkFactory.newUnitOfWork( newUsecase( "remove" ) ) )
+ {
+ uow.remove( uow.get( Some.class, identity ) );
+ uow.complete();
+ }
+
+ try( UnitOfWork uow = unitOfWorkFactory.newUnitOfWork( newUsecase( "create from value" ) ) )
+ {
+ Some entity = uow.toEntity( Some.class, loadedValue );
+ createdValue = uow.toValue( Some.class, entity );
+ System.out.println( "Created Entity from Value\n\t" + entity + "\nCreated Value\n\t" + createdValue );
+ uow.complete();
+ }
+ try( UnitOfWork uow = unitOfWorkFactory.newUnitOfWork( newUsecase( "read again" ) ) )
+ {
+ Some entity = uow.get( Some.class, identity );
+ loadedValue = uow.toValue( Some.class, entity );
+ System.out.println( "Loaded Entity\n\t" + entity + "\nLoaded Value\n\t" + loadedValue );
+ }
+
+ assertThat( "Create from Value/Read equality",
+ createdValue, equalTo( loadedValue ) );
+ }
+
+ /**
+ * @return a Some ValueComposite whose state is populated with test data.
+ */
+ protected static Some buildSomeValue( Module module, UnitOfWork uow, String identity )
+ {
+ ValueBuilder<Some> builder = module.newValueBuilder( Some.class );
+ Some proto = builder.prototype();
+ proto.identity().set( StringIdentity.fromString( identity ) );
+ setSomeValueState( module, uow, proto );
+ return builder.newInstance();
+ }
+
+ /**
+ * @return a Some EntityComposite whose state is populated with test data.
+ */
+ protected static Some buildSomeEntity( Module module, UnitOfWork uow, Identity identity )
+ {
+ EntityBuilder<Some> builder = uow.newEntityBuilder( Some.class, identity );
+ setSomeValueState( module, uow, builder.instance() );
+ return builder.newInstance();
+ }
+
+ private static void setSomeValueState( Module module, UnitOfWork uow, Some some )
+ {
+ some.anotherList().get().add( module.newValue( AnotherValue.class ) );
+
+ ValueBuilder<SpecificCollection> specificColBuilder = module.newValueBuilder( SpecificCollection.class );
+ SpecificCollection specificColProto = specificColBuilder.prototype();
+ List<String> genericList = new ArrayList<>( 2 );
+ genericList.add( "Some" );
+ genericList.add( "String" );
+ specificColProto.genericList().set( genericList );
+ some.specificCollection().set( specificColBuilder.newInstance() );
+
+ AnotherValue anotherValue1 = createAnotherValue( module, "Foo", "Bar" );
+ AnotherValue anotherValue2 = createAnotherValue( module, "Habba", "ZoutZout" );
+ AnotherValue anotherValue3 = createAnotherValue( module, "Niclas", "Hedhman" );
+
+ some.string().set( "Foo\"Bar\"\nTest\f\t\b\r" );
+ some.string2().set( "/Foo/bar" );
+ some.number().set( 43L );
+ some.localTime().set( LocalTime.now() );
+ some.dateTime().set( OffsetDateTime.of( 2020, 3, 4, 13, 24, 35, 0, ZoneOffset.ofHours( 1 ) ) );
+ some.localDate().set( LocalDate.now() );
+ some.localDateTime().set( LocalDateTime.now() );
+ some.entityReference().set( EntityReference.parseEntityReference( "12345" ) );
+ some.stringIntMap().get().put( "foo", 42 );
+
+ // Can't put more than one entry in Map because this test rely on the fact that the underlying implementations
+ // maintain a certain order but it's not the case on some JVMs. On OpenJDK 8 they are reversed for example.
+ // This should not be enforced tough as both the Map API and the JSON specification state that name-value pairs
+ // are unordered.
+ // As a consequence this test should be enhanced to be Map order independant.
+ //
+ // proto.stringIntMap().get().put( "bar", 67 );
+
+ some.stringValueMap().get().put( "foo", anotherValue1 );
+ some.another().set( anotherValue1 );
+ // some.arrayOfValues().set( new AnotherValue[] { anotherValue1, anotherValue2, anotherValue3 } );
+ some.serializable().set( new SerializableObject() );
+ some.foo().set( module.newValue( FooValue.class ) );
+ some.fooValue().set( module.newValue( FooValue.class ) );
+ some.customFoo().set( module.newValue( CustomFooValue.class ) );
+ some.customFooValue().set( module.newValue( CustomFooValue.class ) );
+
+ // Arrays
+ // TODO FIXME Disabled as ValueComposite equality fails here
+ //proto.primitiveByteArray().set( new byte[]
+ // {
+ // 9, -12, 42, -12, 127, 23, -128, 73
+ // } );
+ //proto.byteArray().set( new Byte[]
+ // {
+ // 9, null, -12, 23, -12, 127, -128, 73
+ // } );
+
+ // NestedEntities
+ some.barAssociation().set( buildBarEntity( uow, "bazar in barAssociation" ) );
+ some.barEntityAssociation().set( buildBarEntity( uow, "bazar in barEntityAssociation" ) );
+ some.barManyAssociation().add( buildBarEntity( uow, "bazar ONE in barManyAssociation" ) );
+ some.barManyAssociation().add( buildBarEntity( uow, "bazar TWO in barManyAssociation" ) );
+ some.barEntityManyAssociation().add( buildBarEntity( uow, "bazar ONE in barEntityManyAssociation" ) );
+ some.barEntityManyAssociation().add( buildBarEntity( uow, "bazar TWO in barEntityManyAssociation" ) );
+ some.barNamedAssociation().put( "bazar", buildBarEntity( uow, "bazar in barNamedAssociation" ) );
+ some.barNamedAssociation().put( "cathedral", buildBarEntity( uow, "cathedral in barNamedAssociation" ) );
+ some.barEntityNamedAssociation().put( "bazar",
+ buildBarEntity( uow, "bazar in barEntityNamedAssociation" ) );
+ some.barEntityNamedAssociation().put( "cathedral",
+ buildBarEntity( uow, "cathedral in barEntityNamedAssociation" ) );
+ }
+
+ private static AnotherValue createAnotherValue( Module module, String val1, String val2 )
+ {
+ ValueBuilder<AnotherValue> valueBuilder = module.newValueBuilder( AnotherValue.class );
+ valueBuilder.prototype().val1().set( val1 );
+ valueBuilder.prototypeFor( AnotherValueInternalState.class ).val2().set( val2 );
+ return valueBuilder.newInstance();
+ }
+
+ private static BarEntity buildBarEntity( UnitOfWork uow, String cathedral )
+ {
+ EntityBuilder<BarEntity> barBuilder = uow.newEntityBuilder( BarEntity.class );
+ barBuilder.instance().cathedral().set( cathedral );
+ return barBuilder.newInstance();
+ }
+
+ public enum TestEnum
+ {
+ somevalue,
+ anothervalue
+ }
+
+ public interface Some extends HasIdentity
+ {
+ Property<String> string();
+
+ Property<String> string2();
+
+ @Optional
+ Property<String> nullString();
+
+ @UseDefaults
+ Property<String> emptyString();
+
+ @UseDefaults
+ Property<Long> number();
+
+ Property<LocalTime> localTime();
+
+ Property<OffsetDateTime> dateTime();
+
+ Property<LocalDate> localDate();
+
+ Property<LocalDateTime> localDateTime();
+
+ Property<EntityReference> entityReference();
+
+ @UseDefaults
+ Property<List<String>> stringList();
+
+ @UseDefaults
+ Property<Map<String, Integer>> stringIntMap();
+
+ @UseDefaults
+ Property<Map<String, AnotherValue>> stringValueMap();
+
+ Property<AnotherValue> another();
+
+ // Property<AnotherValue[]> arrayOfValues();
+
+ @Optional
+ Property<AnotherValue> anotherNull();
+
+ @UseDefaults
+ Property<List<AnotherValue>> anotherList();
+
+ @Optional
+ Property<List<AnotherValue>> anotherListNull();
+
+ @UseDefaults
+ Property<List<AnotherValue>> anotherListEmpty();
+
+ @UseDefaults
+ Property<TestEnum> testEnum();
+
+ // TODO FIXME Disabled as ValueComposite equality fails here
+ //Property<byte[]> primitiveByteArray();
+ //
+ //@Optional
+ //Property<byte[]> primitiveByteArrayNull();
+ //
+ //Property<Byte[]> byteArray();
+ //
+ //@Optional
+ //Property<Byte[]> byteArrayNull();
+
+ Property<Object> serializable();
+
+ Property<Foo> foo();
+
+ Property<FooValue> fooValue();
+
+ Property<Foo> customFoo();
+
+ Property<FooValue> customFooValue();
+
+ Property<SpecificCollection> specificCollection();
+
+ /* Too complicated to do generics here for now
+ Property<SpecificValue> specificValue();
+ */
+ @Optional
+ Association<Bar> barAssociationOptional();
+
+ Association<Bar> barAssociation();
+
+ Association<BarEntity> barEntityAssociation();
+
+ ManyAssociation<Bar> barManyAssociationEmpty();
+
+ ManyAssociation<Bar> barManyAssociation();
+
+ ManyAssociation<BarEntity> barEntityManyAssociation();
+
+ NamedAssociation<Bar> barNamedAssociationEmpty();
+
+ NamedAssociation<Bar> barNamedAssociation();
+
+ NamedAssociation<BarEntity> barEntityNamedAssociation();
+ }
+
+ public interface SpecificCollection
+ extends GenericCollection<String>
+ {
+ }
+
+ public interface GenericCollection<TYPE>
+ extends ValueComposite
+ {
+ @UseDefaults
+ Property<List<TYPE>> genericList();
+ }
+
+ public interface SpecificValue
+ extends GenericValue<String>
+ {
+ }
+
+ public interface GenericValue<TYPE>
+ extends ValueComposite
+ {
+ @Optional
+ Property<TYPE> item();
+ }
+
+ @Mixins( AnotherValueMixin.class )
+ public interface AnotherValue
+ extends ValueComposite
+ {
+ @UseDefaults
+ Property<String> val1();
+
+ String internalVal();
+ }
+
+ public interface AnotherValueInternalState
+ {
+ @UseDefaults
+ Property<String> val2();
+ }
+
+ public static abstract class AnotherValueMixin
+ implements AnotherValue
+ {
+ @This
+ private AnotherValueInternalState internalState;
+
+ @Override
+ public String internalVal()
+ {
+ return internalState.val2().get();
+ }
+ }
+
+ public interface Foo
+ {
+ @UseDefaults
+ Property<String> bar();
+ }
+
+ public interface FooValue
+ extends Foo, ValueComposite
+ {
+ }
+
+ public interface CustomFooValue
+ extends FooValue
+ {
+ @UseDefaults
+ Property<String> custom();
+ }
+
+ public interface Bar
+ {
+ @UseDefaults
+ Property<String> cathedral();
+ }
+
+ public interface BarEntity
+ extends Bar, EntityComposite
+ {
+ }
+
+ public static class SerializableObject
+ implements Serializable
+ {
+ private static final long serialVersionUID = 1L;
+ private final String foo = "Foo";
+ private final int val = 35;
+
+ @Override
+ public boolean equals( Object o )
+ {
+ if( this == o )
+ {
+ return true;
+ }
+ if( o == null || getClass() != o.getClass() )
+ {
+ return false;
+ }
+ SerializableObject that = (SerializableObject) o;
+ return val == that.val && foo.equals( that.foo );
+ }
+
+ @Override
+ public int hashCode()
+ {
+ int result = foo.hashCode();
+ result = 31 * result + val;
+ return result;
+ }
+ }
+}
+
+
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/testsupport/src/main/java/org/apache/polygene/test/serialization/package.html
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/serialization/package.html b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/package.html
new file mode 100644
index 0000000..7a03a27
--- /dev/null
+++ b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/package.html
@@ -0,0 +1,24 @@
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ ~
+ ~
+ -->
+<html>
+ <body>
+ <h2>Serialization SPI Test Support.</h2>
+ </body>
+</html>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/testsupport/src/main/java/org/apache/polygene/test/util/JSONAssert.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/util/JSONAssert.java b/core/testsupport/src/main/java/org/apache/polygene/test/util/JSONAssert.java
deleted file mode 100644
index 7652596..0000000
--- a/core/testsupport/src/main/java/org/apache/polygene/test/util/JSONAssert.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.test.util;
-
-import java.util.Iterator;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.junit.Assert;
-
-/**
- * A set of assertion methods useful for tests using org.json.
- */
-public class JSONAssert
- extends Assert
-{
-
- /**
- * Assert that two JSONObjects are equals without enforcing field order.
- *
- * @param o1 First JSON object
- * @param o2 Second JSON object
- * @throws JSONException on json parsing error
- */
- public static void jsonObjectsEquals( JSONObject o1, JSONObject o2 )
- throws JSONException
- {
- if( o1 != o2 )
- {
- if( o1.length() != o2.length() )
- {
- fail( "JSONObjects length differ: " + o1.length() + " / " + o2.length() );
- }
- @SuppressWarnings( "unchecked" )
- Iterator<String> o1Keys = o1.keys();
- while( o1Keys.hasNext() )
- {
- String key = o1Keys.next();
- Object o1Value = o1.get( key );
- Object o2Value = o2.get( key );
- if( !jsonValueEquals( o1Value, o2Value ) )
- {
- fail( "JSONObject '" + key + "' values differ: " + o1Value + " / " + o2Value );
- }
- }
- }
- }
-
- /**
- * Assert that two JSONArrays are equals.
- *
- * @param a1 First JSON array
- * @param a2 Second JSON array
- * @throws JSONException on json parsing error
- */
- public static void jsonArraysEquals( JSONArray a1, JSONArray a2 )
- throws JSONException
- {
- if( a1 != a2 )
- {
- if( a1.length() != a2.length() )
- {
- fail( "JSONArrays length differ: " + a1.length() + " / " + a2.length() );
- }
- for( int idx = 0; idx < a1.length(); idx++ )
- {
- Object a1Value = a1.get( idx );
- Object a2Value = a2.get( idx );
- if( !jsonValueEquals( a1Value, a2Value ) )
- {
- fail( "JSONArray '" + idx + "' values differ: " + a1Value + " / " + a2Value );
- }
- }
- }
- }
-
- private static boolean jsonValueEquals( Object o1Value, Object o2Value )
- throws JSONException
- {
- if( o1Value instanceof JSONObject )
- {
-
- if( !( o2Value instanceof JSONObject ) )
- {
- return false;
- }
- jsonObjectsEquals( (JSONObject) o1Value, (JSONObject) o2Value );
-
- }
- else if( o1Value instanceof JSONArray )
- {
-
- if( !( o2Value instanceof JSONArray ) )
- {
- return false;
- }
- jsonArraysEquals( (JSONArray) o1Value, (JSONArray) o2Value );
-
- }
- else if( !o1Value.equals( o2Value ) )
- {
-
- return false;
-
- }
- return true;
- }
-
- private JSONAssert()
- {
- }
-
-}
[35/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
New (de)serialization API and SPI & new implementations
POLYGENE-191
POLYGENE-153
POLYGENE-137
POLYGENE-102
POLYGENE-157
POLYGENE-53
Breaking changes in org.apache.polygene.:
- api.type
- api.value
- spi.entitystore.helpers
New API/SPI in org.apache.polygene:
- api.serialization
- api.type
- spi.serialization
- spi.type
- Replace org.json with javax.json
- JSON serialization SPI & Extension using javax.json types
- XML serialization SPI & Extension based on javax.xml types
- Binary serialization Extension based on MessagePack
- Refine ValueType and promote ValueTypeFactory to SPI
Those changes fix a lot of issues and inconsistencies with serialization.
SQL EntityStore rewritten along the way to reuse JSONMapEntityStoreMixin.
Work in progress
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/c9dd7229
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/c9dd7229
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/c9dd7229
Branch: refs/heads/serialization-3.0
Commit: c9dd7229d1b7465c29b602bc403d1a4fd92e3228
Parents: 01949a6
Author: Paul Merlin <pa...@apache.org>
Authored: Fri Feb 3 08:56:24 2017 +0100
Committer: Paul Merlin <pa...@apache.org>
Committed: Mon Mar 13 11:24:03 2017 +0100
----------------------------------------------------------------------
.../structure/reports/ReportsPlugin.groovy | 2 +-
core/api/build.gradle | 1 -
core/api/src/docs/api.txt | 4 +
core/api/src/docs/objects.txt | 4 +-
core/api/src/docs/serialization.txt | 110 ++
core/api/src/docs/valuecomposite.txt | 107 +-
.../StatefulAssociationCompositeDescriptor.java | 31 +
.../api/configuration/Configuration.java | 114 +-
.../polygene/api/entity/EntityDescriptor.java | 8 +-
.../api/serialization/Deserializer.java | 68 ++
.../api/serialization/Serialization.java | 48 +
.../serialization/SerializationException.java | 34 +
.../polygene/api/serialization/Serializer.java | 247 +++++
.../polygene/api/serialization/package.html | 24 +
.../polygene/api/type/CollectionType.java | 62 +-
.../org/apache/polygene/api/type/EnumType.java | 5 +-
.../api/type/HasAssignableFromType.java | 33 +
.../polygene/api/type/HasAssignableToType.java | 29 +
.../api/type/HasEqualOrAssignableFromType.java | 25 +
.../api/type/HasEqualOrAssignableToType.java | 25 +
.../apache/polygene/api/type/HasEqualType.java | 26 +
.../polygene/api/type/HasTypesCollectors.java | 408 +++++++
.../polygene/api/type/HasTypesPredicate.java | 60 ++
.../org/apache/polygene/api/type/MapType.java | 45 +-
.../api/type/MatchTypeSpecification.java | 51 -
.../apache/polygene/api/type/Serialization.java | 62 --
.../polygene/api/type/ValueCompositeType.java | 32 +-
.../org/apache/polygene/api/type/ValueType.java | 145 +--
.../apache/polygene/api/util/Collectors.java | 149 ++-
.../MissingValueSerializationException.java | 43 -
.../polygene/api/value/ValueDescriptor.java | 8 +-
.../polygene/api/value/ValueDeserializer.java | 172 ---
.../polygene/api/value/ValueSerialization.java | 56 -
.../api/value/ValueSerializationException.java | 50 -
.../polygene/api/value/ValueSerializer.java | 293 -----
.../api/type/HasTypesCollectorsTest.java | 131 +++
.../api/type/HasTypesPredicatesTest.java | 54 +
.../polygene/api/type/ValueTypeFactoryTest.java | 105 ++
.../polygene/api/util/CollectorsTest.java | 106 +-
.../api/value/DocumentationSupport.java | 121 +--
.../api/configuration/MyService.properties | 2 +-
.../bootstrap/builder/ApplicationBuilder.java | 71 +-
.../DefaultSerializationAssembler.java | 42 +
.../builder/ApplicationBuilderTest.java | 5 +-
.../runtime/bootstrap/ModuleAssemblyImpl.java | 31 +-
.../runtime/property/PropertyModel.java | 46 +-
.../runtime/structure/ModuleInstance.java | 50 +-
.../runtime/structure/TypeLookupImpl.java | 289 +----
.../runtime/type/ValueTypeFactoryInstance.java | 147 +++
.../runtime/types/ValueTypeFactory.java | 233 ----
.../polygene/runtime/value/ValueInstance.java | 2 +-
.../polygene/runtime/value/ValueModel.java | 2 +-
.../bootstrap/ApplicationAssemblerTest.java | 5 +-
.../polygene/regression/qi382/Qi382Test.java | 3 -
.../polygene/regression/qi383/Qi383Test.java | 9 +-
.../association/AssociationAssignmentTest.java | 4 -
.../runtime/defaults/UseDefaultsTest.java | 20 +-
.../polygene/runtime/mixin/JDKMixinTest.java | 88 +-
.../property/ValueNestedBuilderTest.java | 3 -
.../runtime/value/AssociationToValueTest.java | 3 -
.../runtime/value/NestedValueBuilderTest.java | 16 +-
.../runtime/value/ValueCompositeBasicsTest.java | 6 +-
.../value/ValueSerializationRegressionTest.java | 9 +-
.../runtime/value/ValueWithAssociationTest.java | 11 +-
.../visibility/VisibilityInUnitOfWorkTest.java | 5 -
.../memory/MemoryEntityStoreTest.java | 3 -
core/spi/build.gradle | 4 +-
core/spi/src/docs/serialization.txt | 83 ++
core/spi/src/docs/spi.txt | 4 +-
core/spi/src/docs/valueserialization.txt | 83 --
.../memory/MemoryMapEntityStoreMixin.java | 49 +-
.../serialization/javaxjson/JavaxJson.java | 139 +++
.../javaxjson/JavaxJsonAdapter.java | 54 +
.../javaxjson/JavaxJsonAdapters.java | 64 ++
.../javaxjson/JavaxJsonDeserializer.java | 273 +++++
.../javaxjson/JavaxJsonSerialization.java | 26 +
.../JavaxJsonSerializationService.java | 533 ++++++++++
.../javaxjson/JavaxJsonSerializer.java | 216 ++++
.../javaxjson/JavaxJsonSettings.java | 73 ++
.../serialization/javaxjson/package.html | 24 +
.../entitystore/helpers/JSONEntityState.java | 395 ++++---
.../helpers/JSONManyAssociationState.java | 94 +-
.../helpers/JSONMapEntityStoreMixin.java | 327 +++---
.../helpers/JSONNamedAssociationState.java | 77 +-
.../spi/entitystore/helpers/MapEntityStore.java | 78 +-
.../helpers/MapEntityStoreMixin.java | 560 +++++-----
.../spi/entitystore/helpers/Migration.java | 8 +-
.../spi/entitystore/helpers/StateStore.java | 7 +-
.../apache/polygene/spi/module/ModuleSpi.java | 10 +-
.../AbstractBinaryDeserializer.java | 48 +
.../serialization/AbstractBinarySerializer.java | 51 +
.../spi/serialization/AbstractDeserializer.java | 155 +++
.../spi/serialization/AbstractSerializer.java | 147 +++
.../serialization/AbstractTextDeserializer.java | 34 +
.../serialization/AbstractTextSerializer.java | 48 +
.../spi/serialization/JsonDeserializer.java | 164 +++
.../spi/serialization/JsonSerialization.java | 24 +
.../spi/serialization/JsonSerializer.java | 106 ++
.../spi/serialization/XmlDeserializer.java | 107 ++
.../spi/serialization/XmlSerialization.java | 24 +
.../spi/serialization/XmlSerializer.java | 123 +++
.../polygene/spi/serialization/package.html | 24 +
.../polygene/spi/type/ValueTypeFactory.java | 11 +
.../spi/value/ValueDeserializerAdapter.java | 1001 ------------------
.../spi/value/ValueSerializerAdapter.java | 570 ----------
.../org/apache/polygene/spi/value/package.html | 24 -
.../orgjson/OrgJsonValueDeserializer.java | 485 ---------
.../OrgJsonValueSerializationService.java | 32 -
.../orgjson/OrgJsonValueSerializer.java | 114 --
.../valueserialization/orgjson/package.html | 24 -
.../spi/entitystore/Polygene142Test.java | 15 +-
.../helpers/JSONManyAssociationStateTest.java | 34 +-
.../helpers/JsonNamedAssociationStateTest.java | 104 ++
.../polygene/test/EntityTestAssembler.java | 5 +-
...bstractConfigurationDeserializationTest.java | 9 +-
.../layered/assembly/PersistenceModule.java | 3 -
.../AbstractCollectionSerializationTest.java | 481 +++++++++
.../AbstractDateFormatSerializationTest.java | 142 +++
.../AbstractPlainValueSerializationTest.java | 259 +++++
...AbstractValueCompositeSerializationTest.java | 521 +++++++++
.../polygene/test/serialization/package.html | 24 +
.../apache/polygene/test/util/JSONAssert.java | 130 ---
.../AbstractCollectionSerializationTest.java | 433 --------
.../test/value/AbstractJsonDateFormatTest.java | 151 ---
.../AbstractPlainValueSerializationTest.java | 211 ----
...AbstractValueCompositeSerializationTest.java | 431 --------
.../org/apache/polygene/test/value/package.html | 24 -
dependencies.gradle | 14 +-
extensions/cache-ehcache/build.gradle | 1 -
extensions/cache-memcache/build.gradle | 1 -
extensions/entitystore-cassandra/build.gradle | 1 -
.../cassandra/CassandraEntityStoreMixin.java | 10 +-
.../cassandra/CassandraMapEntityStoreTest.java | 2 -
extensions/entitystore-file/build.gradle | 2 -
.../entitystore/file/FileEntityStoreMixin.java | 6 +-
.../entitystore/file/FileEntityStoreTest.java | 2 -
.../file/FileEntityStoreWithCacheTest.java | 2 -
extensions/entitystore-geode/build.gradle | 1 -
.../geode/GeodeEntityStoreMixin.java | 6 +-
.../entitystore/geode/GeodeEntityStoreTest.java | 2 -
.../geode/GeodeEntityStoreWithCacheTest.java | 2 -
extensions/entitystore-hazelcast/build.gradle | 1 -
.../hazelcast/HazelcastEntityStoreMixin.java | 6 +-
.../hazelcast/HazelcastEntityStoreTest.java | 6 +-
.../HazelcastEntityStoreWithCacheTest.java | 2 -
extensions/entitystore-jclouds/build.gradle | 1 -
.../jclouds/JCloudsMapEntityStoreMixin.java | 11 +-
.../jclouds/JCloudsFilesystemTest.java | 4 -
.../entitystore/jclouds/JCloudsS3Test.java | 2 -
.../jclouds/JCloudsTransientTest.java | 6 -
.../jclouds/JCloudsWithCacheTest.java | 2 -
extensions/entitystore-jdbm/build.gradle | 1 -
.../entitystore/jdbm/JdbmEntityStoreMixin.java | 6 +-
.../entitystore/jdbm/JdbmEntityStoreTest.java | 2 -
.../jdbm/JdbmEntityStoreWithCacheTest.java | 2 -
extensions/entitystore-leveldb/build.gradle | 1 -
.../leveldb/LevelDBEntityStoreMixin.java | 9 +-
.../leveldb/JavaLevelDBEntityStoreTest.java | 2 -
.../leveldb/JniLevelDBEntityStoreTest.java | 2 -
.../LevelDBEntityStoreWithCacheTest.java | 2 -
extensions/entitystore-memory/build.gradle | 1 -
.../memory/MemoryEntityStoreTest.java | 5 -
.../memory/MemoryEntityStoreWithCacheTest.java | 2 -
extensions/entitystore-mongodb/build.gradle | 1 -
.../mongodb/MongoMapEntityStoreMixin.java | 10 +-
.../mongodb/EmbedMongoMapEntityStoreTest.java | 3 -
.../mongodb/MongoMapEntityStoreTest.java | 7 +-
.../MongoMapEntityStoreWithCacheTest.java | 7 +-
extensions/entitystore-preferences/build.gradle | 1 -
.../PreferencesEntityStoreMixin.java | 48 +-
.../entitystore/PreferencesEntityStoreTest.java | 2 -
extensions/entitystore-redis/build.gradle | 1 -
.../redis/RedisMapEntityStoreMixin.java | 12 +-
.../redis/RedisMapEntityStoreTest.java | 4 +-
.../redis/RedisMapEntityStoreWithCacheTest.java | 4 +-
extensions/entitystore-riak/build.gradle | 1 -
.../riak/RiakMapEntityStoreMixin.java | 12 +-
.../riak/RiakMapEntityStoreTest.java | 2 -
.../riak/RiakMapEntityStoreWithCacheTest.java | 2 -
extensions/entitystore-sql/build.gradle | 3 +-
.../entitystore/sql/SQLEntityStoreMixin.java | 624 -----------
.../entitystore/sql/SQLEntityStoreService.java | 39 -
.../sql/SQLMapEntityStoreMapping.java | 69 ++
.../entitystore/sql/SQLMapEntityStoreMixin.java | 237 +++++
.../sql/SQLMapEntityStoreService.java | 45 +
.../AbstractSQLEntityStoreAssembler.java | 93 --
.../AbstractSQLMapEntityStoreAssembler.java | 85 ++
.../assembly/DerbySQLEntityStoreAssembler.java | 21 +-
.../sql/assembly/H2SQLEntityStoreAssembler.java | 21 +-
.../sql/assembly/MySQLEntityStoreAssembler.java | 21 +-
.../PostgreSQLEntityStoreAssembler.java | 28 +-
.../assembly/SQLiteEntityStoreAssembler.java | 21 +-
.../sql/internal/DatabaseSQLService.java | 42 +-
.../sql/internal/DatabaseSQLServiceState.java | 6 +-
.../DatabaseSQLServiceStatementsMixin.java | 15 +-
.../sql/internal/DatabaseSQLStringsBuilder.java | 248 ++---
.../DerbySQLDatabaseSQLServiceMixin.java | 17 +-
.../internal/H2SQLDatabaseSQLServiceMixin.java | 25 +-
.../internal/MySQLDatabaseSQLServiceMixin.java | 18 +-
.../PostgreSQLDatabaseSQLServiceMixin.java | 30 +-
.../internal/SQLiteDatabaseSQLServiceMixin.java | 25 +-
.../polygene/entitystore/sql/internal/SQLs.java | 20 +-
.../sql/DerbySQLEntityStoreTest.java | 41 +-
.../entitystore/sql/H2SQLEntityStoreTest.java | 49 +-
.../entitystore/sql/MySQLEntityStoreTest.java | 32 +-
.../sql/PostgreSQLEntityStoreTest.java | 38 +-
.../entitystore/sql/SQLiteEntityStoreTest.java | 51 +-
extensions/indexing-elasticsearch/build.gradle | 1 -
.../elasticsearch/ElasticSearchIndexer.java | 240 ++---
.../assembly/ESClientIndexQueryAssembler.java | 5 -
.../assembly/ESClusterIndexQueryAssembler.java | 5 -
.../ESFilesystemIndexQueryAssembler.java | 2 -
.../elasticsearch/ElasticSearchQueryTest.java | 4 -
extensions/indexing-rdf/build.gradle | 1 -
.../index/rdf/query/RdfQueryParserFactory.java | 11 +-
.../rdf/query/internal/RdfQueryParserImpl.java | 18 +-
.../polygene/index/rdf/ContainsAllTest.java | 118 +--
.../apache/polygene/index/rdf/ContainsTest.java | 50 +-
.../polygene/index/rdf/RdfComplexQueryTest.java | 5 +-
.../polygene/index/rdf/RdfEntityFinderTest.java | 3 -
.../index/rdf/RdfNamedQueryMultimoduleTest.java | 2 -
.../polygene/index/rdf/RdfNamedQueryTest.java | 2 -
.../index/rdf/RdfQueryMultimoduleTest.java | 2 -
.../polygene/index/rdf/qi66/Qi66IssueTest.java | 7 +-
.../polygene/index/rdf/qi95/Qi95IssueTest.java | 22 +-
extensions/indexing-solr/build.gradle | 1 -
.../solr/assembly/SolrIndexingAssembler.java | 25 +-
.../solr/internal/SolrEntityIndexerMixin.java | 95 +-
extensions/indexing-sql/build.gradle | 1 -
.../skeletons/SQLCompatEntityStateWrapper.java | 1 +
.../polygene/migration/MigrationService.java | 549 +++++++---
.../org/apache/polygene/migration/Migrator.java | 56 +-
.../assembly/AbstractMigrationRule.java | 6 +
.../assembly/EntityMigrationOperation.java | 12 +-
.../migration/assembly/EntityMigrationRule.java | 27 +-
.../migration/assembly/MigrationContext.java | 60 ++
.../migration/operation/AddAssociation.java | 14 +-
.../migration/operation/AddManyAssociation.java | 14 +-
.../operation/AddNamedAssociation.java | 14 +-
.../migration/operation/AddProperty.java | 14 +-
.../migration/operation/RemoveAssociation.java | 14 +-
.../operation/RemoveManyAssociation.java | 14 +-
.../operation/RemoveNamedAssociation.java | 14 +-
.../migration/operation/RemoveProperty.java | 14 +-
.../migration/operation/RenameAssociation.java | 14 +-
.../migration/operation/RenameEntity.java | 35 +-
.../operation/RenameManyAssociation.java | 14 +-
.../operation/RenameNamedAssociation.java | 14 +-
.../migration/operation/RenameProperty.java | 14 +-
.../polygene/migration/MigrationTest.java | 37 +-
extensions/reindexer/build.gradle | 1 -
.../polygene/index/reindexer/ReindexerTest.java | 2 -
extensions/serialization-javaxjson/build.gradle | 34 +
.../serialization-javaxjson/dev-status.xml | 38 +
.../src/docs/serialization-javaxjson.txt | 31 +
.../JavaxJsonSerializationAssembler.java | 58 +
.../serialization/javaxjson/package.html | 24 +
.../javaxjson/CustomJsonAdapterTest.java | 180 ++++
.../JavaxJsonCollectionSerializationTest.java | 24 +
...vaxJsonConfigurationDeserializationTest.java | 24 +
.../JavaxJsonDateFormatSerializationTest.java | 24 +
.../JavaxJsonPlainValueSerializationTest.java | 26 +
...avaxJsonValueCompositeSerializationTest.java | 60 ++
.../src/test/resources/configtest.json | 8 +
extensions/serialization-javaxxml/build.gradle | 34 +
.../serialization-javaxxml/dev-status.xml | 38 +
.../src/docs/serialization-javaxxml.txt | 30 +
.../serialization/javaxxml/JavaxXml.java | 161 +++
.../serialization/javaxxml/JavaxXmlAdapter.java | 56 +
.../javaxxml/JavaxXmlAdapters.java | 64 ++
.../javaxxml/JavaxXmlDeserializer.java | 325 ++++++
.../javaxxml/JavaxXmlSerialization.java | 88 ++
.../JavaxXmlSerializationAssembler.java | 58 +
.../javaxxml/JavaxXmlSerializationService.java | 372 +++++++
.../javaxxml/JavaxXmlSerializer.java | 271 +++++
.../javaxxml/JavaxXmlSettings.java | 134 +++
.../serialization/javaxxml/package.html | 24 +
.../javaxxml/JavaxXmlAdaptersTest.java | 39 +
.../javaxxml/JavaxXmlCollectionTest.java | 31 +
.../javaxxml/JavaxXmlDateFormatTest.java | 33 +
.../javaxxml/JavaxXmlPlainValueTest.java | 35 +
.../javaxxml/JavaxXmlValueCompositeTest.java | 68 ++
extensions/serialization-msgpack/build.gradle | 36 +
extensions/serialization-msgpack/dev-status.xml | 38 +
.../src/docs/serialization-msgpack.txt | 30 +
.../msgpack/MessagePackAdapter.java | 57 +
.../msgpack/MessagePackAdapters.java | 64 ++
.../msgpack/MessagePackDeserializer.java | 295 ++++++
.../msgpack/MessagePackSerialization.java | 22 +
.../MessagePackSerializationAssembler.java | 52 +
.../MessagePackSerializationService.java | 414 ++++++++
.../msgpack/MessagePackSerializer.java | 187 ++++
.../msgpack/MessagePackSettings.java | 44 +
.../polygene/serialization/msgpack/package.html | 24 +
.../MessagePackCollectionSerializationTest.java | 31 +
.../MessagePackDateFormatSerializationTest.java | 33 +
.../MessagePackPlainValueSerializationTest.java | 35 +
...sagePackValueCompositeSerializationTest.java | 31 +
.../valueserialization-jackson/build.gradle | 37 -
.../valueserialization-jackson/dev-status.xml | 36 -
.../src/docs/vs-jackson.txt | 43 -
.../jackson/JacksonValueDeserializer.java | 379 -------
.../JacksonValueSerializationService.java | 32 -
.../jackson/JacksonValueSerializer.java | 92 --
.../JacksonValueSerializationAssembler.java | 42 -
.../valueserialization/jackson/package.html | 24 -
.../JacksonCollectionSerializationTest.java | 38 -
...JacksonConfigurationDeserializationTest.java | 39 -
.../jackson/JacksonJsonDateFormatTest.java | 38 -
.../JacksonPlainValueSerializationTest.java | 36 -
.../JacksonValueCompositeSerializationTest.java | 38 -
.../src/test/resources/configtest.json | 8 -
.../valueserialization-orgjson/build.gradle | 35 -
.../valueserialization-orgjson/dev-status.xml | 36 -
.../src/docs/vs-orgjson.txt | 43 -
.../OrgJsonValueSerializationAssembler.java | 41 -
.../valueserialization/orgjson/package.html | 24 -
.../OrgJsonCollectionSerializationTest.java | 37 -
...OrgJsonConfigurationDeserializationTest.java | 38 -
.../orgjson/OrgJsonDateFormatTest.java | 37 -
.../OrgJsonPlainValueSerializationTest.java | 35 -
.../OrgJsonValueCompositeSerializationTest.java | 37 -
.../src/test/resources/configtest.json | 8 -
extensions/valueserialization-stax/build.gradle | 37 -
.../valueserialization-stax/dev-status.xml | 36 -
.../src/docs/vs-stax.txt | 43 -
.../stax/StaxValueDeserializer.java | 522 ---------
.../stax/StaxValueSerializationService.java | 32 -
.../stax/StaxValueSerializer.java | 134 ---
.../StaxValueSerializationAssembler.java | 42 -
.../valueserialization/stax/package.html | 24 -
.../stax/StaxCollectionSerializationTest.java | 47 -
.../StaxConfigurationDeserializationTest.java | 69 --
.../stax/StaxPlainValueSerializationTest.java | 45 -
.../StaxValueCompositeSerializationTest.java | 47 -
.../src/test/resources/configtest.xml | 50 -
internals/testsupport-internal/build.gradle | 5 +
.../library/appbrowser/AppBrowserTest.java | 2 -
.../library/constraints/ConstraintTest.java | 10 +-
libraries/rdf/build.gradle | 1 -
.../rdf/entity/EntityStateSerializer.java | 176 +--
.../rdf/entity/EntitySerializerTest.java | 16 +-
libraries/rest-client/build.gradle | 1 -
.../ValueCompositeRequestWriter.java | 17 +-
.../responsereader/DefaultResponseReader.java | 56 +-
.../responsereader/JSONResponseReader.java | 88 +-
.../responsereader/TableResponseReader.java | 137 +--
.../ContextResourceClientFactoryTest.java | 16 +-
.../rest/client/ContinuousIntegrationTest.java | 20 +-
.../library/rest/client/RssReaderTest.java | 6 +-
.../polygene/library/rest/common/Resource.java | 2 +-
.../rest/server/api/ContextResource.java | 2 +-
.../requestreader/DefaultRequestReader.java | 14 +-
.../responsewriter/AbstractResponseWriter.java | 3 +-
.../responsewriter/DefaultResponseWriter.java | 4 +-
.../responsewriter/FormResponseWriter.java | 21 +-
.../responsewriter/JSONResponseWriter.java | 22 +-
.../responsewriter/LinksResponseWriter.java | 3 +-
.../responsewriter/TableResponseWriter.java | 92 +-
.../ValueCompositeResponseWriter.java | 10 +-
.../ValueDescriptorResponseWriter.java | 51 +-
libraries/rest/build.gradle | 4 +-
.../library/rest/admin/EntitiesResource.java | 7 +-
.../library/rest/admin/EntityResource.java | 13 +-
.../library/rest/admin/RDFAssembler.java | 2 -
libraries/restlet/build.gradle | 3 +-
.../RestletCrudConnectivityAssembler.java | 2 -
.../configuration/ConfigurationModule.java | 2 -
.../infrastructue/SerializationModule.java | 5 -
.../serialization/JsonRepresentation.java | 15 +-
libraries/sql-liquibase/build.gradle | 1 +
.../sql/liquibase/LiquibaseServiceTest.java | 124 +--
.../polygene/library/sql/common/Databases.java | 1 +
.../ConcurrentUoWFileModificationException.java | 2 +-
manual/src/docs/userguide/extensions.txt | 24 +-
samples/forum/build.gradle | 1 -
.../sample/forum/assembler/ForumAssembler.java | 17 +-
samples/rental/build.gradle | 1 -
.../rental/web/assembly/StorageModule.java | 5 -
.../sample/sqlsupport/AppAssembler.java | 7 -
settings.gradle | 6 +-
tests/performance/build.gradle | 1 -
.../jdbm/JdbmEntityStorePerformanceTest.java | 2 -
.../MemoryEntityStorePerformanceTest.java | 4 +-
.../sql/DerbySQLEntityStorePerformanceTest.java | 3 -
.../indexing/rdf/QueryPerformanceTest.java | 14 +-
tools/generator-polygene/app/index.js | 5 +-
.../ConfigModule/bootstrap.tmpl | 2 -
.../SerializationModule/bootstrap.tmpl | 6 +-
.../SerializationModule/module.js | 2 +-
.../InfrastructureLayer/bootstrap.tmpl | 2 +-
.../templates/buildtool/gradle-bootstrap.tmpl | 2 +-
tools/generator-polygene/test/generator_test.js | 15 +-
.../tools/model/VisitableDetailTest.java | 2 +
394 files changed, 13361 insertions(+), 11342 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/buildSrc/src/main/groovy/org/apache/polygene/gradle/structure/reports/ReportsPlugin.groovy
----------------------------------------------------------------------
diff --git a/buildSrc/src/main/groovy/org/apache/polygene/gradle/structure/reports/ReportsPlugin.groovy b/buildSrc/src/main/groovy/org/apache/polygene/gradle/structure/reports/ReportsPlugin.groovy
index 862e2ec..346005f 100644
--- a/buildSrc/src/main/groovy/org/apache/polygene/gradle/structure/reports/ReportsPlugin.groovy
+++ b/buildSrc/src/main/groovy/org/apache/polygene/gradle/structure/reports/ReportsPlugin.groovy
@@ -120,7 +120,7 @@ class ReportsPlugin implements Plugin<Project>
"Core SPI" : [ "org.apache.polygene.spi",
"org.apache.polygene.spi.*" ],
"Libraries" : [ "org.apache.polygene.library.*" ],
- "Extensions" : [ "org.apache.polygene.valueserialization.*",
+ "Extensions" : [ "org.apache.polygene.serialization.*",
"org.apache.polygene.entitystore.*",
"org.apache.polygene.index.*",
"org.apache.polygene.metrics.*",
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/build.gradle
----------------------------------------------------------------------
diff --git a/core/api/build.gradle b/core/api/build.gradle
index b210fac..67c5f96 100644
--- a/core/api/build.gradle
+++ b/core/api/build.gradle
@@ -25,7 +25,6 @@ jar { manifest { name = "Apache Polygene\u2122 Core API" } }
dependencies {
testImplementation polygene.core.testsupport
testImplementation polygene.library( 'constraints' )
- testImplementation polygene.extension( 'valueserialization-orgjson' )
testRuntimeOnly polygene.core.runtime
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/docs/api.txt
----------------------------------------------------------------------
diff --git a/core/api/src/docs/api.txt b/core/api/src/docs/api.txt
index d601b8a..fa7188e 100644
--- a/core/api/src/docs/api.txt
+++ b/core/api/src/docs/api.txt
@@ -94,6 +94,10 @@ include::decoratormixin.txt[]
:leveloffset: {level3}
+include::serialization.txt[]
+
+:leveloffset: {level3}
+
// include::indexing.txt[]
:leveloffset: {level3}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/docs/objects.txt
----------------------------------------------------------------------
diff --git a/core/api/src/docs/objects.txt b/core/api/src/docs/objects.txt
index 6269ca7..4b5d546 100644
--- a/core/api/src/docs/objects.txt
+++ b/core/api/src/docs/objects.txt
@@ -28,9 +28,9 @@ The characteristics of an Object compared to Composite meta types are;
* Can not have Property instances managed by the Polygene runtime.
== Serialization ==
-Objects can be serialized and deserialized using the ValueSerialization API, if and only
+Objects can be serialized and deserialized using the Serialization API, if and only
if they are used as types in Properties in Values or Entities. It depends on the
-ValueSerialization implementation on how the objects are serialized, and
+Serialization implementation on how the objects are serialized, and
what the requirements are to allow for deserialization. In general, the Spring
POJO setter/getter approach will always work, a default constructor is needed, and
to be safe, make it into +java.io.Serializable+.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/docs/serialization.txt
----------------------------------------------------------------------
diff --git a/core/api/src/docs/serialization.txt b/core/api/src/docs/serialization.txt
new file mode 100644
index 0000000..e789125
--- /dev/null
+++ b/core/api/src/docs/serialization.txt
@@ -0,0 +1,110 @@
+//////////////////////
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+//////////////////////
+
+[[core-api-serialization,Serialization]]
+= Serialization =
+
+// TODO Reword with the following outline
+// Preamble - What is it for? What can I use it with?, see <<extensions>>
+// Use cases - Value, collections/streams & arrays of values
+
+State can be serialized and deserialized using the Serialization API which is a Service API implemented
+by SPI and extensions.
+
+TIP: +Serialization extends Serializer, Deserializer+. See the <<javadocs>> for interfaces detail.
+
+The Serialization mechanism apply to the following object types :
+
+ * ValueComposite,
+ * EntityReference,
+ * Iterable & Stream,
+ * Map,
+ * Plain Value.
+
+Nested Plain Values, EntityReferences, Iterables, Streams, Maps, ValueComposites are supported.
+EntityComposites and EntityReferences are serialized as their identity string.
+
+Plain Values can be one of :
+
+ * String,
+ * Character or char,
+ * Boolean or boolean,
+ * Integer or int,
+ * Long or long,
+ * Short or short,
+ * Byte or byte,
+ * Float or float,
+ * Double or double,
+ * BigInteger,
+ * BigDecimal,
+ * Date,
+ * DateTime (JodaTime),
+ * LocalDateTime (JodaTime),
+ * LocalDate (JodaTime).
+
+TIP: Serialization behaviour can be tuned with options.
+Every +Serializer+ methods can take a +Serializer.Options+ object that contains flags to change how some
+values are serialized. See the <<javadocs>> for more details.
+
+Values of unknown types and all arrays are considered as +java.io.Serializable+ and by so are (de)serialized to (from)
+base64 encoded bytes using pure Java serialization. If it happens that the value is not Serializable or the input to
+deserialize is invalid, a +SerializationException+ is thrown.
+
+Methods of +Serializer+ allow to specify if the serialized state should contain extra type information about the
+serialized value. Having type information in the serialized payload allows to keep actual ValueComposite types and by so
+circumvent +AmbiguousTypeException+ when deserializing.
+
+Core Runtime provides a default Serialization system based on the
+https://github.com/douglascrockford/JSON-java[org.json] Java library producing and consuming JSON.
+
+Let's see how it works in practice.
+
+[snippet,java]
+----
+source=core/api/src/test/java/org/apache/polygene/api/value/DocumentationSupport.java
+tag=default
+----
+
+Reading this first example step by step we ;
+
+ . declare a ValueComposite,
+ . assemble it,
+ . create a new Value instance,
+ . use the +ValueComposite#toString()+ method to get a JSON representation of the Value,
+ . and finally, use the +Module#newValueFromSerializedState()+ method to create a new Value instance from the JSON
+ state.
+
++ValueComposite#toString()+ method leverage Value Serialization and by so provide JSON based representation. The Module
+API allows to create new Value instances from serialized state.
+
+On top of that, Application assemblies can register different implementation of Serialization as Services to
+support more formats, see the <<extensions>> section. Note that the default behaviour described above is overriden if a
+Serialization Service is visible.
+
+Let's see how to use the Serialization Services.
+
+[snippet,java]
+----
+source=core/api/src/test/java/org/apache/polygene/api/value/DocumentationSupport.java
+tag=service
+----
+
+In this second example, we ;
+
+ . declare a ValueComposite,
+ . assemble it,
+ . assemble a Serialization Service backed by the +org.json+ package,
+ . get the +Serializer+ and +Deserializer+ Services injected,
+ . create a new Value instance,
+ . use the +Serializer#serialize()+ method to get a JSON representation of the Value,
+ . and finally, use the +Deserializer#deserialize()+ method to create a new Value instance from the JSON state.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/docs/valuecomposite.txt
----------------------------------------------------------------------
diff --git a/core/api/src/docs/valuecomposite.txt b/core/api/src/docs/valuecomposite.txt
index c3de8b5..1903c2c 100644
--- a/core/api/src/docs/valuecomposite.txt
+++ b/core/api/src/docs/valuecomposite.txt
@@ -27,109 +27,4 @@ The characteristics of a ValueComposite compared to other Composite meta types a
* It is Immutable.
* Its equals/hashCode works on both the descriptor and the values of the ValueComposite.
* Can be used as Property types.
- * Can be serialized and deserialized.
-
-== Value Serialization ==
-Value objects can be serialized and deserialized using the ValueSerialization API which is a Service API implemented
-by SPI and extensions.
-
-TIP: +ValueSerialization extends ValueSerializer, ValueDeserializer+. See the <<javadocs>> for interfaces detail.
-
-The ValueSerialization mechanism apply to the following object types :
-
- * ValueComposite,
- * EntityReference,
- * Iterable,
- * Map,
- * Plain Value.
-
-Nested Plain Values, EntityReferences, Iterables, Maps, ValueComposites are supported.
-EntityComposites and EntityReferences are serialized as their identity string.
-
-Plain Values can be one of :
-
- * String,
- * Character or char,
- * Boolean or boolean,
- * Integer or int,
- * Long or long,
- * Short or short,
- * Byte or byte,
- * Float or float,
- * Double or double,
- * BigInteger,
- * BigDecimal,
- * Date,
- * DateTime (JodaTime),
- * LocalDateTime (JodaTime),
- * LocalDate (JodaTime).
-
-TIP: Serialization behaviour can be tuned with options.
-Every +ValueSerializer+ methods can take a +ValueSerializer.Options+ object that contains flags to change how some
-values are serialized. See the <<javadocs>> for more details.
-
-Values of unknown types and all arrays are considered as +java.io.Serializable+ and by so are (de)serialized to (from)
-base64 encoded bytes using pure Java serialization. If it happens that the value is not Serializable or the input to
-deserialize is invalid, a +ValueSerializationException+ is thrown.
-
-Methods of +ValueSerializer+ allow to specify if the serialized state should contain extra type information about the
-serialized value. Having type information in the serialized payload allows to keep actual ValueComposite types and by so
-circumvent +AmbiguousTypeException+ when deserializing.
-
-Core Runtime provides a default ValueSerialization system based on the
-https://github.com/douglascrockford/JSON-java[org.json] Java library producing and consuming JSON.
-
-Let's see how it works in practice.
-
-[snippet,java]
-----
-source=core/api/src/test/java/org/apache/polygene/api/value/DocumentationSupport.java
-tag=default
-----
-
-Reading this first example step by step we ;
-
- . declare a ValueComposite,
- . assemble it,
- . create a new Value instance,
- . use the +ValueComposite#toString()+ method to get a JSON representation of the Value,
- . and finally, use the +Module#newValueFromSerializedState()+ method to create a new Value instance from the JSON
- state.
-
-+ValueComposite#toString()+ method leverage Value Serialization and by so provide JSON based representation. The Module
-API allows to create new Value instances from serialized state.
-
-On top of that, Application assemblies can register different implementation of ValueSerialization as Services to
-support more formats, see the <<extensions>> section. Note that the default behaviour described above is overriden if a
-ValueSerialization Service is visible.
-
-Let's see how to use the ValueSerialization Services.
-
-[snippet,java]
-----
-source=core/api/src/test/java/org/apache/polygene/api/value/DocumentationSupport.java
-tag=service
-----
-
-In this second example, we ;
-
- . declare a ValueComposite,
- . assemble it,
- . assemble a ValueSerialization Service backed by the +org.json+ package,
- . get the +ValueSerializer+ and +ValueDeserializer+ Services injected,
- . create a new Value instance,
- . use the +ValueSerializer#serialize()+ method to get a JSON representation of the Value,
- . and finally, use the +ValueDeserializer#eserialize()+ method to create a new Value instance from the JSON state.
-
-Many applications need to stream data. The ValueSerialization API support such use cases using classic streams:
-
-[snippet,java]
-----
-source=core/api/src/test/java/org/apache/polygene/api/value/DocumentationSupport.java
-tag=stream
-----
-
- . get a handle on a source of values and an +OutputStream+,
- . serialize data into the +OutputStream+,
- . get a handle on an +InputStream+,
- . deserialize data from the +InputStream+.
+ * Can be serialized and deserialized, see <<core-api-serialization>>.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/composite/StatefulAssociationCompositeDescriptor.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/composite/StatefulAssociationCompositeDescriptor.java b/core/api/src/main/java/org/apache/polygene/api/composite/StatefulAssociationCompositeDescriptor.java
new file mode 100644
index 0000000..c3c5a61
--- /dev/null
+++ b/core/api/src/main/java/org/apache/polygene/api/composite/StatefulAssociationCompositeDescriptor.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.api.composite;
+
+import org.apache.polygene.api.association.AssociationStateDescriptor;
+
+/**
+ * Stateful Association Composite Descriptor.
+ */
+public interface StatefulAssociationCompositeDescriptor extends StatefulCompositeDescriptor
+{
+ @Override
+ AssociationStateDescriptor state();
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/configuration/Configuration.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/configuration/Configuration.java b/core/api/src/main/java/org/apache/polygene/api/configuration/Configuration.java
index 96822a0..21eb05f 100644
--- a/core/api/src/main/java/org/apache/polygene/api/configuration/Configuration.java
+++ b/core/api/src/main/java/org/apache/polygene/api/configuration/Configuration.java
@@ -22,6 +22,7 @@ package org.apache.polygene.api.configuration;
import java.io.IOException;
import java.io.InputStream;
+import java.io.InputStreamReader;
import org.apache.polygene.api.PolygeneAPI;
import org.apache.polygene.api.composite.Composite;
import org.apache.polygene.api.composite.PropertyMapper;
@@ -37,15 +38,16 @@ import org.apache.polygene.api.service.ServiceComposite;
import org.apache.polygene.api.service.ServiceDescriptor;
import org.apache.polygene.api.service.ServiceReference;
import org.apache.polygene.api.service.qualifier.ServiceTags;
+import org.apache.polygene.api.serialization.Deserializer;
+import org.apache.polygene.api.serialization.Serialization;
import org.apache.polygene.api.structure.Module;
-import org.apache.polygene.api.unitofwork.NoSuchEntityTypeException;
import org.apache.polygene.api.unitofwork.NoSuchEntityException;
+import org.apache.polygene.api.unitofwork.NoSuchEntityTypeException;
import org.apache.polygene.api.unitofwork.UnitOfWork;
import org.apache.polygene.api.unitofwork.UnitOfWorkCompletionException;
import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
import org.apache.polygene.api.usecase.Usecase;
import org.apache.polygene.api.usecase.UsecaseBuilder;
-import org.apache.polygene.api.value.ValueSerialization;
/**
* Provide Configurations for Services. A Service that wants to be configurable
@@ -175,8 +177,7 @@ public interface Configuration<T>
private UnitOfWorkFactory uowf;
@Service
- private Iterable<ServiceReference<ValueSerialization>> valueSerialization;
-
+ private Iterable<ServiceReference<Deserializer>> stateDeserializers;
public ConfigurationMixin()
{
@@ -247,16 +248,17 @@ public interface Configuration<T>
}
catch( NoSuchEntityException | NoSuchEntityTypeException e )
{
- return (V) initializeConfigurationInstance( serviceComposite, uow, serviceModel, serviceComposite.identity().get() );
+ return (V) initializeConfigurationInstance( serviceComposite, uow, serviceModel,
+ serviceComposite.identity().get() );
}
return configuration;
}
@SuppressWarnings( "unchecked" )
- private <V extends HasIdentity> V initializeConfigurationInstance(ServiceComposite serviceComposite,
- UnitOfWork uow,
- ServiceDescriptor serviceModel,
- Identity identity
+ private <V extends HasIdentity> V initializeConfigurationInstance( ServiceComposite serviceComposite,
+ UnitOfWork uow,
+ ServiceDescriptor serviceModel,
+ Identity identity
)
throws InstantiationException
{
@@ -282,7 +284,8 @@ public interface Configuration<T>
{
try
{
- EntityBuilder<V> configBuilder = buildUow.newEntityBuilder( serviceModel.<V>configurationType(), identity );
+ EntityBuilder<V> configBuilder = buildUow.newEntityBuilder(
+ serviceModel.<V>configurationType(), identity );
configBuilder.newInstance();
}
catch( ConstraintViolationException e )
@@ -304,7 +307,8 @@ public interface Configuration<T>
catch( Exception e1 )
{
InstantiationException ex = new InstantiationException(
- "Could not instantiate configuration, and no configuration initialization file was found (" + identity + ")" );
+ "Could not instantiate configuration, and no configuration initialization file was found ("
+ + identity + ")" );
ex.initCause( e1 );
throw ex;
}
@@ -319,23 +323,29 @@ public interface Configuration<T>
{
EntityBuilder<V> configBuilder = buildUow.newEntityBuilder( configType, identity );
String resourceName = identity + ".properties";
- InputStream asStream = getResource( compositeType, resourceName );
- if( asStream != null )
+ try( InputStream asStream = getResource( compositeType, resourceName ) )
{
- try
- {
- PropertyMapper.map( asStream, (Composite) configBuilder.instance() );
- return configBuilder.newInstance();
- }
- catch( IOException e1 )
+ if( asStream != null )
{
- InstantiationException exception = new InstantiationException(
- "Could not read underlying Properties file." );
- exception.initCause( e1 );
- throw exception;
+ try
+ {
+ PropertyMapper.map( asStream, (Composite) configBuilder.instance() );
+ return configBuilder.newInstance();
+ }
+ catch( IOException e1 )
+ {
+ InstantiationException exception = new InstantiationException(
+ "Could not read underlying Properties file." );
+ exception.initCause( e1 );
+ throw exception;
+ }
}
+ return null;
+ }
+ catch( IOException ignored )
+ {
+ return null;
}
- return null;
}
private InputStream getResource( Class<?> type, String resourceName )
@@ -348,53 +358,57 @@ public interface Configuration<T>
return type.getResourceAsStream( resourceName );
}
- private <C, V extends HasIdentity> V tryLoadJsonFile(UnitOfWork uow,
- Class<C> compositeType,
- Class<V> configType,
- Identity identity
+ private <C, V extends HasIdentity> V tryLoadJsonFile( UnitOfWork uow,
+ Class<C> compositeType,
+ Class<V> configType,
+ Identity identity
)
{
- return readConfig( uow, compositeType, configType, identity, ValueSerialization.Formats.JSON, ".json" );
+ return readConfig( uow, compositeType, configType, identity, Serialization.Formats.JSON, ".json" );
}
- private <C, V extends HasIdentity> V tryLoadYamlFile(UnitOfWork uow,
- Class<C> compositeType,
- Class<V> configType,
- Identity identity
+ private <C, V extends HasIdentity> V tryLoadYamlFile( UnitOfWork uow,
+ Class<C> compositeType,
+ Class<V> configType,
+ Identity identity
)
{
- return readConfig( uow, compositeType, configType, identity, ValueSerialization.Formats.YAML, ".yaml" );
+ return readConfig( uow, compositeType, configType, identity, Serialization.Formats.YAML, ".yaml" );
}
- private <C, V extends HasIdentity> V tryLoadXmlFile(UnitOfWork uow,
- Class<C> compositeType,
- Class<V> configType,
- Identity identity
+ private <C, V extends HasIdentity> V tryLoadXmlFile( UnitOfWork uow,
+ Class<C> compositeType,
+ Class<V> configType,
+ Identity identity
)
{
- return readConfig( uow, compositeType, configType, identity, ValueSerialization.Formats.XML, ".xml" );
+ return readConfig( uow, compositeType, configType, identity, Serialization.Formats.XML, ".xml" );
}
- private <C, V extends HasIdentity> V readConfig(UnitOfWork uow,
- Class<C> compositeType,
- Class<V> configType,
- Identity identity,
- String format,
- String extension
+ private <C, V extends HasIdentity> V readConfig( UnitOfWork uow,
+ Class<C> compositeType,
+ Class<V> configType,
+ Identity identity,
+ String format,
+ String extension
)
{
- for( ServiceReference<ValueSerialization> serializerRef : valueSerialization )
+ for( ServiceReference<Deserializer> serializerRef : stateDeserializers )
{
ServiceTags serviceTags = serializerRef.metaInfo( ServiceTags.class );
if( serviceTags.hasTag( format ) )
{
String resourceName = identity + extension;
- InputStream asStream = getResource( compositeType, resourceName );
- if( asStream != null )
+ try( InputStream asStream = getResource( compositeType, resourceName ) )
{
- V configObject = serializerRef.get().deserialize( uow.module(), configType, asStream );
- return uow.toEntity( configType, configObject );
+ if( asStream != null )
+ {
+ V configObject = serializerRef.get().deserialize( uow.module(), configType,
+ new InputStreamReader( asStream ) );
+ return uow.toEntity( configType, configObject );
+ }
}
+ catch( IOException ignored ) {}
}
}
return null;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/entity/EntityDescriptor.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/entity/EntityDescriptor.java b/core/api/src/main/java/org/apache/polygene/api/entity/EntityDescriptor.java
index 1ff6180..bac90e1 100644
--- a/core/api/src/main/java/org/apache/polygene/api/entity/EntityDescriptor.java
+++ b/core/api/src/main/java/org/apache/polygene/api/entity/EntityDescriptor.java
@@ -20,18 +20,14 @@
package org.apache.polygene.api.entity;
-import org.apache.polygene.api.association.AssociationStateDescriptor;
import org.apache.polygene.api.composite.CompositeDescriptor;
-import org.apache.polygene.api.composite.StatefulCompositeDescriptor;
+import org.apache.polygene.api.composite.StatefulAssociationCompositeDescriptor;
/**
* Entity Descriptor.
*/
public interface EntityDescriptor
- extends CompositeDescriptor, StatefulCompositeDescriptor
+ extends CompositeDescriptor, StatefulAssociationCompositeDescriptor
{
- @Override
- AssociationStateDescriptor state();
-
boolean queryable();
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/serialization/Deserializer.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/serialization/Deserializer.java b/core/api/src/main/java/org/apache/polygene/api/serialization/Deserializer.java
new file mode 100644
index 0000000..7ab1c44
--- /dev/null
+++ b/core/api/src/main/java/org/apache/polygene/api/serialization/Deserializer.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.api.serialization;
+
+import java.io.InputStream;
+import java.io.Reader;
+import java.util.function.Function;
+import java.util.stream.Stream;
+import org.apache.polygene.api.structure.ModuleDescriptor;
+import org.apache.polygene.api.type.ValueType;
+
+public interface Deserializer
+{
+ <T> T deserialize( ModuleDescriptor module, ValueType valueType, InputStream state );
+
+ <T> T deserialize( ModuleDescriptor module, ValueType valueType, Reader state );
+
+ <T> T deserialize( ModuleDescriptor module, ValueType valueType, String state );
+
+ <T> Function<String, T> deserializeFunction( ModuleDescriptor module, ValueType valueType );
+
+ <T> Stream<T> deserializeEach( ModuleDescriptor module, ValueType valueType, Iterable<String> states );
+
+ <T> Stream<T> deserializeEach( ModuleDescriptor module, ValueType valueType, String... states );
+
+ <T> T fromBytes( ModuleDescriptor module, ValueType valueType, byte[] bytes );
+
+ <T> Function<byte[], T> fromBytesFunction( ModuleDescriptor module, ValueType valueType );
+
+ <T> Stream<T> fromBytesEach( ModuleDescriptor module, ValueType valueType, Iterable<byte[]> states );
+
+ <T> Stream<T> fromBytesEach( ModuleDescriptor module, ValueType valueType, byte[]... states );
+
+ <T> T deserialize( ModuleDescriptor module, Class<T> type, InputStream state );
+
+ <T> T deserialize( ModuleDescriptor module, Class<T> type, Reader state );
+
+ <T> T deserialize( ModuleDescriptor module, Class<T> type, String state );
+
+ <T> Function<String, T> deserializeFunction( ModuleDescriptor module, Class<T> type );
+
+ <T> Stream<T> deserializeEach( ModuleDescriptor module, Class<T> type, Iterable<String> states );
+
+ <T> Stream<T> deserializeEach( ModuleDescriptor module, Class<T> type, String... states );
+
+ <T> T fromBytes( ModuleDescriptor module, Class<T> type, byte[] bytes );
+
+ <T> Function<byte[], T> fromBytesFunction( ModuleDescriptor module, Class<T> type );
+
+ <T> Stream<T> fromBytesEach( ModuleDescriptor module, Class<T> type, Iterable<byte[]> states );
+
+ <T> Stream<T> fromBytesEach( ModuleDescriptor module, Class<T> type, byte[]... states );
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/serialization/Serialization.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/serialization/Serialization.java b/core/api/src/main/java/org/apache/polygene/api/serialization/Serialization.java
new file mode 100644
index 0000000..ff1d32f
--- /dev/null
+++ b/core/api/src/main/java/org/apache/polygene/api/serialization/Serialization.java
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.api.serialization;
+
+/**
+ *
+ */
+public interface Serialization extends Serializer, Deserializer
+{
+ /**
+ * Serialization format @Service tags.
+ *
+ * <p>
+ * Serialization implementations should be tagged with theses at assembly time so that consumers can
+ * specify which format they need.
+ * </p>
+ */
+ interface Formats
+ {
+ /**
+ * Tag a Serialization service that support the JSON format.
+ */
+ String JSON = "json";
+ /**
+ * Tag a Serialization service that support the XML format.
+ */
+ String XML = "xml";
+ /**
+ * Tag a Serialization service that support the YAML format.
+ */
+ String YAML = "yaml";
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/serialization/SerializationException.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/serialization/SerializationException.java b/core/api/src/main/java/org/apache/polygene/api/serialization/SerializationException.java
new file mode 100644
index 0000000..aeb0bfa
--- /dev/null
+++ b/core/api/src/main/java/org/apache/polygene/api/serialization/SerializationException.java
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.api.serialization;
+
+/**
+ * Serialization Exception.
+ */
+public class SerializationException extends RuntimeException
+{
+ public SerializationException( String message )
+ {
+ super( message );
+ }
+
+ public SerializationException( String message, Throwable cause )
+ {
+ super( message, cause );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/serialization/Serializer.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/serialization/Serializer.java b/core/api/src/main/java/org/apache/polygene/api/serialization/Serializer.java
new file mode 100644
index 0000000..9f9f47d
--- /dev/null
+++ b/core/api/src/main/java/org/apache/polygene/api/serialization/Serializer.java
@@ -0,0 +1,247 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.api.serialization;
+
+import java.io.OutputStream;
+import java.io.Writer;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Stream;
+import org.apache.polygene.api.common.Optional;
+
+// TODO QUID Remove Optional?
+public interface Serializer
+{
+ void serialize( Options options, Writer writer, @Optional Object object );
+
+ void serialize( Options options, OutputStream output, @Optional Object object );
+
+ void serialize( Writer writer, @Optional Object object );
+
+ void serialize( OutputStream output, @Optional Object object );
+
+ String serialize( Options options, @Optional Object object );
+
+ String serialize( @Optional Object object );
+
+ <T> Function<T, String> serializeFunction( Options options );
+
+ <T> Function<T, String> serializeFunction();
+
+ Stream<String> serializeEach( Options options, Iterable<Object> objects );
+
+ Stream<String> serializeEach( Iterable<Object> objects );
+
+ Stream<String> serializeEach( Options options, Object... objects );
+
+ Stream<String> serializeEach( Object... objects );
+
+ byte[] toBytes( Options options, @Optional Object object );
+
+ byte[] toBytes( @Optional Object object );
+
+ <T> Function<T, byte[]> toBytesFunction( Options options );
+
+ <T> Function<T, byte[]> toBytesFunction();
+
+ Stream<byte[]> toBytesEach( Options options, Iterable<Object> objects );
+
+ Stream<byte[]> toBytesEach( Iterable<Object> objects );
+
+ Stream<byte[]> toBytesEach( Options options, Object... objects );
+
+ Stream<byte[]> toBytesEach( Object... objects );
+
+ /**
+ * State serializer options.
+ *
+ * Use {@link #builder()} to create new instances.
+ *
+ * All options provided by the builder are safe to use with all serialization extensions. Serialization extensions
+ * might provide more options, see {@link #option(String)} and the respective extension documentation.
+ */
+ // TODO rootTypeInfo / nestedTypeInfo
+ interface Options
+ {
+ /**
+ * Default state serializer options.
+ *
+ * {@link #includeTypeInfo()} set to {@literal true}.
+ */
+ Options DEFAULT = builder().build();
+
+ /**
+ * Default state serializer options with {@link #includeTypeInfo()} set to {@literal false}.
+ */
+ Options NO_TYPE_INFO = builder().withoutTypeInfo().build();
+
+ /**
+ * Include type information in the serialized form of nested values.
+ *
+ * Boolean flag to include type information in the serialized form of nested values types.
+ * Each serialization extension is free to chose how to represent this type information.
+ *
+ * This is enabled by default to allow for polymorphic deserialization.
+ *
+ * Let's say you have a type hierarchy of values as follows ;
+ * <code>
+ * interface Parent { Property<String> something(); }
+ * interface Child1 { Property<Long> number(); }
+ * interface Child2 { Property<Duration> duration(); }
+ * </code>
+ * and want to serialize and deserialize a set of values like this one ;
+ * <code>
+ * interface MyValue { Property<Parent> polymorphicValue(); }
+ * </code>
+ * that is a view of a value composite that also has the following fragments ;
+ * <code>
+ * interface MyValueWithNumber { Property<Child1> polymorphicValue(); }
+ * interface MyValueWithDuration { Property<Child2> polymorphicValue(); }
+ * </code>
+ * when deserializing, the {@link Deserializer} needs a way to know which specialization
+ * type to use to deserialize the value state, {@literal Child1} or {@literal Child2} in our example.
+ *
+ * If the deserializer can't know it use the type information from the
+ * {@link org.apache.polygene.api.type.ValueType} provided at deserialization time.
+ *
+ * Disable it using {@link Builder#withoutTypeInfo()} if you are sure you don't need this.
+ *
+ * @return {@literal true} if type information must be included in the serialized form of nested values,
+ * {@literal false} otherwise
+ */
+ boolean includeTypeInfo();
+
+ /**
+ * Query for an option's value.
+ *
+ * @param option the option
+ * @return the option's value, {@literal} null if absent
+ */
+ String option( String option );
+
+ /**
+ * Create a new builder of {@link Options}
+ *
+ * @return a new builder
+ */
+ static Builder builder()
+ {
+ return new Builder();
+ }
+
+ /**
+ * Builder for {@link Options}.
+ *
+ * This builder is mutable, built instances are not.
+ */
+ final class Builder
+ {
+ private static final String INCLUDE_TYPE_INFO = "includeTypeInfo";
+
+ private static class Instance implements Options
+ {
+ private final Map<String, String> options;
+
+ private Instance( Map<String, String> options )
+ {
+ this.options = options;
+ }
+
+ @Override
+ public boolean includeTypeInfo()
+ {
+ return "true".equals( options.get( INCLUDE_TYPE_INFO ) );
+ }
+
+ @Override
+ public String option( String option )
+ {
+ return options.get( option );
+ }
+ }
+
+ private final Map<String, String> options = new HashMap<String, String>()
+ {{
+ put( INCLUDE_TYPE_INFO, "true" );
+ }};
+
+ /**
+ * Include type information in the serialized form of nested values.
+ *
+ * @return this builder
+ */
+ public Builder withTypeInfo()
+ {
+ return withOption( INCLUDE_TYPE_INFO, "true" );
+ }
+
+ /**
+ * Do not include type information in the serialized form of nested values.
+ *
+ * <strong>WARNING</strong>
+ * Without this, {@link Deserializer}s will use the provided
+ * {@link org.apache.polygene.api.type.ValueType} for instantiation potentially breaking polymorphism,
+ * see {@link Options#includeTypeInfo()}.
+ *
+ * @return this builder
+ * @see Builder#withTypeInfo()
+ */
+ public Builder withoutTypeInfo()
+ {
+ return withOption( INCLUDE_TYPE_INFO, "false" );
+ }
+
+ /**
+ * Set extension specific option.
+ *
+ * @param option the option to add
+ * @param value it's value
+ * @return this builder
+ */
+ public Builder withOption( String option, String value )
+ {
+ options.put( option, value );
+ return this;
+ }
+
+ /**
+ * Remove extension specific option.
+ *
+ * @param option the option to remove
+ * @return this builder
+ */
+ public Builder withoutOption( String option )
+ {
+ options.remove( option );
+ return this;
+ }
+
+ /**
+ * Build the options.
+ *
+ * @return a new immutable instance of {@link Options}.
+ */
+ public Options build()
+ {
+ return new Instance( Collections.unmodifiableMap( options ) );
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/serialization/package.html
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/serialization/package.html b/core/api/src/main/java/org/apache/polygene/api/serialization/package.html
new file mode 100644
index 0000000..fc2a3bd
--- /dev/null
+++ b/core/api/src/main/java/org/apache/polygene/api/serialization/package.html
@@ -0,0 +1,24 @@
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ ~
+ ~
+ -->
+<html>
+<body>
+<h2>Serialization API.</h2>
+</body>
+</html>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/type/CollectionType.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/type/CollectionType.java b/core/api/src/main/java/org/apache/polygene/api/type/CollectionType.java
index faf19c5..09a0aeb 100644
--- a/core/api/src/main/java/org/apache/polygene/api/type/CollectionType.java
+++ b/core/api/src/main/java/org/apache/polygene/api/type/CollectionType.java
@@ -22,6 +22,7 @@ package org.apache.polygene.api.type;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
+import java.util.Objects;
import java.util.Set;
import org.apache.polygene.api.util.Classes;
@@ -32,27 +33,52 @@ import org.apache.polygene.api.util.Classes;
public final class CollectionType
extends ValueType
{
-
public static boolean isCollection( Type type )
{
Class<?> cl = Classes.RAW_CLASS.apply( type );
- return cl.equals( Collection.class ) || cl.equals( List.class ) || cl.equals( Set.class );
+ return Collection.class.isAssignableFrom( cl );
+ }
+
+ public static CollectionType of( Class<?> type, ValueType collectedType )
+ {
+ return new CollectionType( type, collectedType );
+ }
+
+ public static CollectionType of( Class<?> type, Class<?> collectedType )
+ {
+ return of( type, ValueType.of( collectedType ) );
+ }
+
+ public static CollectionType collectionOf( ValueType collectedType )
+ {
+ return of( Collection.class, collectedType );
}
public static CollectionType collectionOf( Class<?> collectedType )
{
- return new CollectionType( Collection.class, ValueType.of( collectedType ) );
+ return of( Collection.class, collectedType );
+ }
+
+ public static CollectionType listOf( ValueType collectedType )
+ {
+ return of( List.class, collectedType );
}
public static CollectionType listOf( Class<?> collectedType )
{
- return new CollectionType( List.class, ValueType.of( collectedType ) );
+ return of( List.class, collectedType );
+ }
+
+ public static CollectionType setOf( ValueType collectedType )
+ {
+ return of( Set.class, collectedType );
}
public static CollectionType setOf( Class<?> collectedType )
{
- return new CollectionType( Set.class, ValueType.of( collectedType ) );
+ return of( Set.class, collectedType );
}
+
private ValueType collectedType;
public CollectionType( Class<?> type, ValueType collectedType )
@@ -70,6 +96,32 @@ public final class CollectionType
return collectedType;
}
+ public boolean isSet()
+ {
+ return Set.class.isAssignableFrom( primaryType() );
+ }
+
+ public boolean isList()
+ {
+ return List.class.isAssignableFrom( primaryType() );
+ }
+
+ @Override
+ public boolean equals( final Object o )
+ {
+ if( this == o ) { return true; }
+ if( o == null || getClass() != o.getClass() ) { return false; }
+ if( !super.equals( o ) ) { return false; }
+ CollectionType that = (CollectionType) o;
+ return Objects.equals( collectedType, that.collectedType );
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hash( super.hashCode(), collectedType );
+ }
+
@Override
public String toString()
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/type/EnumType.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/type/EnumType.java b/core/api/src/main/java/org/apache/polygene/api/type/EnumType.java
index ba7dc5a..9ae6feb 100644
--- a/core/api/src/main/java/org/apache/polygene/api/type/EnumType.java
+++ b/core/api/src/main/java/org/apache/polygene/api/type/EnumType.java
@@ -27,13 +27,12 @@ import java.lang.reflect.Type;
public final class EnumType
extends ValueType
{
-
public static boolean isEnum( Type type )
{
if( type instanceof Class )
{
Class<?> typeClass = (Class) type;
- return ( typeClass.isEnum() );
+ return typeClass.isEnum();
}
return false;
}
@@ -43,7 +42,7 @@ public final class EnumType
return new EnumType( type );
}
- public EnumType( Class<?> type )
+ private EnumType( Class<?> type )
{
super( type );
if( !isEnum( type ) )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/type/HasAssignableFromType.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/type/HasAssignableFromType.java b/core/api/src/main/java/org/apache/polygene/api/type/HasAssignableFromType.java
new file mode 100644
index 0000000..bfa7763
--- /dev/null
+++ b/core/api/src/main/java/org/apache/polygene/api/type/HasAssignableFromType.java
@@ -0,0 +1,33 @@
+package org.apache.polygene.api.type;
+
+import java.lang.reflect.Type;
+import java.util.Collections;
+import java.util.function.Predicate;
+
+import static java.util.stream.Collectors.toList;
+
+public class HasAssignableFromType<T extends HasTypes> extends HasTypesPredicate<T>
+{
+ public HasAssignableFromType( Type type )
+ {
+ super( Collections.singletonList( type ) );
+ }
+
+ public HasAssignableFromType( T hasTypes )
+ {
+ super( hasTypes.types().collect( toList() ) );
+ }
+
+ @Override
+ protected Predicate<Type> matchPredicate( Type candidate )
+ {
+ // TODO; what to do if there is ParameterizedType here??
+ // Now set to ClassCastException and see if anything surfaces
+ //if( candidate instanceof Class )
+ {
+ Class<?> clazz = (Class<?>) candidate;
+ return input -> !input.equals( candidate ) && clazz.isAssignableFrom( (Class<?>) input );
+ }
+ //return input -> input.equals( candidate );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/type/HasAssignableToType.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/type/HasAssignableToType.java b/core/api/src/main/java/org/apache/polygene/api/type/HasAssignableToType.java
new file mode 100644
index 0000000..0a8e3df
--- /dev/null
+++ b/core/api/src/main/java/org/apache/polygene/api/type/HasAssignableToType.java
@@ -0,0 +1,29 @@
+package org.apache.polygene.api.type;
+
+import java.lang.reflect.Type;
+import java.util.Collections;
+import java.util.function.Predicate;
+
+import static java.util.stream.Collectors.toList;
+
+public class HasAssignableToType<T extends HasTypes> extends HasTypesPredicate<T>
+{
+ public HasAssignableToType( Type type )
+ {
+ super( Collections.singletonList( type ) );
+ }
+
+ public HasAssignableToType( T hasTypes )
+ {
+ super( hasTypes.types().collect( toList() ) );
+ }
+
+ @Override
+ protected Predicate<Type> matchPredicate( Type candidate )
+ {
+ // TODO; what to do if there is ParameterizedType here??
+ // Now set to ClassCastException and see if anything surfaces
+ Class<?> clazz = (Class<?>) candidate;
+ return input -> !input.equals( candidate ) && ( (Class<?>) input ).isAssignableFrom( clazz );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/type/HasEqualOrAssignableFromType.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/type/HasEqualOrAssignableFromType.java b/core/api/src/main/java/org/apache/polygene/api/type/HasEqualOrAssignableFromType.java
new file mode 100644
index 0000000..190512e
--- /dev/null
+++ b/core/api/src/main/java/org/apache/polygene/api/type/HasEqualOrAssignableFromType.java
@@ -0,0 +1,25 @@
+package org.apache.polygene.api.type;
+
+import java.lang.reflect.Type;
+import java.util.function.Predicate;
+
+public class HasEqualOrAssignableFromType<T extends HasTypes> implements Predicate<T>
+{
+ private final Predicate<T> composedPredicate;
+
+ public HasEqualOrAssignableFromType( Type type )
+ {
+ composedPredicate = new HasEqualType<T>( type ).or( new HasAssignableFromType<>( type ) );
+ }
+
+ public HasEqualOrAssignableFromType( T hasTypes )
+ {
+ composedPredicate = new HasEqualType<>( hasTypes ).or( new HasAssignableFromType<>( hasTypes ) );
+ }
+
+ @Override
+ public boolean test( T hasTypes )
+ {
+ return composedPredicate.test( hasTypes );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/type/HasEqualOrAssignableToType.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/type/HasEqualOrAssignableToType.java b/core/api/src/main/java/org/apache/polygene/api/type/HasEqualOrAssignableToType.java
new file mode 100644
index 0000000..e54bf35
--- /dev/null
+++ b/core/api/src/main/java/org/apache/polygene/api/type/HasEqualOrAssignableToType.java
@@ -0,0 +1,25 @@
+package org.apache.polygene.api.type;
+
+import java.lang.reflect.Type;
+import java.util.function.Predicate;
+
+public class HasEqualOrAssignableToType<T extends HasTypes> implements Predicate<T>
+{
+ private final Predicate<T> composedPredicate;
+
+ public HasEqualOrAssignableToType( Type type )
+ {
+ composedPredicate = new HasEqualType<T>( type ).or( new HasAssignableToType<>( type ) );
+ }
+
+ public HasEqualOrAssignableToType( T hasTypes )
+ {
+ composedPredicate = new HasEqualType<>( hasTypes ).or( new HasAssignableToType<>( hasTypes ) );
+ }
+
+ @Override
+ public boolean test( T hasTypes )
+ {
+ return composedPredicate.test( hasTypes );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/type/HasEqualType.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/type/HasEqualType.java b/core/api/src/main/java/org/apache/polygene/api/type/HasEqualType.java
new file mode 100644
index 0000000..18ebce7
--- /dev/null
+++ b/core/api/src/main/java/org/apache/polygene/api/type/HasEqualType.java
@@ -0,0 +1,26 @@
+package org.apache.polygene.api.type;
+
+import java.lang.reflect.Type;
+import java.util.Collections;
+import java.util.function.Predicate;
+
+import static java.util.stream.Collectors.toList;
+
+public class HasEqualType<T extends HasTypes> extends HasTypesPredicate<T>
+{
+ public HasEqualType( Type type )
+ {
+ super( Collections.singletonList( type ) );
+ }
+
+ public HasEqualType( T hasTypes )
+ {
+ super( hasTypes.types().collect( toList() ) );
+ }
+
+ @Override
+ protected Predicate<Type> matchPredicate( Type candidate )
+ {
+ return candidate::equals;
+ }
+}
[23/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/MigrationService.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/MigrationService.java b/extensions/migration/src/main/java/org/apache/polygene/migration/MigrationService.java
index 09b4663..79e1583 100644
--- a/extensions/migration/src/main/java/org/apache/polygene/migration/MigrationService.java
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/MigrationService.java
@@ -22,9 +22,12 @@ package org.apache.polygene.migration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.Json;
+import javax.json.JsonException;
+import javax.json.JsonObject;
+import javax.json.JsonObjectBuilder;
+import javax.json.JsonString;
+import javax.json.JsonValue;
import org.apache.polygene.api.activation.ActivatorAdapter;
import org.apache.polygene.api.activation.Activators;
import org.apache.polygene.api.configuration.Configuration;
@@ -39,14 +42,18 @@ import org.apache.polygene.api.structure.Application;
import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
import org.apache.polygene.migration.assembly.EntityMigrationRule;
import org.apache.polygene.migration.assembly.MigrationBuilder;
+import org.apache.polygene.migration.assembly.MigrationContext;
import org.apache.polygene.migration.assembly.MigrationRule;
import org.apache.polygene.spi.entitystore.EntityStore;
import org.apache.polygene.spi.entitystore.helpers.JSONKeys;
import org.apache.polygene.spi.entitystore.helpers.Migration;
import org.apache.polygene.spi.entitystore.helpers.StateStore;
+import org.apache.polygene.spi.serialization.JsonSerialization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static java.util.Arrays.asList;
+
/**
* Migration service. This is used by MapEntityStore EntityStore implementations to
* migrate JSON state for Entities. To use it register the service so that the EntityStore
@@ -63,24 +70,21 @@ import org.slf4j.LoggerFactory;
public interface MigrationService
extends Migration
{
-
void initialize()
throws Exception;
class Activator
extends ActivatorAdapter<ServiceReference<MigrationService>>
{
-
@Override
public void afterActivation( ServiceReference<MigrationService> activated )
throws Exception
{
activated.get().initialize();
}
-
}
- public class MigrationMixin
+ class MigrationMixin
implements MigrationService, Migrator
{
@Structure
@@ -98,6 +102,9 @@ public interface MigrationService
@Service
EntityStore entityStore;
+ @Service
+ JsonSerialization serialization;
+
@Structure
UnitOfWorkFactory uowf;
@@ -111,38 +118,61 @@ public interface MigrationService
Iterable<MigrationEvents> migrationEvents;
@Override
- public boolean migrate( JSONObject state, String toVersion, StateStore stateStore )
- throws JSONException
+ public JsonObject migrate( final JsonObject state, String toVersion, StateStore stateStore )
+ throws JsonException
{
// Get current version
- String fromVersion = state.optString( JSONKeys.APPLICATION_VERSION, "0.0" );
+ String fromVersion = state.getString( JSONKeys.APPLICATION_VERSION, "0.0" );
- Iterable<EntityMigrationRule> matchedRules = builder.entityMigrationRules().rulesBetweenVersions( fromVersion, toVersion );
+ Iterable<EntityMigrationRule> matchedRules = builder.entityMigrationRules()
+ .rulesBetweenVersions( fromVersion, toVersion );
+ JsonObject migratedState = state;
boolean changed = false;
+ List<String> failures = new ArrayList<>();
if( matchedRules != null )
{
for( EntityMigrationRule matchedRule : matchedRules )
{
- boolean ruleExecuted = matchedRule.upgrade( state, stateStore, migrator );
+ MigrationContext context = new MigrationContext();
- if( ruleExecuted && log.isDebugEnabled() )
+ migratedState = matchedRule.upgrade( context, migratedState, stateStore, migrator );
+
+ if( context.isSuccess() && context.hasChanged() && log.isDebugEnabled() )
{
log.debug( matchedRule.toString() );
}
- changed = ruleExecuted || changed;
+ failures.addAll( context.failures() );
+ changed = context.hasChanged() || changed;
}
}
- state.put( JSONKeys.APPLICATION_VERSION, toVersion );
+ JsonObjectBuilder appVersionBuilder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : migratedState.entrySet() )
+ {
+ appVersionBuilder.add( entry.getKey(), entry.getValue() );
+ }
+ appVersionBuilder.add( JSONKeys.APPLICATION_VERSION, toVersion );
+ migratedState = appVersionBuilder.build();
+
+ if( failures.size() > 0 )
+ {
+ log.warn( "Migration of {} from {} to {} aborted, failed operation(s):\n{}",
+ state.getString( JSONKeys.IDENTITY ), fromVersion, toVersion,
+ String.join( "\n\t", failures ) );
+ return state;
+ }
if( changed )
{
- log.info( "Migrated " + state.getString( JSONKeys.IDENTITY ) + " from " + fromVersion + " to " + toVersion );
+ log.info( "Migrated {} from {} to {}",
+ migratedState.getString( JSONKeys.IDENTITY ), fromVersion, toVersion );
+ return migratedState;
}
- return changed;
+ // Nothing done
+ return state;
}
@Override
@@ -193,304 +223,571 @@ public interface MigrationService
// Migrator implementation
@Override
- public boolean addProperty( JSONObject state, String name, Object defaultValue )
- throws JSONException
+ public JsonObject addProperty( MigrationContext context, JsonObject state, String name, Object defaultValue )
+ throws JsonException
{
- JSONObject properties = state.getJSONObject( JSONKeys.PROPERTIES );
- if( !properties.has( name ) )
+ JsonObject properties = state.getJsonObject( JSONKeys.PROPERTIES );
+ if( !properties.containsKey( name ) )
{
- if( defaultValue == null )
+ JsonValue value = serialization.toJson( defaultValue );
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : state.entrySet() )
{
- properties.put( name, JSONObject.NULL );
+ String key = entry.getKey();
+ if( !JSONKeys.PROPERTIES.equals( key ) )
+ {
+ builder.add( key, entry.getValue() );
+ }
}
- else
+ JsonObjectBuilder propBuilder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : properties.entrySet() )
{
- properties.put( name, defaultValue );
+ propBuilder.add( entry.getKey(), entry.getValue() );
}
+ propBuilder.add( name, value );
+ builder.add( JSONKeys.PROPERTIES, propBuilder.build() );
+ context.markAsChanged();
for( MigrationEvents migrationEvent : migrationEvents )
{
migrationEvent.propertyAdded( state.getString( JSONKeys.IDENTITY ), name, defaultValue );
}
- return true;
+ return builder.build();
}
else
{
- return false;
+ context.addFailure( "Add property " + name + ", default:" + defaultValue );
+ return state;
}
}
@Override
- public boolean removeProperty( JSONObject state, String name )
- throws JSONException
+ public JsonObject removeProperty( MigrationContext context, JsonObject state, String name )
+ throws JsonException
{
- JSONObject properties = state.getJSONObject( JSONKeys.PROPERTIES );
- if( properties.has( name ) )
+ JsonObject properties = state.getJsonObject( JSONKeys.PROPERTIES );
+ if( properties.containsKey( name ) )
{
- properties.remove( name );
- for( MigrationEvents migrationEvent : migrationEvents )
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : state.entrySet() )
{
- migrationEvent.propertyRemoved( state.getString( JSONKeys.IDENTITY ), name );
+ String key = entry.getKey();
+ if( !JSONKeys.PROPERTIES.equals( key ) )
+ {
+ builder.add( key, entry.getValue() );
+ }
+ }
+ JsonObjectBuilder propBuilder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : properties.entrySet() )
+ {
+ String key = entry.getKey();
+ if( !name.equals( key ) )
+ {
+ propBuilder.add( key, entry.getValue() );
+ }
+ else
+ {
+ context.markAsChanged();
+ }
}
+ builder.add( JSONKeys.PROPERTIES, propBuilder.build() );
- return true;
+ if( context.hasChanged() )
+ {
+ for( MigrationEvents migrationEvent : migrationEvents )
+ {
+ migrationEvent.propertyRemoved( state.getString( JSONKeys.IDENTITY ), name );
+ }
+ }
+
+ return builder.build();
}
else
{
- return false;
+ context.addFailure( "Remove property " + name );
+ return state;
}
}
@Override
- public boolean renameProperty( JSONObject state, String from, String to )
- throws JSONException
+ public JsonObject renameProperty( MigrationContext context, JsonObject state, String from, String to )
+ throws JsonException
{
- JSONObject properties = state.getJSONObject( JSONKeys.PROPERTIES );
- if( properties.has( from ) )
+ JsonObject properties = state.getJsonObject( JSONKeys.PROPERTIES );
+ if( properties.containsKey( from ) )
{
- Object value = properties.remove( from );
- properties.put( to, value );
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : state.entrySet() )
+ {
+ String key = entry.getKey();
+ if( !JSONKeys.PROPERTIES.equals( key ) )
+ {
+ builder.add( key, entry.getValue() );
+ }
+ }
+ JsonObjectBuilder propBuilder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : properties.entrySet() )
+ {
+ String key = entry.getKey();
+ if( from.equals( key ) )
+ {
+ propBuilder.add( to, entry.getValue() );
+ context.markAsChanged();
+ }
+ else
+ {
+ propBuilder.add( key, entry.getValue() );
+ }
+ }
+ builder.add( JSONKeys.PROPERTIES, propBuilder.build() );
+
for( MigrationEvents migrationEvent : migrationEvents )
{
migrationEvent.propertyRenamed( state.getString( JSONKeys.IDENTITY ), from, to );
}
- return true;
+ return builder.build();
}
else
{
- return false;
+ context.addFailure( "Rename property " + from + " to " + to );
+ return state;
}
}
@Override
- public boolean addAssociation( JSONObject state, String name, String defaultReference )
- throws JSONException
+ public JsonObject addAssociation( MigrationContext context, JsonObject state, String name,
+ String defaultReference )
+ throws JsonException
{
- JSONObject associations = state.getJSONObject( JSONKeys.ASSOCIATIONS );
- if( !associations.has( name ) )
+ JsonObject associations = state.getJsonObject( JSONKeys.ASSOCIATIONS );
+ if( !associations.containsKey( name ) )
{
- if( defaultReference == null )
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : state.entrySet() )
{
- associations.put( name, JSONObject.NULL );
+ String key = entry.getKey();
+ if( !JSONKeys.ASSOCIATIONS.equals( key ) )
+ {
+ builder.add( key, entry.getValue() );
+ }
}
- else
+ JsonObjectBuilder assocBuilder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : associations.entrySet() )
{
- associations.put( name, defaultReference );
+ assocBuilder.add( entry.getKey(), entry.getValue() );
}
+ JsonValue value = serialization.toJson( defaultReference );
+ assocBuilder.add( name, value );
+ builder.add( JSONKeys.ASSOCIATIONS, assocBuilder.build() );
+ context.markAsChanged();
for( MigrationEvents migrationEvent : migrationEvents )
{
migrationEvent.associationAdded( state.getString( JSONKeys.IDENTITY ), name, defaultReference );
}
- return true;
+ return builder.build();
}
else
{
- return false;
+ context.addFailure( "Add association " + name + ", default:" + defaultReference );
+ return state;
}
}
@Override
- public boolean removeAssociation( JSONObject state, String name )
- throws JSONException
+ public JsonObject removeAssociation( MigrationContext context, JsonObject state, String name )
+ throws JsonException
{
- JSONObject associations = state.getJSONObject( JSONKeys.ASSOCIATIONS );
- if( associations.has( name ) )
+ JsonObject associations = state.getJsonObject( JSONKeys.ASSOCIATIONS );
+ if( associations.containsKey( name ) )
{
- associations.remove( name );
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : state.entrySet() )
+ {
+ String key = entry.getKey();
+ if( !JSONKeys.ASSOCIATIONS.equals( key ) )
+ {
+ builder.add( key, entry.getValue() );
+ }
+ }
+ JsonObjectBuilder assocBuilder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : associations.entrySet() )
+ {
+ String key = entry.getKey();
+ if( !name.equals( key ) )
+ {
+ assocBuilder.add( key, entry.getValue() );
+ }
+ else
+ {
+ context.markAsChanged();
+ }
+ }
+ builder.add( JSONKeys.ASSOCIATIONS, assocBuilder.build() );
+
for( MigrationEvents migrationEvent : migrationEvents )
{
migrationEvent.associationRemoved( state.getString( JSONKeys.IDENTITY ), name );
}
- return true;
+ return builder.build();
}
else
{
- return false;
+ context.addFailure( "Remove association " + name );
+ return state;
}
}
@Override
- public boolean renameAssociation( JSONObject state, String from, String to )
- throws JSONException
+ public JsonObject renameAssociation( MigrationContext context, JsonObject state, String from, String to )
+ throws JsonException
{
- JSONObject associations = state.getJSONObject( JSONKeys.ASSOCIATIONS );
- if( associations.has( from ) )
+ JsonObject associations = state.getJsonObject( JSONKeys.ASSOCIATIONS );
+ if( associations.containsKey( from ) )
{
- Object value = associations.remove( from );
- associations.put( to, value );
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : state.entrySet() )
+ {
+ String key = entry.getKey();
+ if( !JSONKeys.ASSOCIATIONS.equals( key ) )
+ {
+ builder.add( key, entry.getValue() );
+ }
+ }
+ JsonObjectBuilder assocBuilder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : associations.entrySet() )
+ {
+ String key = entry.getKey();
+ if( from.equals( key ) )
+ {
+ assocBuilder.add( to, entry.getValue() );
+ context.markAsChanged();
+ }
+ else
+ {
+ assocBuilder.add( to, entry.getValue() );
+ }
+ }
+ builder.add( JSONKeys.ASSOCIATIONS, assocBuilder.build() );
for( MigrationEvents migrationEvent : migrationEvents )
{
migrationEvent.associationRenamed( state.getString( JSONKeys.IDENTITY ), from, to );
}
- return true;
+ return builder.build();
}
else
{
- return false;
+ context.addFailure( "Rename association " + from + " to " + to );
+ return state;
}
}
@Override
- public boolean addManyAssociation( JSONObject state, String name, String... defaultReferences )
- throws JSONException
+ public JsonObject addManyAssociation( MigrationContext context, JsonObject state, String name,
+ String... defaultReferences )
+ throws JsonException
{
- JSONObject manyAssociations = state.getJSONObject( JSONKeys.MANY_ASSOCIATIONS );
- if( !manyAssociations.has( name ) )
+ JsonObject manyAssociations = state.getJsonObject( JSONKeys.MANY_ASSOCIATIONS );
+ if( !manyAssociations.containsKey( name ) )
{
- JSONArray references = new JSONArray();
- for( String reference : defaultReferences )
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : state.entrySet() )
+ {
+ String key = entry.getKey();
+ if( !JSONKeys.MANY_ASSOCIATIONS.equals( key ) )
+ {
+ builder.add( key, entry.getValue() );
+ }
+ }
+ JsonObjectBuilder assocBuilder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : manyAssociations.entrySet() )
{
- references.put( reference );
+ assocBuilder.add( entry.getKey(), entry.getValue() );
}
- manyAssociations.put( name, references );
+ JsonValue value = serialization.toJson( defaultReferences );
+ assocBuilder.add( name, value );
+ builder.add( JSONKeys.MANY_ASSOCIATIONS, assocBuilder.build() );
+ context.markAsChanged();
for( MigrationEvents migrationEvent : migrationEvents )
{
- migrationEvent.manyAssociationAdded( state.getString( JSONKeys.IDENTITY ), name, defaultReferences );
+ migrationEvent.manyAssociationAdded( state.getString( JSONKeys.IDENTITY ), name,
+ defaultReferences );
}
- return true;
+ return builder.build();
}
else
{
- return false;
+ context.addFailure( "Add many-association " + name + ", default:" + asList( defaultReferences ) );
+ return state;
}
}
@Override
- public boolean removeManyAssociation( JSONObject state, String name )
- throws JSONException
+ public JsonObject removeManyAssociation( MigrationContext context, JsonObject state, String name )
+ throws JsonException
{
- JSONObject manyAssociations = state.getJSONObject( JSONKeys.MANY_ASSOCIATIONS );
- if( manyAssociations.has( name ) )
+ JsonObject manyAssociations = state.getJsonObject( JSONKeys.MANY_ASSOCIATIONS );
+ if( manyAssociations.containsKey( name ) )
{
- manyAssociations.remove( name );
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : state.entrySet() )
+ {
+ String key = entry.getKey();
+ if( !JSONKeys.MANY_ASSOCIATIONS.equals( key ) )
+ {
+ builder.add( key, entry.getValue() );
+ }
+ }
+ JsonObjectBuilder assocBuilder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : manyAssociations.entrySet() )
+ {
+ String key = entry.getKey();
+ if( !name.equals( key ) )
+ {
+ assocBuilder.add( key, entry.getValue() );
+ }
+ else
+ {
+ context.markAsChanged();
+ }
+ }
+ builder.add( JSONKeys.MANY_ASSOCIATIONS, assocBuilder.build() );
+
for( MigrationEvents migrationEvent : migrationEvents )
{
migrationEvent.manyAssociationRemoved( state.getString( JSONKeys.IDENTITY ), name );
}
- return true;
+ return builder.build();
}
else
{
- return false;
+ context.addFailure( "Remove many-association " + name );
+ return state;
}
}
@Override
- public boolean renameManyAssociation( JSONObject state, String from, String to )
- throws JSONException
+ public JsonObject renameManyAssociation( MigrationContext context, JsonObject state, String from, String to )
+ throws JsonException
{
- JSONObject manyAssociations = state.getJSONObject( JSONKeys.MANY_ASSOCIATIONS );
- if( manyAssociations.has( from ) )
+ JsonObject manyAssociations = state.getJsonObject( JSONKeys.MANY_ASSOCIATIONS );
+ if( manyAssociations.containsKey( from ) )
{
- Object value = manyAssociations.remove( from );
- manyAssociations.put( to, value );
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : state.entrySet() )
+ {
+ String key = entry.getKey();
+ if( !JSONKeys.MANY_ASSOCIATIONS.equals( key ) )
+ {
+ builder.add( key, entry.getValue() );
+ }
+ }
+ JsonObjectBuilder assocBuilder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : manyAssociations.entrySet() )
+ {
+ String key = entry.getKey();
+ if( from.equals( key ) )
+ {
+ context.markAsChanged();
+ assocBuilder.add( to, entry.getValue() );
+ }
+ else
+ {
+ assocBuilder.add( key, entry.getValue() );
+ }
+ }
+ builder.add( JSONKeys.MANY_ASSOCIATIONS, assocBuilder.build() );
for( MigrationEvents migrationEvent : migrationEvents )
{
migrationEvent.manyAssociationRenamed( state.getString( JSONKeys.IDENTITY ), from, to );
}
- return true;
+ return builder.build();
}
else
{
- return false;
+ context.addFailure( "Rename many-association " + from + " to " + to );
+ return state;
}
}
@Override
- public boolean addNamedAssociation( JSONObject state, String name, Map<String, String> defaultReferences )
- throws JSONException
+ public JsonObject addNamedAssociation( MigrationContext context, JsonObject state, String name,
+ Map<String, String> defaultReferences )
+ throws JsonException
{
- JSONObject namedAssociations = state.getJSONObject( JSONKeys.NAMED_ASSOCIATIONS );
- if( !namedAssociations.has( name ) )
+ JsonObject namedAssociations = state.getJsonObject( JSONKeys.NAMED_ASSOCIATIONS );
+ if( !namedAssociations.containsKey( name ) )
{
- JSONObject references = new JSONObject();
- for( Map.Entry<String, String> namedRef : defaultReferences.entrySet() )
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : state.entrySet() )
+ {
+ String key = entry.getKey();
+ if( !JSONKeys.NAMED_ASSOCIATIONS.equals( key ) )
+ {
+ builder.add( key, entry.getValue() );
+ }
+ }
+ JsonObjectBuilder assocBuilder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : namedAssociations.entrySet() )
{
- references.put( namedRef.getKey(), namedRef.getValue() );
+ assocBuilder.add( entry.getKey(), entry.getValue() );
}
- namedAssociations.put( name, references );
+ JsonValue value = serialization.toJson( defaultReferences );
+ assocBuilder.add( name, value );
+ builder.add( JSONKeys.NAMED_ASSOCIATIONS, assocBuilder.build() );
+ context.markAsChanged();
for( MigrationEvents migrationEvent : migrationEvents )
{
- migrationEvent.namedAssociationAdded( state.getString( JSONKeys.IDENTITY ), name, defaultReferences );
+ migrationEvent.namedAssociationAdded( state.getString( JSONKeys.IDENTITY ), name,
+ defaultReferences );
}
- return true;
+ return builder.build();
}
else
{
- return false;
+ context.addFailure( "Add named-association " + name + ", default:" + defaultReferences );
+ return state;
}
}
@Override
- public boolean removeNamedAssociation( JSONObject state, String name )
- throws JSONException
+ public JsonObject removeNamedAssociation( MigrationContext context, JsonObject state, String name )
+ throws JsonException
{
- JSONObject namedAssociations = state.getJSONObject( JSONKeys.NAMED_ASSOCIATIONS );
- if( namedAssociations.has( name ) )
+ JsonObject namedAssociations = state.getJsonObject( JSONKeys.NAMED_ASSOCIATIONS );
+ if( namedAssociations.containsKey( name ) )
{
- namedAssociations.remove( name );
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : state.entrySet() )
+ {
+ String key = entry.getKey();
+ if( !JSONKeys.NAMED_ASSOCIATIONS.equals( key ) )
+ {
+ builder.add( key, entry.getValue() );
+ }
+ }
+ JsonObjectBuilder assocBuilder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : namedAssociations.entrySet() )
+ {
+ String key = entry.getKey();
+ if( !name.equals( key ) )
+ {
+ assocBuilder.add( key, entry.getValue() );
+ }
+ else
+ {
+ context.markAsChanged();
+ }
+ }
+ builder.add( JSONKeys.NAMED_ASSOCIATIONS, assocBuilder.build() );
for( MigrationEvents migrationEvent : migrationEvents )
{
migrationEvent.namedAssociationRemoved( state.getString( JSONKeys.IDENTITY ), name );
}
- return true;
+ return builder.build();
}
else
{
- return false;
+ context.addFailure( "Remove named-association " + name );
+ return state;
}
}
@Override
- public boolean renameNamedAssociation( JSONObject state, String from, String to )
- throws JSONException
+ public JsonObject renameNamedAssociation( MigrationContext context, JsonObject state, String from, String to )
+ throws JsonException
{
- JSONObject namedAssociations = state.getJSONObject( JSONKeys.NAMED_ASSOCIATIONS );
- if( namedAssociations.has( from ) )
+ JsonObject namedAssociations = state.getJsonObject( JSONKeys.NAMED_ASSOCIATIONS );
+ if( namedAssociations.containsKey( from ) )
{
- Object value = namedAssociations.remove( from );
- namedAssociations.put( to, value );
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : state.entrySet() )
+ {
+ String key = entry.getKey();
+ if( !JSONKeys.NAMED_ASSOCIATIONS.equals( key ) )
+ {
+ builder.add( key, entry.getValue() );
+ }
+ }
+ JsonObjectBuilder assocBuilder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : namedAssociations.entrySet() )
+ {
+ String key = entry.getKey();
+ if( from.equals( key ) )
+ {
+ assocBuilder.add( to, entry.getValue() );
+ context.markAsChanged();
+ }
+ else
+ {
+ assocBuilder.add( key, entry.getValue() );
+ }
+ }
+ builder.add( JSONKeys.NAMED_ASSOCIATIONS, assocBuilder.build() );
for( MigrationEvents migrationEvent : migrationEvents )
{
migrationEvent.namedAssociationRenamed( state.getString( JSONKeys.IDENTITY ), from, to );
}
- return true;
+ return builder.build();
}
else
{
- return false;
+ context.addFailure( "Rename named-association " + from + " to " + to );
+ return state;
}
}
@Override
- public void changeEntityType( JSONObject state, String newEntityType )
- throws JSONException
+ public JsonObject changeEntityType( MigrationContext context, JsonObject state,
+ String fromType, String toType )
+ throws JsonException
{
- state.put( JSONKeys.TYPE, newEntityType );
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : state.entrySet() )
+ {
+ String key = entry.getKey();
+ if( JSONKeys.TYPE.equals( key ) )
+ {
+ String oldValue = entry.getValue().getValueType() == JsonValue.ValueType.STRING
+ ? ( (JsonString) entry.getValue() ).getString()
+ : entry.getValue().toString();
+ if( !fromType.equals( oldValue ) )
+ {
+ context.addFailure( "Change entity type from " + fromType + " to " + toType );
+ return state;
+ }
+ builder.add( JSONKeys.TYPE, toType );
+ context.markAsChanged();
+ }
+ else
+ {
+ builder.add( key, entry.getValue() );
+ }
+ }
for( MigrationEvents migrationEvent : migrationEvents )
{
- migrationEvent.entityTypeChanged( state.getString( JSONKeys.IDENTITY ), newEntityType );
+ migrationEvent.entityTypeChanged( state.getString( JSONKeys.IDENTITY ), toType );
}
+
+ return builder.build();
}
}
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/Migrator.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/Migrator.java b/extensions/migration/src/main/java/org/apache/polygene/migration/Migrator.java
index 7880946..a09b891 100644
--- a/extensions/migration/src/main/java/org/apache/polygene/migration/Migrator.java
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/Migrator.java
@@ -20,8 +20,8 @@
package org.apache.polygene.migration;
import java.util.Map;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.JsonObject;
+import org.apache.polygene.migration.assembly.MigrationContext;
/**
* The Migrator implements this interface, which is invoked by MigrationOperation implementations
@@ -29,42 +29,42 @@ import org.json.JSONObject;
*/
public interface Migrator
{
- boolean addProperty( JSONObject state, String name, Object defaultValue )
- throws JSONException;
+ JsonObject addProperty( MigrationContext content, JsonObject state,
+ String name, Object defaultValue );
- boolean removeProperty( JSONObject state, String name )
- throws JSONException;
+ JsonObject removeProperty( MigrationContext content, JsonObject state,
+ String name );
- boolean renameProperty( JSONObject state, String from, String to )
- throws JSONException;
+ JsonObject renameProperty( MigrationContext content, JsonObject state,
+ String from, String to );
- boolean addAssociation( JSONObject state, String name, String defaultReference )
- throws JSONException;
+ JsonObject addAssociation( MigrationContext content, JsonObject state,
+ String name, String defaultReference );
- boolean removeAssociation( JSONObject state, String name )
- throws JSONException;
+ JsonObject removeAssociation( MigrationContext content, JsonObject state,
+ String name );
- boolean renameAssociation( JSONObject state, String from, String to )
- throws JSONException;
+ JsonObject renameAssociation( MigrationContext content, JsonObject state,
+ String from, String to );
- boolean addManyAssociation( JSONObject state, String name, String... defaultReferences )
- throws JSONException;
+ JsonObject addManyAssociation( MigrationContext content, JsonObject state,
+ String name, String... defaultReferences );
- boolean removeManyAssociation( JSONObject state, String name )
- throws JSONException;
+ JsonObject removeManyAssociation( MigrationContext content, JsonObject state,
+ String name );
- boolean renameManyAssociation( JSONObject state, String from, String to )
- throws JSONException;
+ JsonObject renameManyAssociation( MigrationContext content, JsonObject state,
+ String from, String to );
- boolean addNamedAssociation( JSONObject state, String name, Map<String, String> defaultReferences )
- throws JSONException;
+ JsonObject addNamedAssociation( MigrationContext content, JsonObject state,
+ String name, Map<String, String> defaultReferences );
- boolean removeNamedAssociation( JSONObject state, String name )
- throws JSONException;
+ JsonObject removeNamedAssociation( MigrationContext content, JsonObject state,
+ String name );
- boolean renameNamedAssociation( JSONObject state, String from, String to )
- throws JSONException;
+ JsonObject renameNamedAssociation( MigrationContext content, JsonObject state,
+ String from, String to );
- void changeEntityType( JSONObject state, String newEntityType )
- throws JSONException;
+ JsonObject changeEntityType( MigrationContext content, JsonObject state,
+ String fromType, String toType );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/AbstractMigrationRule.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/AbstractMigrationRule.java b/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/AbstractMigrationRule.java
index 80f9612..df5e929 100644
--- a/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/AbstractMigrationRule.java
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/AbstractMigrationRule.java
@@ -43,4 +43,10 @@ public class AbstractMigrationRule
{
return toVersion;
}
+
+ @Override
+ public String toString()
+ {
+ return fromVersion + "=>" + toVersion + ": " + getClass();
+ }
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/EntityMigrationOperation.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/EntityMigrationOperation.java b/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/EntityMigrationOperation.java
index 0bff1aa..a5b5741 100644
--- a/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/EntityMigrationOperation.java
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/EntityMigrationOperation.java
@@ -20,8 +20,8 @@
package org.apache.polygene.migration.assembly;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.JsonException;
+import javax.json.JsonObject;
import org.apache.polygene.migration.Migrator;
import org.apache.polygene.spi.entitystore.helpers.StateStore;
@@ -30,9 +30,9 @@ import org.apache.polygene.spi.entitystore.helpers.StateStore;
*/
public interface EntityMigrationOperation
{
- boolean upgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException;
+ JsonObject upgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
+ throws JsonException;
- boolean downgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException;
+ JsonObject downgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
+ throws JsonException;
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/EntityMigrationRule.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/EntityMigrationRule.java b/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/EntityMigrationRule.java
index f238f93..291ae0d 100644
--- a/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/EntityMigrationRule.java
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/EntityMigrationRule.java
@@ -20,8 +20,7 @@
package org.apache.polygene.migration.assembly;
import java.util.Arrays;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.JsonObject;
import org.apache.polygene.migration.Migrator;
import org.apache.polygene.spi.entitystore.helpers.JSONKeys;
import org.apache.polygene.spi.entitystore.helpers.StateStore;
@@ -33,17 +32,17 @@ public class EntityMigrationRule
extends AbstractMigrationRule
{
private final String[] entityTypes;
- private final EntityMigrationOperation operationEntity;
+ private final EntityMigrationOperation entityOperation;
public EntityMigrationRule( String fromVersion,
String toVersion,
String[] entityTypes,
- EntityMigrationOperation operationEntity
+ EntityMigrationOperation entityOperation
)
{
super( fromVersion, toVersion );
this.entityTypes = entityTypes;
- this.operationEntity = operationEntity;
+ this.entityOperation = entityOperation;
}
public String[] entityTypes()
@@ -51,29 +50,29 @@ public class EntityMigrationRule
return entityTypes;
}
- public boolean upgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject upgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
if( appliesTo( state.getString( JSONKeys.TYPE ) ) )
{
- return operationEntity.upgrade( state, stateStore, migrator );
+ return entityOperation.upgrade( context, state, stateStore, migrator );
}
else
{
- return false;
+ context.addFailure( entityOperation.toString() );
+ return state;
}
}
- public boolean downgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject downgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
if( appliesTo( state.getString( JSONKeys.TYPE ) ) )
{
- return operationEntity.downgrade( state, stateStore, migrator );
+ return entityOperation.downgrade( context, state, stateStore, migrator );
}
else
{
- return false;
+ context.addFailure( entityOperation.toString() );
+ return state;
}
}
@@ -92,6 +91,6 @@ public class EntityMigrationRule
@Override
public String toString()
{
- return fromVersion + "->" + toVersion + ": on " + Arrays.asList( entityTypes ) + " do " + operationEntity;
+ return fromVersion + "=>" + toVersion + ": on " + Arrays.asList( entityTypes ) + " do " + entityOperation;
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/MigrationContext.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/MigrationContext.java b/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/MigrationContext.java
new file mode 100644
index 0000000..8ee057f
--- /dev/null
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/assembly/MigrationContext.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.migration.assembly;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public class MigrationContext
+{
+ private boolean changed;
+ private final List<String> failures = new ArrayList<>();
+
+ public boolean hasChanged()
+ {
+ return changed;
+ }
+
+ public void markAsChanged()
+ {
+ changed = true;
+ }
+
+ public boolean isSuccess()
+ {
+ return failures.isEmpty();
+ }
+
+ public boolean hasFailures()
+ {
+ return failures.size() > 0;
+ }
+
+ public List<String> failures()
+ {
+ return Collections.unmodifiableList( failures );
+ }
+
+ public void addFailure( String operation )
+ {
+ failures.add( operation );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddAssociation.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddAssociation.java b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddAssociation.java
index 9873ae3..471843b 100644
--- a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddAssociation.java
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddAssociation.java
@@ -20,8 +20,8 @@
package org.apache.polygene.migration.operation;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.JsonObject;
+import org.apache.polygene.migration.assembly.MigrationContext;
import org.apache.polygene.migration.Migrator;
import org.apache.polygene.migration.assembly.EntityMigrationOperation;
import org.apache.polygene.spi.entitystore.helpers.StateStore;
@@ -42,17 +42,15 @@ public class AddAssociation
}
@Override
- public boolean upgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject upgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.addAssociation( state, association, defaultValue );
+ return migrator.addAssociation( context, state, association, defaultValue );
}
@Override
- public boolean downgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject downgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.removeAssociation( state, association );
+ return migrator.removeAssociation( context, state, association );
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddManyAssociation.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddManyAssociation.java b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddManyAssociation.java
index 0f71acc..82610fe 100644
--- a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddManyAssociation.java
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddManyAssociation.java
@@ -21,8 +21,8 @@
package org.apache.polygene.migration.operation;
import java.util.Arrays;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.JsonObject;
+import org.apache.polygene.migration.assembly.MigrationContext;
import org.apache.polygene.migration.Migrator;
import org.apache.polygene.migration.assembly.EntityMigrationOperation;
import org.apache.polygene.spi.entitystore.helpers.StateStore;
@@ -43,17 +43,15 @@ public class AddManyAssociation
}
@Override
- public boolean upgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject upgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.addManyAssociation( state, association, defaultReferences );
+ return migrator.addManyAssociation( context, state, association, defaultReferences );
}
@Override
- public boolean downgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject downgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.removeManyAssociation( state, association );
+ return migrator.removeManyAssociation( context, state, association );
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddNamedAssociation.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddNamedAssociation.java b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddNamedAssociation.java
index cfd1c96..90725e8 100644
--- a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddNamedAssociation.java
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddNamedAssociation.java
@@ -20,8 +20,8 @@
package org.apache.polygene.migration.operation;
import java.util.Map;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.JsonObject;
+import org.apache.polygene.migration.assembly.MigrationContext;
import org.apache.polygene.migration.Migrator;
import org.apache.polygene.migration.assembly.EntityMigrationOperation;
import org.apache.polygene.spi.entitystore.helpers.StateStore;
@@ -42,17 +42,15 @@ public class AddNamedAssociation
}
@Override
- public boolean upgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject upgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.addNamedAssociation( state, association, defaultReferences );
+ return migrator.addNamedAssociation( context, state, association, defaultReferences );
}
@Override
- public boolean downgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject downgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.removeNamedAssociation( state, association );
+ return migrator.removeNamedAssociation( context, state, association );
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddProperty.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddProperty.java b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddProperty.java
index 6bef0b9..8f8898a 100644
--- a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddProperty.java
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/AddProperty.java
@@ -20,8 +20,8 @@
package org.apache.polygene.migration.operation;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.JsonObject;
+import org.apache.polygene.migration.assembly.MigrationContext;
import org.apache.polygene.migration.Migrator;
import org.apache.polygene.migration.assembly.EntityMigrationOperation;
import org.apache.polygene.spi.entitystore.helpers.StateStore;
@@ -42,17 +42,15 @@ public class AddProperty
}
@Override
- public boolean upgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject upgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.addProperty( state, property, defaultValue );
+ return migrator.addProperty( context, state, property, defaultValue );
}
@Override
- public boolean downgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject downgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.removeProperty( state, property );
+ return migrator.removeProperty( context, state, property );
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveAssociation.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveAssociation.java b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveAssociation.java
index 5d9f8bb..d1f8771 100644
--- a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveAssociation.java
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveAssociation.java
@@ -20,10 +20,10 @@
package org.apache.polygene.migration.operation;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.JsonObject;
import org.apache.polygene.migration.Migrator;
import org.apache.polygene.migration.assembly.EntityMigrationOperation;
+import org.apache.polygene.migration.assembly.MigrationContext;
import org.apache.polygene.spi.entitystore.helpers.StateStore;
/**
@@ -43,17 +43,15 @@ public class RemoveAssociation
}
@Override
- public boolean upgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject upgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.removeAssociation( state, association );
+ return migrator.removeAssociation( context, state, association );
}
@Override
- public boolean downgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject downgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.addAssociation( state, association, defaultValue );
+ return migrator.addAssociation( context, state, association, defaultValue );
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveManyAssociation.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveManyAssociation.java b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveManyAssociation.java
index dd4a0c8..d063338 100644
--- a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveManyAssociation.java
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveManyAssociation.java
@@ -21,10 +21,10 @@
package org.apache.polygene.migration.operation;
import java.util.Arrays;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.JsonObject;
import org.apache.polygene.migration.Migrator;
import org.apache.polygene.migration.assembly.EntityMigrationOperation;
+import org.apache.polygene.migration.assembly.MigrationContext;
import org.apache.polygene.spi.entitystore.helpers.StateStore;
/**
@@ -43,17 +43,15 @@ public class RemoveManyAssociation
}
@Override
- public boolean upgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject upgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.removeManyAssociation( state, association );
+ return migrator.removeManyAssociation( context, state, association );
}
@Override
- public boolean downgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject downgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.addManyAssociation( state, association, defaultReferences );
+ return migrator.addManyAssociation( context, state, association, defaultReferences );
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveNamedAssociation.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveNamedAssociation.java b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveNamedAssociation.java
index 33260bf..f97dbea 100644
--- a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveNamedAssociation.java
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveNamedAssociation.java
@@ -20,10 +20,10 @@
package org.apache.polygene.migration.operation;
import java.util.Map;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.JsonObject;
import org.apache.polygene.migration.Migrator;
import org.apache.polygene.migration.assembly.EntityMigrationOperation;
+import org.apache.polygene.migration.assembly.MigrationContext;
import org.apache.polygene.spi.entitystore.helpers.StateStore;
/**
@@ -42,17 +42,15 @@ public class RemoveNamedAssociation
}
@Override
- public boolean upgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject upgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.removeNamedAssociation( state, association );
+ return migrator.removeNamedAssociation( context, state, association );
}
@Override
- public boolean downgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject downgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.addNamedAssociation( state, association, defaultReferences );
+ return migrator.addNamedAssociation( context, state, association, defaultReferences );
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveProperty.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveProperty.java b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveProperty.java
index 1563928..9ad8673 100644
--- a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveProperty.java
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RemoveProperty.java
@@ -20,8 +20,8 @@
package org.apache.polygene.migration.operation;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.JsonObject;
+import org.apache.polygene.migration.assembly.MigrationContext;
import org.apache.polygene.migration.Migrator;
import org.apache.polygene.migration.assembly.EntityMigrationOperation;
import org.apache.polygene.spi.entitystore.helpers.StateStore;
@@ -43,17 +43,15 @@ public class RemoveProperty
}
@Override
- public boolean upgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject upgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.removeProperty( state, property );
+ return migrator.removeProperty( context, state, property );
}
@Override
- public boolean downgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject downgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.addProperty( state, property, defaultValue );
+ return migrator.addProperty( context, state, property, defaultValue );
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameAssociation.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameAssociation.java b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameAssociation.java
index 52ba536..277de57 100644
--- a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameAssociation.java
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameAssociation.java
@@ -20,10 +20,10 @@
package org.apache.polygene.migration.operation;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.JsonObject;
import org.apache.polygene.migration.Migrator;
import org.apache.polygene.migration.assembly.EntityMigrationOperation;
+import org.apache.polygene.migration.assembly.MigrationContext;
import org.apache.polygene.spi.entitystore.helpers.StateStore;
/**
@@ -42,17 +42,15 @@ public class RenameAssociation
}
@Override
- public boolean upgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject upgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.renameAssociation( state, from, to );
+ return migrator.renameAssociation( context, state, from, to );
}
@Override
- public boolean downgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject downgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.renameAssociation( state, to, from );
+ return migrator.renameAssociation( context, state, to, from );
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameEntity.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameEntity.java b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameEntity.java
index 37cdd59..716a6b1 100644
--- a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameEntity.java
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameEntity.java
@@ -19,11 +19,10 @@
*/
package org.apache.polygene.migration.operation;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.JsonObject;
import org.apache.polygene.migration.Migrator;
import org.apache.polygene.migration.assembly.EntityMigrationOperation;
-import org.apache.polygene.spi.entitystore.helpers.JSONKeys;
+import org.apache.polygene.migration.assembly.MigrationContext;
import org.apache.polygene.spi.entitystore.helpers.StateStore;
/**
@@ -42,37 +41,15 @@ public class RenameEntity
}
@Override
- public boolean upgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject upgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- String type = state.getString( JSONKeys.TYPE );
-
- if( type.equals( fromName ) )
- {
- migrator.changeEntityType( state, toName );
- return true;
- }
- else
- {
- return false;
- }
+ return migrator.changeEntityType( context, state, fromName, toName );
}
@Override
- public boolean downgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject downgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- String type = state.getString( JSONKeys.TYPE );
-
- if( type.equals( toName ) )
- {
- migrator.changeEntityType( state, fromName );
- return true;
- }
- else
- {
- return false;
- }
+ return migrator.changeEntityType( context, state, fromName, fromName );
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameManyAssociation.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameManyAssociation.java b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameManyAssociation.java
index dc207b6..cfc12c5 100644
--- a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameManyAssociation.java
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameManyAssociation.java
@@ -20,10 +20,10 @@
package org.apache.polygene.migration.operation;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.JsonObject;
import org.apache.polygene.migration.Migrator;
import org.apache.polygene.migration.assembly.EntityMigrationOperation;
+import org.apache.polygene.migration.assembly.MigrationContext;
import org.apache.polygene.spi.entitystore.helpers.StateStore;
/**
@@ -42,17 +42,15 @@ public class RenameManyAssociation
}
@Override
- public boolean upgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject upgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.renameManyAssociation( state, from, to );
+ return migrator.renameManyAssociation( context, state, from, to );
}
@Override
- public boolean downgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject downgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.renameManyAssociation( state, to, from );
+ return migrator.renameManyAssociation( context, state, to, from );
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameNamedAssociation.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameNamedAssociation.java b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameNamedAssociation.java
index 0045d15..05fb92a 100644
--- a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameNamedAssociation.java
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameNamedAssociation.java
@@ -19,10 +19,10 @@
*/
package org.apache.polygene.migration.operation;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.JsonObject;
import org.apache.polygene.migration.Migrator;
import org.apache.polygene.migration.assembly.EntityMigrationOperation;
+import org.apache.polygene.migration.assembly.MigrationContext;
import org.apache.polygene.spi.entitystore.helpers.StateStore;
/**
@@ -41,17 +41,15 @@ public class RenameNamedAssociation
}
@Override
- public boolean upgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject upgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.renameNamedAssociation( state, from, to );
+ return migrator.renameNamedAssociation( context, state, from, to );
}
@Override
- public boolean downgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject downgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.renameNamedAssociation( state, to, from );
+ return migrator.renameNamedAssociation( context, state, to, from );
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameProperty.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameProperty.java b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameProperty.java
index b373b76..4f0b80c 100644
--- a/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameProperty.java
+++ b/extensions/migration/src/main/java/org/apache/polygene/migration/operation/RenameProperty.java
@@ -20,8 +20,8 @@
package org.apache.polygene.migration.operation;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.JsonObject;
+import org.apache.polygene.migration.assembly.MigrationContext;
import org.apache.polygene.migration.Migrator;
import org.apache.polygene.migration.assembly.EntityMigrationOperation;
import org.apache.polygene.spi.entitystore.helpers.StateStore;
@@ -42,17 +42,15 @@ public class RenameProperty
}
@Override
- public boolean upgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject upgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.renameProperty( state, fromProperty, toProperty );
+ return migrator.renameProperty( context, state, fromProperty, toProperty );
}
@Override
- public boolean downgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject downgrade( MigrationContext context, JsonObject state, StateStore stateStore, Migrator migrator )
{
- return migrator.renameProperty( state, toProperty, fromProperty );
+ return migrator.renameProperty( context, state, toProperty, fromProperty );
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/migration/src/test/java/org/apache/polygene/migration/MigrationTest.java
----------------------------------------------------------------------
diff --git a/extensions/migration/src/test/java/org/apache/polygene/migration/MigrationTest.java b/extensions/migration/src/test/java/org/apache/polygene/migration/MigrationTest.java
index 811d79f..1068abb 100644
--- a/extensions/migration/src/test/java/org/apache/polygene/migration/MigrationTest.java
+++ b/extensions/migration/src/test/java/org/apache/polygene/migration/MigrationTest.java
@@ -22,6 +22,7 @@ package org.apache.polygene.migration;
import java.io.IOException;
import java.util.List;
import java.util.stream.Stream;
+import javax.json.JsonObject;
import org.apache.polygene.api.activation.ActivationException;
import org.apache.polygene.api.identity.Identity;
import org.apache.polygene.api.service.importer.NewObjectImporter;
@@ -33,18 +34,17 @@ import org.apache.polygene.bootstrap.SingletonAssembler;
import org.apache.polygene.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
import org.apache.polygene.migration.assembly.EntityMigrationOperation;
import org.apache.polygene.migration.assembly.MigrationBuilder;
+import org.apache.polygene.migration.assembly.MigrationContext;
import org.apache.polygene.migration.assembly.MigrationOperation;
import org.apache.polygene.spi.entitystore.BackupRestore;
import org.apache.polygene.spi.entitystore.helpers.JSONKeys;
import org.apache.polygene.spi.entitystore.helpers.StateStore;
import org.apache.polygene.test.AbstractPolygeneTest;
import org.apache.polygene.test.EntityTestAssembler;
-import org.hamcrest.CoreMatchers;
-import org.json.JSONException;
-import org.json.JSONObject;
import org.junit.Test;
import static java.util.stream.Collectors.toList;
+import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
/**
@@ -124,9 +124,7 @@ public class MigrationTest
id = entity.identity().get();
uow.complete();
- BackupRestore backupRestore = v1.module()
- .findService( BackupRestore.class )
- .get();
+ BackupRestore backupRestore = v1.module().findService( BackupRestore.class ).get();
try( Stream<String> backup = backupRestore.backup() )
{
data_v1 = backup.collect( toList() );
@@ -152,9 +150,9 @@ public class MigrationTest
UnitOfWork uow = v1_1.module().unitOfWorkFactory().newUnitOfWork();
TestEntity1_1 entity = uow.get( TestEntity1_1.class, id );
- assertThat( "Property has been renamed", entity.newFoo().get(), CoreMatchers.equalTo( "Some value" ) );
- assertThat( "ManyAssociation has been renamed", entity.newFooManyAssoc().count(), CoreMatchers.equalTo( 1 ) );
- assertThat( "Association has been renamed", entity.newFooAssoc().get(), CoreMatchers.equalTo( entity ) );
+ assertThat( "Property has been renamed", entity.newFoo().get(), equalTo( "Some value" ) );
+ assertThat( "ManyAssociation has been renamed", entity.newFooManyAssoc().count(), equalTo( 1 ) );
+ assertThat( "Association has been renamed", entity.newFooAssoc().get(), equalTo( entity ) );
uow.complete();
try( Stream<String> backup = testData.backup() )
@@ -183,10 +181,10 @@ public class MigrationTest
testData.restore( data_v1.stream() );
UnitOfWork uow = v2_0.module().unitOfWorkFactory().newUnitOfWork();
TestEntity2_0 entity = uow.get( TestEntity2_0.class, id );
- assertThat( "Property has been created", entity.bar().get(), CoreMatchers.equalTo( "Some value" ) );
- assertThat( "Custom Property has been created", entity.customBar().get(), CoreMatchers.equalTo( "Hello Some value" ) );
- assertThat( "ManyAssociation has been renamed", entity.newFooManyAssoc().count(), CoreMatchers.equalTo( 1 ) );
- assertThat( "Association has been renamed", entity.newFooAssoc().get(), CoreMatchers.equalTo( entity ) );
+ assertThat( "Property has been created", entity.bar().get(), equalTo( "Some value" ) );
+ assertThat( "Custom Property has been created", entity.customBar().get(), equalTo( "Hello Some value" ) );
+ assertThat( "ManyAssociation has been renamed", entity.newFooManyAssoc().count(), equalTo( 1 ) );
+ assertThat( "Association has been renamed", entity.newFooAssoc().get(), equalTo( entity ) );
uow.complete();
}
}
@@ -221,19 +219,16 @@ public class MigrationTest
implements EntityMigrationOperation
{
@Override
- public boolean upgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject upgrade( MigrationContext context, JsonObject state, StateStore store, Migrator migrator )
{
- JSONObject properties = (JSONObject) state.get( JSONKeys.PROPERTIES );
-
- return migrator.addProperty( state, "customBar", "Hello " + properties.getString( "bar" ) );
+ JsonObject properties = state.getJsonObject( JSONKeys.PROPERTIES );
+ return migrator.addProperty( context, state, "customBar", "Hello " + properties.getString( "bar" ) );
}
@Override
- public boolean downgrade( JSONObject state, StateStore stateStore, Migrator migrator )
- throws JSONException
+ public JsonObject downgrade( MigrationContext context, JsonObject state, StateStore store, Migrator migrator )
{
- return migrator.removeProperty( state, "customBar" );
+ return migrator.removeProperty( context, state, "customBar" );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/reindexer/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/reindexer/build.gradle b/extensions/reindexer/build.gradle
index 1315db1..f956f60 100644
--- a/extensions/reindexer/build.gradle
+++ b/extensions/reindexer/build.gradle
@@ -31,7 +31,6 @@ dependencies {
testImplementation polygene.core.testsupport
testImplementation polygene.extension( 'entitystore-jdbm' )
- testImplementation polygene.extension( 'valueserialization-jackson' )
testImplementation polygene.extension( 'indexing-rdf' )
testRuntimeOnly libraries.logback
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/reindexer/src/test/java/org/apache/polygene/index/reindexer/ReindexerTest.java
----------------------------------------------------------------------
diff --git a/extensions/reindexer/src/test/java/org/apache/polygene/index/reindexer/ReindexerTest.java b/extensions/reindexer/src/test/java/org/apache/polygene/index/reindexer/ReindexerTest.java
index f3cd992..38c91a8 100644
--- a/extensions/reindexer/src/test/java/org/apache/polygene/index/reindexer/ReindexerTest.java
+++ b/extensions/reindexer/src/test/java/org/apache/polygene/index/reindexer/ReindexerTest.java
@@ -40,7 +40,6 @@ import org.apache.polygene.index.rdf.assembly.RdfNativeSesameStoreAssembler;
import org.apache.polygene.library.rdf.repository.NativeConfiguration;
import org.apache.polygene.test.AbstractPolygeneTest;
import org.apache.polygene.test.EntityTestAssembler;
-import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
@@ -67,7 +66,6 @@ public class ReindexerTest
// Native Sesame EntityFinder
new RdfNativeSesameStoreAssembler().assemble( module );
- new JacksonValueSerializationAssembler().assemble( module );
// Reindexer
// START SNIPPET: assembly
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxjson/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxjson/build.gradle b/extensions/serialization-javaxjson/build.gradle
new file mode 100644
index 0000000..e93e5fc
--- /dev/null
+++ b/extensions/serialization-javaxjson/build.gradle
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+apply plugin: 'polygene-extension'
+
+description = "Apache Polygene\u2122 javax.json Serialization Extension"
+
+jar { manifest { name = "Apache Polygene\u2122 Extension - Serialization - javax.json" } }
+
+dependencies {
+ api polygene.core.bootstrap
+
+ runtimeOnly polygene.core.runtime
+ runtimeOnly libraries.johnzon
+
+ testImplementation polygene.core.testsupport
+
+ testRuntimeOnly libraries.logback
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxjson/dev-status.xml
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxjson/dev-status.xml b/extensions/serialization-javaxjson/dev-status.xml
new file mode 100644
index 0000000..0d777be
--- /dev/null
+++ b/extensions/serialization-javaxjson/dev-status.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ ~
+ ~
+ -->
+<module xmlns="http://polygene.apache.org/schemas/2008/dev-status/1"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://polygene.apache.org/schemas/2008/dev-status/1
+ http://polygene.apache.org/schemas/2008/dev-status/1/dev-status.xsd">
+ <status>
+ <!--none,early,beta,stable,mature-->
+ <codebase>beta</codebase>
+
+ <!-- none, brief, good, complete -->
+ <documentation>none</documentation>
+
+ <!-- none, some, good, complete -->
+ <unittests>good</unittests>
+ </status>
+ <licenses>
+ <license>ALv2</license>
+ </licenses>
+</module>
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxjson/src/docs/serialization-javaxjson.txt
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxjson/src/docs/serialization-javaxjson.txt b/extensions/serialization-javaxjson/src/docs/serialization-javaxjson.txt
new file mode 100644
index 0000000..f9aee3f
--- /dev/null
+++ b/extensions/serialization-javaxjson/src/docs/serialization-javaxjson.txt
@@ -0,0 +1,31 @@
+///////////////////////////////////////////////////////////////
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+///////////////////////////////////////////////////////////////
+
+[[extension-serialization-javaxjson,javax.json serialization]]
+= javax.json serialization =
+
+[devstatus]
+--------------
+source=extensions/serialization-javaxjson/dev-status.xml
+--------------
+
+// TODO Preamble - link to <<core-api-serialization>> and <<core-spi-serialization>>
+// TODO Document usage of JsonSerialization
+// TODO Include sample model and its output from test code & resources
+// TODO Assembly - Serialization extension or sole Service, settings & adapters
[48/50] [abbrv] polygene-java git commit: POLYGENE-231 arrays default
values
Posted by pa...@apache.org.
POLYGENE-231 arrays default values
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/a94e4657
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/a94e4657
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/a94e4657
Branch: refs/heads/serialization-3.0
Commit: a94e465767faca965fefb31166e4e160cb5aa178
Parents: 2b5bad8
Author: Paul Merlin <pa...@apache.org>
Authored: Mon Mar 6 17:56:07 2017 +0100
Committer: Paul Merlin <pa...@apache.org>
Committed: Mon Mar 13 11:24:42 2017 +0100
----------------------------------------------------------------------
.../polygene/api/property/DefaultValues.java | 5 +++
.../runtime/defaults/UseDefaultsTest.java | 34 +++++++++++++++++++-
2 files changed, 38 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a94e4657/core/api/src/main/java/org/apache/polygene/api/property/DefaultValues.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/property/DefaultValues.java b/core/api/src/main/java/org/apache/polygene/api/property/DefaultValues.java
index 00a128e..4207358 100644
--- a/core/api/src/main/java/org/apache/polygene/api/property/DefaultValues.java
+++ b/core/api/src/main/java/org/apache/polygene/api/property/DefaultValues.java
@@ -20,6 +20,7 @@
package org.apache.polygene.api.property;
+import java.lang.reflect.Array;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
@@ -82,6 +83,10 @@ public final class DefaultValues
{
return ( (Class) type ).getEnumConstants()[ 0 ];
}
+ else if( typeAsClass.isArray() )
+ {
+ return Array.newInstance( typeAsClass.getComponentType(), 0 );
+ }
}
throw new IllegalArgumentException( "Cannot use @UseDefaults with type " + type.toString() );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a94e4657/core/runtime/src/test/java/org/apache/polygene/runtime/defaults/UseDefaultsTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/polygene/runtime/defaults/UseDefaultsTest.java b/core/runtime/src/test/java/org/apache/polygene/runtime/defaults/UseDefaultsTest.java
index ab1feb9..a2dc6b3 100644
--- a/core/runtime/src/test/java/org/apache/polygene/runtime/defaults/UseDefaultsTest.java
+++ b/core/runtime/src/test/java/org/apache/polygene/runtime/defaults/UseDefaultsTest.java
@@ -20,6 +20,7 @@
package org.apache.polygene.runtime.defaults;
+import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -36,6 +37,7 @@ import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
/**
* JAVADOC
@@ -59,7 +61,14 @@ public class UseDefaultsTest extends AbstractPolygeneTest
assertThat( "zeroInt is zero", testComposite.defaultInt().get(), equalTo( 0 ) );
assertThat( "nullString is null", testComposite.nullString().get(), nullValue() );
assertThat( "defaultString is empty string", testComposite.defaultString().get(), equalTo( "" ) );
- assertThat( "assemblyString is empty string", testComposite.assemblyString().get(), equalTo( "habba" ) );
+ assertThat( "assemblyString is set string", testComposite.assemblyString().get(), equalTo( "habba" ) );
+
+ assertThat( "nullPrimitiveArray is null", testComposite.nullPrimitiveArray().get(), nullValue() );
+ assertTrue( "emptyPrimitiveArray is empty",
+ Arrays.equals( testComposite.emptyPrimitiveArray().get(), new int[ 0 ] ) );
+ assertThat( "nullArray is null", testComposite.nullArray().get(), nullValue() );
+ assertTrue( "emptyArray is empty array",
+ Arrays.equals( testComposite.emptyArray().get(), new Integer[ 0 ] ) );
}
@Test
@@ -75,6 +84,11 @@ public class UseDefaultsTest extends AbstractPolygeneTest
assertThat( testComposite.initializedStringListDefultString().get(), equalTo( expectedList ) );
Map<String, Integer> expectedMap = Collections.singletonMap( "abcd", 345 );
assertThat( testComposite.initializedMapDefaultValue().get(), equalTo( expectedMap ) );
+
+ assertTrue( "initializedPrimitiveArray is set",
+ Arrays.equals( testComposite.initializedPrimitiveArray().get(), new int[] { 23, 42 } ) );
+ assertTrue( "initializedArray is set",
+ Arrays.equals( testComposite.initializedArray().get(), new Integer[] { 23, 42 } ) );
}
interface TestComposite
@@ -110,5 +124,23 @@ public class UseDefaultsTest extends AbstractPolygeneTest
@UseDefaults( "{\"abcd\": 345}" )
Property<Map<String, Integer>> initializedMapDefaultValue();
+
+ @Optional
+ Property<int[]> nullPrimitiveArray();
+
+ @UseDefaults
+ Property<int[]> emptyPrimitiveArray();
+
+ @UseDefaults( "[23, 42]" )
+ Property<int[]> initializedPrimitiveArray();
+
+ @Optional
+ Property<Integer[]> nullArray();
+
+ @UseDefaults
+ Property<Integer[]> emptyArray();
+
+ @UseDefaults( "[23, 42]" )
+ Property<Integer[]> initializedArray();
}
}
[46/50] [abbrv] polygene-java git commit: POLYGENE-231 value state
can now contain arrays
Posted by pa...@apache.org.
POLYGENE-231 value state can now contain arrays
byte[] are serialized as such, Base64 encoded in text-based formats.
Other arrays, including primitive ones, are (de)serialized like
collections.
Supported by json, xml & msgpack serialization extensions
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/2b5bad87
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/2b5bad87
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/2b5bad87
Branch: refs/heads/serialization-3.0
Commit: 2b5bad87bb37aeea0b5b32c79dab56bc988bf861
Parents: 928a285
Author: Paul Merlin <pa...@apache.org>
Authored: Mon Mar 6 16:33:10 2017 +0100
Committer: Paul Merlin <pa...@apache.org>
Committed: Mon Mar 13 11:24:42 2017 +0100
----------------------------------------------------------------------
.../org/apache/polygene/api/type/ArrayType.java | 97 ++++++++++++++++++++
.../apache/polygene/api/util/ArrayIterable.java | 75 +++++++++++++++
.../runtime/property/PropertyInstance.java | 45 +++++++++
.../runtime/type/ValueTypeFactoryInstance.java | 5 +
.../javaxjson/JavaxJsonDeserializer.java | 29 ++++++
.../javaxjson/JavaxJsonSerializer.java | 30 +++++-
...AbstractValueCompositeSerializationTest.java | 38 +++-----
.../javaxxml/JavaxXmlDeserializer.java | 23 +++++
.../javaxxml/JavaxXmlSerializer.java | 21 +++++
.../msgpack/MessagePackDeserializer.java | 22 +++++
.../msgpack/MessagePackSerializer.java | 20 ++++
11 files changed, 379 insertions(+), 26 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/2b5bad87/core/api/src/main/java/org/apache/polygene/api/type/ArrayType.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/type/ArrayType.java b/core/api/src/main/java/org/apache/polygene/api/type/ArrayType.java
new file mode 100644
index 0000000..29834ce
--- /dev/null
+++ b/core/api/src/main/java/org/apache/polygene/api/type/ArrayType.java
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.api.type;
+
+import java.lang.reflect.Type;
+import java.util.Objects;
+import org.apache.polygene.api.util.Classes;
+
+/**
+ * Array ValueType.
+ * <p>This handles arrays of primitives and values</p>
+ */
+public class ArrayType extends ValueType
+{
+ public static boolean isArray( Type type )
+ {
+ return Classes.RAW_CLASS.apply( type ).isArray();
+ }
+
+ public static ArrayType of( Class<?> arrayType )
+ {
+ return new ArrayType( arrayType, ValueType.of( arrayType.getComponentType() ) );
+ }
+
+ private ValueType collectedType;
+
+ public ArrayType( Class<?> type, ValueType collectedType )
+ {
+ super( type );
+ this.collectedType = collectedType;
+ if( !isArray( type ) )
+ {
+ throw new IllegalArgumentException( type + " is not an array" );
+ }
+ }
+
+ public ValueType collectedType()
+ {
+ return collectedType;
+ }
+
+ public boolean isArrayOfPrimitives()
+ {
+ return hasType( boolean[].class )
+ || hasType( char[].class )
+ || hasType( short[].class )
+ || hasType( int[].class )
+ || hasType( byte[].class )
+ || hasType( long[].class )
+ || hasType( float[].class )
+ || hasType( double[].class );
+ }
+
+ public boolean isArrayOfPrimitiveBytes()
+ {
+ return hasType( byte[].class );
+ }
+
+ @Override
+ public boolean equals( final Object o )
+ {
+ if( this == o ) { return true; }
+ if( o == null || getClass() != o.getClass() ) { return false; }
+ if( !super.equals( o ) ) { return false; }
+ ArrayType that = (ArrayType) o;
+ return Objects.equals( collectedType, that.collectedType );
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hash( super.hashCode(), collectedType );
+ }
+
+ @Override
+ public String toString()
+ {
+ return collectedType + "[]";
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/2b5bad87/core/api/src/main/java/org/apache/polygene/api/util/ArrayIterable.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/util/ArrayIterable.java b/core/api/src/main/java/org/apache/polygene/api/util/ArrayIterable.java
new file mode 100644
index 0000000..707eaca
--- /dev/null
+++ b/core/api/src/main/java/org/apache/polygene/api/util/ArrayIterable.java
@@ -0,0 +1,75 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.api.util;
+
+import java.lang.reflect.Array;
+import java.util.Iterator;
+
+/**
+ * Iterate over arrays, both primitive arrays and Object[].
+ */
+public class ArrayIterable implements Iterable<Object>
+{
+ private final Object array;
+
+ public ArrayIterable( final Object array )
+ {
+ if( !array.getClass().isArray() )
+ {
+ throw new IllegalArgumentException( array + " is not an array" );
+ }
+ this.array = array;
+ }
+
+ @Override
+ public Iterator<Object> iterator()
+ {
+ return new ArrayIterator( array );
+ }
+
+ private class ArrayIterator implements Iterator<Object>
+ {
+ private final Object array;
+ private int currentIndex = 0;
+
+ private ArrayIterator( Object array )
+ {
+ this.array = array;
+ }
+
+ @Override
+ public boolean hasNext()
+ {
+ return currentIndex < Array.getLength( array );
+ }
+
+ @Override
+ public Object next()
+ {
+ return Array.get( array, currentIndex++ );
+ }
+
+ @Override
+ public void remove()
+ {
+ throw new UnsupportedOperationException( "cannot remove items from an array" );
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/2b5bad87/core/runtime/src/main/java/org/apache/polygene/runtime/property/PropertyInstance.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/polygene/runtime/property/PropertyInstance.java b/core/runtime/src/main/java/org/apache/polygene/runtime/property/PropertyInstance.java
index 72d39cb..41d5e3c 100644
--- a/core/runtime/src/main/java/org/apache/polygene/runtime/property/PropertyInstance.java
+++ b/core/runtime/src/main/java/org/apache/polygene/runtime/property/PropertyInstance.java
@@ -20,6 +20,7 @@
package org.apache.polygene.runtime.property;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
@@ -139,6 +140,50 @@ public class PropertyInstance<T>
{
return that.get() == null;
}
+ Class<?> valueClass = value.getClass();
+ // Handling arrays
+ if( valueClass.isArray() )
+ {
+ Object thatValue = that.get();
+ if( !thatValue.getClass().isArray() )
+ {
+ return false;
+ }
+ Class<?> componentType = valueClass.getComponentType();
+ if( boolean.class.equals( componentType ) )
+ {
+ return Arrays.equals( (boolean[]) value, (boolean[]) thatValue );
+ }
+ if( char.class.equals( componentType ) )
+ {
+ return Arrays.equals( (char[]) value, (char[]) thatValue );
+ }
+ if( short.class.equals( componentType ) )
+ {
+ return Arrays.equals( (short[]) value, (short[]) thatValue );
+ }
+ if( int.class.equals( componentType ) )
+ {
+ return Arrays.equals( (int[]) value, (int[]) thatValue );
+ }
+ if( byte.class.equals( componentType ) )
+ {
+ return Arrays.equals( (byte[]) value, (byte[]) thatValue );
+ }
+ if( long.class.equals( componentType ) )
+ {
+ return Arrays.equals( (long[]) value, (long[]) thatValue );
+ }
+ if( float.class.equals( componentType ) )
+ {
+ return Arrays.equals( (float[]) value, (float[]) thatValue );
+ }
+ if( double.class.equals( componentType ) )
+ {
+ return Arrays.equals( (double[]) value, (double[]) thatValue );
+ }
+ return Arrays.deepEquals( (Object[]) value, (Object[]) thatValue );
+ }
return value.equals( that.get() );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/2b5bad87/core/runtime/src/main/java/org/apache/polygene/runtime/type/ValueTypeFactoryInstance.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/polygene/runtime/type/ValueTypeFactoryInstance.java b/core/runtime/src/main/java/org/apache/polygene/runtime/type/ValueTypeFactoryInstance.java
index 37a1b91..21134e8 100644
--- a/core/runtime/src/main/java/org/apache/polygene/runtime/type/ValueTypeFactoryInstance.java
+++ b/core/runtime/src/main/java/org/apache/polygene/runtime/type/ValueTypeFactoryInstance.java
@@ -25,6 +25,7 @@ import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import org.apache.polygene.api.common.InvalidApplicationException;
import org.apache.polygene.api.structure.ModuleDescriptor;
+import org.apache.polygene.api.type.ArrayType;
import org.apache.polygene.api.type.CollectionType;
import org.apache.polygene.api.type.EnumType;
import org.apache.polygene.api.type.MapType;
@@ -77,6 +78,10 @@ public class ValueTypeFactoryInstance implements ValueTypeFactory
{
valueType = EnumType.of( Classes.RAW_CLASS.apply( type ) );
}
+ else if( ArrayType.isArray( type ) )
+ {
+ valueType = ArrayType.of( Classes.RAW_CLASS.apply( type ) );
+ }
else if( CollectionType.isCollection( type ) )
{
if( type instanceof ParameterizedType )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/2b5bad87/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java
index 721c884..b9d9e94 100644
--- a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java
@@ -20,6 +20,7 @@ package org.apache.polygene.serialization.javaxjson;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
+import java.lang.reflect.Array;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Base64;
@@ -43,6 +44,7 @@ import org.apache.polygene.api.property.PropertyDescriptor;
import org.apache.polygene.api.serialization.SerializationException;
import org.apache.polygene.api.service.ServiceDescriptor;
import org.apache.polygene.api.structure.ModuleDescriptor;
+import org.apache.polygene.api.type.ArrayType;
import org.apache.polygene.api.type.CollectionType;
import org.apache.polygene.api.type.EnumType;
import org.apache.polygene.api.type.MapType;
@@ -95,6 +97,10 @@ public class JavaxJsonDeserializer extends AbstractTextDeserializer implements J
{
return (T) Enum.valueOf( (Class) valueType.primaryType(), asString( json ) );
}
+ if( ArrayType.class.isAssignableFrom( valueTypeClass ) )
+ {
+ return (T) deserializeArray( module, (ArrayType) valueType, json );
+ }
if( CollectionType.class.isAssignableFrom( valueTypeClass ) )
{
return (T) deserializeCollection( module, (CollectionType) valueType, requireJsonArray( json ) );
@@ -110,6 +116,29 @@ public class JavaxJsonDeserializer extends AbstractTextDeserializer implements J
return doGuessDeserialize( module, valueType, json );
}
+ private Object deserializeArray( ModuleDescriptor module, ArrayType arrayType, JsonValue json )
+ {
+ if( arrayType.isArrayOfPrimitiveBytes() && json.getValueType() == JsonValue.ValueType.STRING )
+ {
+ byte[] bytes = asString( json ).getBytes( UTF_8 );
+ return Base64.getDecoder().decode( bytes );
+ }
+ if( json.getValueType() == JsonValue.ValueType.ARRAY )
+ {
+ CollectionType collectionType = CollectionType.listOf( arrayType.collectedType() );
+ List<Object> collection = (List<Object>) deserializeCollection( module,
+ collectionType,
+ requireJsonArray( json ) );
+ Object array = Array.newInstance( arrayType.collectedType().primaryType(), collection.size() );
+ for( int idx = 0; idx < collection.size(); idx++ )
+ {
+ Array.set( array, idx, collection.get( idx ) );
+ }
+ return array;
+ }
+ throw new SerializationException( "Don't know how to deserialize " + arrayType + " from " + json );
+ }
+
@SuppressWarnings( "unchecked" )
private <T> T doGuessDeserialize( ModuleDescriptor module, ValueType valueType, JsonValue json )
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/2b5bad87/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java
index 5450ec9..c93c822 100644
--- a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java
@@ -40,10 +40,12 @@ import org.apache.polygene.api.composite.CompositeInstance;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.injection.scope.Uses;
import org.apache.polygene.api.service.ServiceDescriptor;
+import org.apache.polygene.api.type.ArrayType;
import org.apache.polygene.api.type.EnumType;
import org.apache.polygene.api.type.MapType;
import org.apache.polygene.api.type.ValueCompositeType;
import org.apache.polygene.api.type.ValueType;
+import org.apache.polygene.api.util.ArrayIterable;
import org.apache.polygene.api.value.ValueComposite;
import org.apache.polygene.api.value.ValueDescriptor;
import org.apache.polygene.spi.serialization.AbstractTextSerializer;
@@ -91,6 +93,10 @@ public class JavaxJsonSerializer extends AbstractTextSerializer implements JsonS
{
return serializeMap( options, (Map<?, ?>) object );
}
+ if( ArrayType.isArray( objectClass ) )
+ {
+ return serializeArray( options, object );
+ }
if( Iterable.class.isAssignableFrom( objectClass ) )
{
return serializeIterable( options, (Iterable<?>) object );
@@ -181,6 +187,21 @@ public class JavaxJsonSerializer extends AbstractTextSerializer implements JsonS
}
}
+ private JsonValue serializeArray( Options options, Object object )
+ {
+ ArrayType valueType = ArrayType.of( object.getClass() );
+ if( valueType.isArrayOfPrimitiveBytes() )
+ {
+ byte[] base64 = Base64.getEncoder().encode( (byte[]) object );
+ return JavaxJson.toJsonString( new String( base64, UTF_8 ) );
+ }
+ if( valueType.isArrayOfPrimitives() )
+ {
+ return serializeIterable( options, new ArrayIterable( object ) );
+ }
+ return serializeStream( options, Stream.of( (Object[]) object ) );
+ }
+
private JsonArray serializeIterable( Options options, Iterable<?> iterable )
{
return serializeStream( options, StreamSupport.stream( iterable.spliterator(), false ) );
@@ -195,12 +216,17 @@ public class JavaxJsonSerializer extends AbstractTextSerializer implements JsonS
private JsonString serializeBase64( Object object )
{
+ byte[] bytes = Base64.getEncoder().encode( javaSerialization( object ) );
+ return JavaxJson.toJsonString( new String( bytes, UTF_8 ) );
+ }
+
+ private byte[] javaSerialization( Object object )
+ {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
try( ObjectOutputStream out = new ObjectOutputStream( bout ) )
{
out.writeUnshared( object );
- byte[] bytes = Base64.getEncoder().encode( bout.toByteArray() );
- return JavaxJson.toJsonString( new String( bytes, UTF_8 ) );
+ return bout.toByteArray();
}
catch( IOException ex )
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/2b5bad87/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
index dced530..a0975ee 100644
--- a/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
+++ b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
@@ -61,6 +61,7 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
+import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.polygene.api.usecase.UsecaseBuilder.newUsecase;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
@@ -69,7 +70,6 @@ import static org.junit.Assert.assertThat;
/**
* Assert that ValueSerialization behaviour on ValueComposites is correct.
*/
-// TODO Assert Arrays behaviour!
// TODO Assert Generics behaviour!
public abstract class AbstractValueCompositeSerializationTest
extends AbstractPolygeneTest
@@ -320,24 +320,15 @@ public abstract class AbstractValueCompositeSerializationTest
some.stringValueMap().get().put( "foo", anotherValue1 );
some.another().set( anotherValue1 );
- // some.arrayOfValues().set( new AnotherValue[] { anotherValue1, anotherValue2, anotherValue3 } );
+ some.arrayOfValues().set( new AnotherValue[] { anotherValue1, anotherValue2, anotherValue3 } );
+ some.primitiveByteArray().set( "foo".getBytes( UTF_8 ) );
+ some.byteArray().set( new Byte[] { 23, null, 42 } );
some.serializable().set( new SerializableObject() );
some.foo().set( module.newValue( FooValue.class ) );
some.fooValue().set( module.newValue( FooValue.class ) );
some.customFoo().set( module.newValue( CustomFooValue.class ) );
some.customFooValue().set( module.newValue( CustomFooValue.class ) );
- // Arrays
- // TODO FIXME Disabled as ValueComposite equality fails here
- //proto.primitiveByteArray().set( new byte[]
- // {
- // 9, -12, 42, -12, 127, 23, -128, 73
- // } );
- //proto.byteArray().set( new Byte[]
- // {
- // 9, null, -12, 23, -12, 127, -128, 73
- // } );
-
// NestedEntities
some.barAssociation().set( buildBarEntity( uow, "bazar in barAssociation" ) );
some.barEntityAssociation().set( buildBarEntity( uow, "bazar in barEntityAssociation" ) );
@@ -410,7 +401,7 @@ public abstract class AbstractValueCompositeSerializationTest
Property<AnotherValue> another();
- // Property<AnotherValue[]> arrayOfValues();
+ Property<AnotherValue[]> arrayOfValues();
@Optional
Property<AnotherValue> anotherNull();
@@ -427,16 +418,15 @@ public abstract class AbstractValueCompositeSerializationTest
@UseDefaults
Property<TestEnum> testEnum();
- // TODO FIXME Disabled as ValueComposite equality fails here
- //Property<byte[]> primitiveByteArray();
- //
- //@Optional
- //Property<byte[]> primitiveByteArrayNull();
- //
- //Property<Byte[]> byteArray();
- //
- //@Optional
- //Property<Byte[]> byteArrayNull();
+ Property<byte[]> primitiveByteArray();
+
+ @Optional
+ Property<byte[]> primitiveByteArrayNull();
+
+ Property<Byte[]> byteArray();
+
+ @Optional
+ Property<Byte[]> byteArrayNull();
Property<Object> serializable();
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/2b5bad87/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
index d556f09..25f5a22 100644
--- a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
@@ -20,6 +20,7 @@ package org.apache.polygene.serialization.javaxxml;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
+import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
@@ -43,6 +44,7 @@ import org.apache.polygene.api.property.PropertyDescriptor;
import org.apache.polygene.api.serialization.SerializationException;
import org.apache.polygene.api.service.ServiceDescriptor;
import org.apache.polygene.api.structure.ModuleDescriptor;
+import org.apache.polygene.api.type.ArrayType;
import org.apache.polygene.api.type.CollectionType;
import org.apache.polygene.api.type.EnumType;
import org.apache.polygene.api.type.MapType;
@@ -104,6 +106,10 @@ public class JavaxXmlDeserializer extends AbstractTextDeserializer implements Xm
{
return (T) Enum.valueOf( (Class) valueType.primaryType(), xml.getNodeValue() );
}
+ if( ArrayType.class.isAssignableFrom( valueType.getClass() ) )
+ {
+ return (T) deserializeArray( module, (ArrayType) valueType, xml );
+ }
if( CollectionType.class.isAssignableFrom( valueType.getClass() ) )
{
return (T) deserializeCollection( module, (CollectionType) valueType, xml );
@@ -209,6 +215,23 @@ public class JavaxXmlDeserializer extends AbstractTextDeserializer implements Xm
.orElse( Stream.empty() );
}
+
+ private Object deserializeArray( ModuleDescriptor module, ArrayType arrayType, Node xml )
+ {
+ if( arrayType.isArrayOfPrimitiveBytes() )
+ {
+ return Base64.getDecoder().decode( xml.getNodeValue().getBytes( UTF_8 ) );
+ }
+ CollectionType collectionType = CollectionType.listOf( arrayType.collectedType() );
+ List collection = (List) deserializeCollection( module, collectionType, xml );
+ Object array = Array.newInstance( arrayType.collectedType().primaryType(), collection.size() );
+ for( int idx = 0; idx < collection.size(); idx++ )
+ {
+ Array.set( array, idx, collection.get( idx ) );
+ }
+ return array;
+ }
+
@SuppressWarnings( "unchecked" )
private Collection deserializeCollection( ModuleDescriptor module, CollectionType collectionType, Node xml )
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/2b5bad87/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java
index bf26f0c..f0ce0fa 100644
--- a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java
@@ -36,9 +36,11 @@ import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.injection.scope.Uses;
import org.apache.polygene.api.serialization.SerializationException;
import org.apache.polygene.api.service.ServiceDescriptor;
+import org.apache.polygene.api.type.ArrayType;
import org.apache.polygene.api.type.EnumType;
import org.apache.polygene.api.type.MapType;
import org.apache.polygene.api.type.ValueCompositeType;
+import org.apache.polygene.api.util.ArrayIterable;
import org.apache.polygene.api.value.ValueComposite;
import org.apache.polygene.api.value.ValueDescriptor;
import org.apache.polygene.spi.serialization.AbstractTextSerializer;
@@ -114,6 +116,10 @@ public class JavaxXmlSerializer extends AbstractTextSerializer implements XmlSer
{
return serializeMap( document, options, (Map<?, ?>) object );
}
+ if( ArrayType.isArray( objectClass ) )
+ {
+ return serializeArray( document, options, object );
+ }
if( Iterable.class.isAssignableFrom( objectClass ) )
{
return serializeIterable( document, options, (Iterable<?>) object );
@@ -230,6 +236,21 @@ public class JavaxXmlSerializer extends AbstractTextSerializer implements XmlSer
return mapElement;
}
+ private <T> Node serializeArray( Document document, Options options, T object )
+ {
+ ArrayType valueType = ArrayType.of( object.getClass() );
+ if( valueType.isArrayOfPrimitiveBytes() )
+ {
+ byte[] base64 = Base64.getEncoder().encode( (byte[]) object );
+ return document.createCDATASection( new String( base64, UTF_8 ) );
+ }
+ if( valueType.isArrayOfPrimitives() )
+ {
+ return serializeIterable( document, options, new ArrayIterable( object ) );
+ }
+ return serializeStream( document, options, Stream.of( (Object[]) object ) );
+ }
+
private Node serializeIterable( Document document, Options options, Iterable<?> object )
{
return serializeStream( document, options, StreamSupport.stream( object.spliterator(), false ) );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/2b5bad87/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
index 56f32e6..70b4b8a 100644
--- a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
+++ b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
@@ -21,6 +21,7 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
+import java.lang.reflect.Array;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
@@ -41,6 +42,7 @@ import org.apache.polygene.api.property.PropertyDescriptor;
import org.apache.polygene.api.serialization.Deserializer;
import org.apache.polygene.api.serialization.SerializationException;
import org.apache.polygene.api.structure.ModuleDescriptor;
+import org.apache.polygene.api.type.ArrayType;
import org.apache.polygene.api.type.CollectionType;
import org.apache.polygene.api.type.EnumType;
import org.apache.polygene.api.type.MapType;
@@ -107,6 +109,10 @@ public interface MessagePackDeserializer extends Deserializer
{
return (T) Enum.valueOf( (Class) valueType.primaryType(), value.asStringValue().asString() );
}
+ if( ArrayType.class.isAssignableFrom( valueType.getClass() ) )
+ {
+ return (T) deserializeArray( module, (ArrayType) valueType, value );
+ }
if( CollectionType.class.isAssignableFrom( valueType.getClass() ) )
{
return (T) deserializeCollection( module, (CollectionType) valueType, value.asArrayValue() );
@@ -127,6 +133,22 @@ public interface MessagePackDeserializer extends Deserializer
}
}
+ private Object deserializeArray( ModuleDescriptor module, ArrayType arrayType, Value value ) throws IOException
+ {
+ if( arrayType.isArrayOfPrimitiveBytes() )
+ {
+ return value.asBinaryValue().asByteArray();
+ }
+ CollectionType collectionType = CollectionType.listOf( arrayType.collectedType() );
+ List collection = (List) deserializeCollection( module, collectionType, value.asArrayValue() );
+ Object array = Array.newInstance( arrayType.collectedType().primaryType(), collection.size() );
+ for( int idx = 0; idx < collection.size(); idx++ )
+ {
+ Array.set( array, idx, collection.get( idx ) );
+ }
+ return array;
+ }
+
private Collection<?> deserializeCollection( ModuleDescriptor module, CollectionType collectionType,
ArrayValue value ) throws IOException
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/2b5bad87/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java
index 7321e6d..a8f396c 100644
--- a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java
+++ b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java
@@ -32,9 +32,11 @@ import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.serialization.SerializationException;
import org.apache.polygene.api.serialization.Serializer;
+import org.apache.polygene.api.type.ArrayType;
import org.apache.polygene.api.type.EnumType;
import org.apache.polygene.api.type.MapType;
import org.apache.polygene.api.type.ValueCompositeType;
+import org.apache.polygene.api.util.ArrayIterable;
import org.apache.polygene.api.value.ValueComposite;
import org.apache.polygene.api.value.ValueDescriptor;
import org.apache.polygene.spi.serialization.AbstractBinarySerializer;
@@ -99,6 +101,10 @@ public interface MessagePackSerializer extends Serializer
{
return serializeMap( options, (Map<?, ?>) object );
}
+ if( ArrayType.isArray( objectClass ) )
+ {
+ return serializeArray( options, object );
+ }
if( Iterable.class.isAssignableFrom( objectClass ) )
{
return serializeIterable( options, (Iterable<?>) object );
@@ -162,6 +168,20 @@ public interface MessagePackSerializer extends Serializer
return builder.build();
}
+ private Value serializeArray( Options options, Object object )
+ {
+ ArrayType valueType = ArrayType.of( object.getClass() );
+ if( valueType.isArrayOfPrimitiveBytes() )
+ {
+ return ValueFactory.newBinary( (byte[]) object );
+ }
+ if( valueType.isArrayOfPrimitives() )
+ {
+ return serializeIterable( options, new ArrayIterable( object ) );
+ }
+ return serializeStream( options, Stream.of( (Object[]) object ) );
+ }
+
private ArrayValue serializeIterable( Options options, Iterable<?> iterable )
{
return serializeStream( options, StreamSupport.stream( iterable.spliterator(), false ) );
[31/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java
new file mode 100644
index 0000000..5450ec9
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java
@@ -0,0 +1,216 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxjson;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+import java.io.UncheckedIOException;
+import java.util.Base64;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+import javax.json.Json;
+import javax.json.JsonArray;
+import javax.json.JsonArrayBuilder;
+import javax.json.JsonObject;
+import javax.json.JsonObjectBuilder;
+import javax.json.JsonString;
+import javax.json.JsonValue;
+import org.apache.polygene.api.PolygeneAPI;
+import org.apache.polygene.api.association.AssociationStateHolder;
+import org.apache.polygene.api.composite.CompositeInstance;
+import org.apache.polygene.api.injection.scope.This;
+import org.apache.polygene.api.injection.scope.Uses;
+import org.apache.polygene.api.service.ServiceDescriptor;
+import org.apache.polygene.api.type.EnumType;
+import org.apache.polygene.api.type.MapType;
+import org.apache.polygene.api.type.ValueCompositeType;
+import org.apache.polygene.api.type.ValueType;
+import org.apache.polygene.api.value.ValueComposite;
+import org.apache.polygene.api.value.ValueDescriptor;
+import org.apache.polygene.spi.serialization.AbstractTextSerializer;
+import org.apache.polygene.spi.serialization.JsonSerializer;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static java.util.stream.Collectors.toList;
+import static org.apache.polygene.api.util.Collectors.toMap;
+
+public class JavaxJsonSerializer extends AbstractTextSerializer implements JsonSerializer
+{
+ @This
+ private JavaxJsonAdapters adapters;
+
+ @Uses
+ private ServiceDescriptor descriptor;
+
+ @Override
+ public <T> Function<T, JsonValue> toJsonFunction( Options options )
+ {
+ return object -> doSerialize( options, object, true );
+ }
+
+ private JsonValue doSerialize( Options options, Object object, boolean root )
+ {
+ if( object == null )
+ {
+ return JsonValue.NULL;
+ }
+ Class<?> objectClass = object.getClass();
+ JavaxJsonAdapter<?> adapter = adapters.adapterFor( objectClass );
+ if( adapter != null )
+ {
+ return adapter.serialize( object, obj -> doSerialize( options, obj, false ) );
+ }
+ if( EnumType.isEnum( objectClass ) )
+ {
+ return JavaxJson.toJsonString( object.toString() );
+ }
+ if( ValueCompositeType.isValueComposite( objectClass ) )
+ {
+ return serializeValueComposite( options, object, root );
+ }
+ if( MapType.isMap( objectClass ) )
+ {
+ return serializeMap( options, (Map<?, ?>) object );
+ }
+ if( Iterable.class.isAssignableFrom( objectClass ) )
+ {
+ return serializeIterable( options, (Iterable<?>) object );
+ }
+ if( Stream.class.isAssignableFrom( objectClass ) )
+ {
+ return serializeStream( options, (Stream<?>) object );
+ }
+ // Fallback to Java Serialization in Base 64
+ // Include all arrays!
+ return serializeBase64( object );
+ }
+
+ private JsonObject serializeValueComposite( Options options, Object composite, boolean root )
+ {
+ CompositeInstance instance = PolygeneAPI.FUNCTION_COMPOSITE_INSTANCE_OF.apply( (ValueComposite) composite );
+ ValueDescriptor descriptor = (ValueDescriptor) instance.descriptor();
+ AssociationStateHolder state = (AssociationStateHolder) instance.state();
+ ValueCompositeType valueType = descriptor.valueType();
+
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ valueType.properties().forEach(
+ property -> builder.add(
+ property.qualifiedName().name(),
+ doSerialize( options, state.propertyFor( property.accessor() ).get(), false ) ) );
+ valueType.associations().forEach(
+ association -> builder.add(
+ association.qualifiedName().name(),
+ doSerialize( options, state.associationFor( association.accessor() ).reference(), false ) ) );
+ valueType.manyAssociations().forEach(
+ association -> builder.add(
+ association.qualifiedName().name(),
+ doSerialize( options, state.manyAssociationFor( association.accessor() ).references()
+ .collect( toList() ),
+ false ) ) );
+ valueType.namedAssociations().forEach(
+ association -> builder.add(
+ association.qualifiedName().name(),
+ doSerialize( options,
+ state.namedAssociationFor( association.accessor() ).references()
+ .collect( toMap() ),
+ false ) ) );
+ if( !root && options.includeTypeInfo() )
+ {
+ withTypeInfo( builder, valueType );
+ }
+ return builder.build();
+ }
+
+ private JsonObjectBuilder withTypeInfo( JsonObjectBuilder builder, ValueType valueType )
+ {
+ return builder.add( getTypeInfoPropertyName(), valueType.primaryType().getName() );
+ }
+
+ /**
+ * Map serialization.
+ *
+ * {@literal Map<String, ?>} are serialized to a {@literal JsonObject}.
+ * {@literal Map<?, ?>} are serialized to a {@literal JsonArray} or key/value {@literal JsonObject}s.
+ * Empty maps are serialized to an empty {@literal JsonObject}.
+ */
+ private JsonValue serializeMap( Options options, Map<?, ?> map )
+ {
+ if( map.isEmpty() )
+ {
+ // Defaults to {}
+ return Json.createObjectBuilder().build();
+ }
+ Predicate<Object> characterKeyPredicate = key ->
+ key != null && ( key instanceof CharSequence || key instanceof Character );
+ if( map.keySet().stream().allMatch( characterKeyPredicate ) )
+ {
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ map.entrySet().forEach( entry -> builder.add( entry.getKey().toString(),
+ doSerialize( options, entry.getValue(), false ) ) );
+ return builder.build();
+ }
+ else
+ {
+ JsonArrayBuilder builder = Json.createArrayBuilder();
+ map.entrySet().forEach(
+ entry -> builder.add(
+ Json.createObjectBuilder()
+ .add( "key", doSerialize( options, entry.getKey(), false ) )
+ .add( "value", doSerialize( options, entry.getValue(), false ) )
+ .build() ) );
+ return builder.build();
+ }
+ }
+
+ private JsonArray serializeIterable( Options options, Iterable<?> iterable )
+ {
+ return serializeStream( options, StreamSupport.stream( iterable.spliterator(), false ) );
+ }
+
+ private <T> JsonArray serializeStream( Options options, Stream<?> stream )
+ {
+ JsonArrayBuilder builder = Json.createArrayBuilder();
+ stream.forEach( element -> builder.add( doSerialize( options, element, false ) ) );
+ return builder.build();
+ }
+
+ private JsonString serializeBase64( Object object )
+ {
+ ByteArrayOutputStream bout = new ByteArrayOutputStream();
+ try( ObjectOutputStream out = new ObjectOutputStream( bout ) )
+ {
+ out.writeUnshared( object );
+ byte[] bytes = Base64.getEncoder().encode( bout.toByteArray() );
+ return JavaxJson.toJsonString( new String( bytes, UTF_8 ) );
+ }
+ catch( IOException ex )
+ {
+ throw new UncheckedIOException( ex );
+ }
+ }
+
+ private String getTypeInfoPropertyName()
+ {
+ return JavaxJsonSettings.orDefault( descriptor.metaInfo( JavaxJsonSettings.class ) )
+ .getTypeInfoPropertyName();
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSettings.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSettings.java b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSettings.java
new file mode 100644
index 0000000..266bd99
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSettings.java
@@ -0,0 +1,73 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxjson;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.apache.polygene.api.type.ValueType;
+
+public class JavaxJsonSettings
+{
+ public static final JavaxJsonSettings DEFAULT = new JavaxJsonSettings();
+
+ public static JavaxJsonSettings orDefault( JavaxJsonSettings settings )
+ {
+ return settings != null ? settings : DEFAULT;
+ }
+
+ private String typeInfoPropertyName;
+ private Map<ValueType, JavaxJsonAdapter<?>> adapters;
+
+ public JavaxJsonSettings()
+ {
+ typeInfoPropertyName = "_type";
+ adapters = new LinkedHashMap<>();
+ }
+
+ public String getTypeInfoPropertyName()
+ {
+ return typeInfoPropertyName;
+ }
+
+ public void setTypeInfoPropertyName( String typeInfoPropertyName )
+ {
+ this.typeInfoPropertyName = typeInfoPropertyName;
+ }
+
+ public Map<ValueType, JavaxJsonAdapter<?>> getAdapters()
+ {
+ return adapters;
+ }
+
+ public JavaxJsonSettings withTypeInfoPropertyName( String typeInfoPropertyName )
+ {
+ setTypeInfoPropertyName( typeInfoPropertyName );
+ return this;
+ }
+
+ public JavaxJsonSettings withJsonAdapter( ValueType valueType, JavaxJsonAdapter<?> adapter )
+ {
+ getAdapters().put( valueType, adapter );
+ return this;
+ }
+
+ public JavaxJsonSettings withJsonAdapter( JavaxJsonAdapter<?> adapter )
+ {
+ return withJsonAdapter( ValueType.of( adapter.type() ), adapter );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/package.html
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/package.html b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/package.html
new file mode 100644
index 0000000..43db1d9
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/package.html
@@ -0,0 +1,24 @@
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ ~
+ ~
+ -->
+<html>
+ <body>
+ <h2>javax.json Serialization.</h2>
+ </body>
+</html>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONEntityState.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONEntityState.java b/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONEntityState.java
index 6bbef04..e4b5c05 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONEntityState.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONEntityState.java
@@ -14,28 +14,32 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
- *
*/
package org.apache.polygene.spi.entitystore.helpers;
import java.time.Instant;
+import java.util.Map;
+import javax.json.Json;
+import javax.json.JsonArray;
+import javax.json.JsonArrayBuilder;
+import javax.json.JsonObject;
+import javax.json.JsonObjectBuilder;
+import javax.json.JsonValue;
import org.apache.polygene.api.common.QualifiedName;
import org.apache.polygene.api.entity.EntityDescriptor;
import org.apache.polygene.api.entity.EntityReference;
import org.apache.polygene.api.property.PropertyDescriptor;
+import org.apache.polygene.api.serialization.SerializationException;
import org.apache.polygene.api.structure.ModuleDescriptor;
import org.apache.polygene.api.type.ValueType;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.api.value.ValueSerializationException;
+import org.apache.polygene.api.value.ValueDescriptor;
+import org.apache.polygene.serialization.javaxjson.JavaxJson;
import org.apache.polygene.spi.entity.EntityState;
import org.apache.polygene.spi.entity.EntityStatus;
import org.apache.polygene.spi.entity.ManyAssociationState;
import org.apache.polygene.spi.entity.NamedAssociationState;
import org.apache.polygene.spi.entitystore.EntityStoreException;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
+import org.apache.polygene.spi.serialization.JsonSerialization;
/**
* Standard JSON implementation of EntityState.
@@ -43,7 +47,6 @@ import org.json.JSONObject;
public final class JSONEntityState
implements EntityState
{
- private static final String[] EMPTY_NAMES = new String[ 0 ];
private static final String[] CLONE_NAMES =
{
JSONKeys.IDENTITY,
@@ -54,27 +57,27 @@ public final class JSONEntityState
};
private final ModuleDescriptor module;
- private final ValueSerialization valueSerialization;
private final String version;
private final EntityReference reference;
private final EntityDescriptor entityDescriptor;
+ private final JsonSerialization serialization;
private EntityStatus status;
private Instant lastModified;
- private JSONObject state;
+ private JsonObject state;
/* package */ JSONEntityState( ModuleDescriptor module,
- ValueSerialization valueSerialization,
+ JsonSerialization serialization,
String version,
Instant lastModified,
EntityReference reference,
EntityStatus status,
EntityDescriptor entityDescriptor,
- JSONObject state
+ JsonObject state
)
{
this.module = module;
- this.valueSerialization = valueSerialization;
+ this.serialization = serialization;
this.version = version;
this.lastModified = lastModified;
this.reference = reference;
@@ -107,22 +110,45 @@ public final class JSONEntityState
{
try
{
- Object json = state.getJSONObject( JSONKeys.PROPERTIES ).opt( stateName.name() );
- if( JSONObject.NULL.equals( json ) )
+ JsonValue json = state.getJsonObject( JSONKeys.PROPERTIES ).get( stateName.name() );
+ if( json == null || JsonValue.NULL.equals( json ) )
{
return null;
}
else
{
- PropertyDescriptor descriptor = entityDescriptor.state().findPropertyModelByQualifiedName( stateName );
- if( descriptor == null )
+ // TODO This rely on _type explicitely :(
+ // Needed because of this mess that is JsonEntityState
+ ValueType propertyValueType = null;
+ if( json.getValueType() == JsonValue.ValueType.OBJECT )
+ {
+ String typeInfo = ( (JsonObject) json ).getString( "_type", null );
+ if( typeInfo != null )
+ {
+ ValueDescriptor valueDescriptor = module.valueDescriptor( typeInfo );
+ if( valueDescriptor != null )
+ {
+ propertyValueType = valueDescriptor.valueType();
+ }
+ }
+ }
+ if( propertyValueType == null )
+ {
+ PropertyDescriptor descriptor = entityDescriptor.state()
+ .findPropertyModelByQualifiedName( stateName );
+ if( descriptor != null )
+ {
+ propertyValueType = descriptor.valueType();
+ }
+ }
+ if( propertyValueType == null )
{
return null;
}
- return valueSerialization.deserialize( module, descriptor.valueType(), json.toString() );
+ return serialization.fromJson( module, propertyValueType, json );
}
}
- catch( ValueSerializationException | JSONException e )
+ catch( SerializationException e )
{
throw new EntityStoreException( e );
}
@@ -133,129 +159,44 @@ public final class JSONEntityState
{
try
{
- Object jsonValue;
- if( newValue == null || ValueType.isPrimitiveValue( newValue ) )
- {
- jsonValue = newValue;
- }
- else if( ValueType.isIdentity( newValue ) )
- {
- jsonValue = newValue.toString();
- }
- else
- {
- String serialized = valueSerialization.serialize( newValue );
- if( serialized.startsWith( "{" ) )
- {
- jsonValue = new JSONObject( serialized );
- }
- else if( serialized.startsWith( "[" ) )
- {
- jsonValue = new JSONArray( serialized );
- }
- else
- {
- jsonValue = serialized;
- }
- }
- cloneStateIfGlobalStateLoaded();
- state.getJSONObject( JSONKeys.PROPERTIES ).put( stateName.name(), jsonValue );
+ JsonValue jsonValue = serialization.toJson( newValue );
+ stateCloneWithProperty( stateName.name(), jsonValue );
markUpdated();
}
- catch( ValueSerializationException | JSONException e )
+ catch( SerializationException e )
{
throw new EntityStoreException( "Unable to set property " + stateName + " value " + newValue, e );
}
}
- private JSONObject cloneJSON( JSONObject jsonObject )
- throws JSONException
- {
- String[] names = JSONObject.getNames( jsonObject );
- if( names == null )
- {
- names = EMPTY_NAMES;
- }
- return new JSONObject( jsonObject, names );
- }
-
@Override
public EntityReference associationValueOf( QualifiedName stateName )
{
- try
- {
- Object jsonValue = state.getJSONObject( JSONKeys.ASSOCIATIONS ).opt( stateName.name() );
- if( jsonValue == null )
- {
- return null;
- }
-
- EntityReference value = jsonValue == JSONObject.NULL
- ? null
- : EntityReference.parseEntityReference( (String) jsonValue );
- return value;
- }
- catch( JSONException e )
+ String jsonValue = state.getJsonObject( JSONKeys.ASSOCIATIONS ).getString( stateName.name(), null );
+ if( jsonValue == null )
{
- throw new EntityStoreException( e );
+ return null;
}
+ return EntityReference.parseEntityReference( jsonValue );
}
@Override
public void setAssociationValue( QualifiedName stateName, EntityReference newEntity )
{
- try
- {
- cloneStateIfGlobalStateLoaded();
- state.getJSONObject( JSONKeys.ASSOCIATIONS ).put( stateName.name(), newEntity == null
- ? null
- : newEntity.identity().toString() );
- markUpdated();
- }
- catch( JSONException e )
- {
- throw new EntityStoreException( e );
- }
+ stateCloneWithAssociation( stateName.name(), newEntity );
+ markUpdated();
}
@Override
public ManyAssociationState manyAssociationValueOf( QualifiedName stateName )
{
- try
- {
- JSONObject manyAssociations = state.getJSONObject( JSONKeys.MANY_ASSOCIATIONS );
- JSONArray jsonValues = manyAssociations.optJSONArray( stateName.name() );
- if( jsonValues == null )
- {
- jsonValues = new JSONArray();
- manyAssociations.put( stateName.name(), jsonValues );
- }
- return new JSONManyAssociationState( this, jsonValues );
- }
- catch( JSONException e )
- {
- throw new EntityStoreException( e );
- }
+ return new JSONManyAssociationState( this, stateName.name() );
}
@Override
public NamedAssociationState namedAssociationValueOf( QualifiedName stateName )
{
- try
- {
- JSONObject namedAssociations = state.getJSONObject( JSONKeys.NAMED_ASSOCIATIONS );
- JSONObject jsonValues = namedAssociations.optJSONObject( stateName.name() );
- if( jsonValues == null )
- {
- jsonValues = new JSONObject();
- namedAssociations.put( stateName.name(), jsonValues );
- }
- return new JSONNamedAssociationState( this, jsonValues );
- }
- catch( JSONException e )
- {
- throw new EntityStoreException( e );
- }
+ return new JSONNamedAssociationState( this, stateName.name() );
}
@Override
@@ -282,7 +223,7 @@ public final class JSONEntityState
return entityDescriptor;
}
- public JSONObject state()
+ public JsonObject state()
{
return state;
}
@@ -293,7 +234,7 @@ public final class JSONEntityState
return reference + "(" + state + ")";
}
- public void markUpdated()
+ void markUpdated()
{
if( status == EntityStatus.LOADED )
{
@@ -301,29 +242,217 @@ public final class JSONEntityState
}
}
- void cloneStateIfGlobalStateLoaded()
+ void stateCloneWithVersionAndModified( String version, Instant lastModified )
+ {
+ JsonObjectBuilder builder = JavaxJson.toBuilder( state );
+ builder.add( JSONKeys.VERSION, version );
+ builder.add( JSONKeys.MODIFIED, lastModified.toEpochMilli() );
+ state = builder.build();
+ }
+
+ void stateCloneWithProperty( String stateName, JsonValue value )
{
- if( status != EntityStatus.LOADED )
+ JsonObjectBuilder builder = stateShallowClone();
+ JsonObjectBuilder propertiesBuilder = JavaxJson.toBuilder( state.getJsonObject( JSONKeys.PROPERTIES ) );
+ if( value == null )
+ {
+ propertiesBuilder.add( stateName, JsonValue.NULL );
+ }
+ else
{
- return;
+ propertiesBuilder.add( stateName, value );
}
+ builder.add( JSONKeys.PROPERTIES, propertiesBuilder.build() );
+ builder.add( JSONKeys.ASSOCIATIONS, state.get( JSONKeys.ASSOCIATIONS ) );
+ builder.add( JSONKeys.MANY_ASSOCIATIONS, state.get( JSONKeys.MANY_ASSOCIATIONS ) );
+ builder.add( JSONKeys.NAMED_ASSOCIATIONS, state.get( JSONKeys.NAMED_ASSOCIATIONS ) );
+ state = builder.build();
+ }
- try
+ void stateCloneWithAssociation( String stateName, EntityReference ref )
+ {
+ JsonObjectBuilder builder = stateShallowClone();
+ JsonObjectBuilder assocBuilder = JavaxJson.toBuilder( state.getJsonObject( JSONKeys.ASSOCIATIONS ) );
+ if( ref == null )
{
- JSONObject newProperties = cloneJSON( state.getJSONObject( JSONKeys.PROPERTIES ) );
- JSONObject newAssoc = cloneJSON( state.getJSONObject( JSONKeys.ASSOCIATIONS ) );
- JSONObject newManyAssoc = cloneJSON( state.getJSONObject( JSONKeys.MANY_ASSOCIATIONS ) );
- JSONObject newNamedAssoc = cloneJSON( state.getJSONObject( JSONKeys.NAMED_ASSOCIATIONS ) );
- JSONObject stateClone = new JSONObject( state, CLONE_NAMES );
- stateClone.put( JSONKeys.PROPERTIES, newProperties );
- stateClone.put( JSONKeys.ASSOCIATIONS, newAssoc );
- stateClone.put( JSONKeys.MANY_ASSOCIATIONS, newManyAssoc );
- stateClone.put( JSONKeys.NAMED_ASSOCIATIONS, newNamedAssoc );
- state = stateClone;
+ assocBuilder.add( stateName, JsonValue.NULL );
}
- catch( JSONException e )
+ else
{
- throw new EntityStoreException( e );
+ assocBuilder.add( stateName, ref.identity().toString() );
+ }
+ builder.add( JSONKeys.PROPERTIES, state.get( JSONKeys.PROPERTIES ) );
+ builder.add( JSONKeys.ASSOCIATIONS, assocBuilder.build() );
+ builder.add( JSONKeys.MANY_ASSOCIATIONS, state.get( JSONKeys.MANY_ASSOCIATIONS ) );
+ builder.add( JSONKeys.NAMED_ASSOCIATIONS, state.get( JSONKeys.NAMED_ASSOCIATIONS ) );
+ state = builder.build();
+ }
+
+ void stateCloneAddManyAssociation( int idx, String stateName, EntityReference ref )
+ {
+ JsonObjectBuilder builder = stateShallowClone();
+ JsonObjectBuilder manyAssociations = Json.createObjectBuilder();
+ JsonObject previousManyAssociations = state.getJsonObject( JSONKeys.MANY_ASSOCIATIONS );
+ for( Map.Entry<String, JsonValue> previousManyAssociation : previousManyAssociations.entrySet() )
+ {
+ String key = previousManyAssociation.getKey();
+ if( !key.equals( stateName ) )
+ {
+ manyAssociations.add( key, previousManyAssociation.getValue() );
+ }
+ }
+ JsonValue previousReferences = previousManyAssociations.get( stateName );
+ JsonArrayBuilder references = Json.createArrayBuilder();
+ String newRef = ref.identity().toString();
+ if( previousReferences == null || previousReferences.getValueType() != JsonValue.ValueType.ARRAY )
+ {
+ references.add( newRef );
+ }
+ else
+ {
+ JsonArray previousReferencesArray = (JsonArray) previousReferences;
+ boolean insert = !previousReferencesArray.contains( newRef );
+ for( int i = 0; i < previousReferencesArray.size(); i++ )
+ {
+ if( insert && i == idx )
+ {
+ references.add( newRef );
+ }
+ references.add( previousReferencesArray.getString( i ) );
+ }
+ if( insert && idx >= previousReferencesArray.size() )
+ {
+ references.add( newRef );
+ }
+ }
+ manyAssociations.add( stateName, references.build() );
+ builder.add( JSONKeys.PROPERTIES, state.get( JSONKeys.PROPERTIES ) );
+ builder.add( JSONKeys.ASSOCIATIONS, state.get( JSONKeys.ASSOCIATIONS ) );
+ builder.add( JSONKeys.MANY_ASSOCIATIONS, manyAssociations.build() );
+ builder.add( JSONKeys.NAMED_ASSOCIATIONS, state.get( JSONKeys.NAMED_ASSOCIATIONS ) );
+ state = builder.build();
+ }
+
+ void stateCloneRemoveManyAssociation( String stateName, EntityReference ref )
+ {
+ String stringRef = ref.identity().toString();
+ JsonObjectBuilder builder = stateShallowClone();
+ JsonObjectBuilder manyAssociations = Json.createObjectBuilder();
+ JsonObject previousManyAssociations = state.getJsonObject( JSONKeys.MANY_ASSOCIATIONS );
+ for( Map.Entry<String, JsonValue> previousManyAssociation : previousManyAssociations.entrySet() )
+ {
+ String key = previousManyAssociation.getKey();
+ if( !key.equals( stateName ) )
+ {
+ manyAssociations.add( key, previousManyAssociation.getValue() );
+ }
+ }
+ JsonValue previousReferences = previousManyAssociations.get( stateName );
+ JsonArrayBuilder references = Json.createArrayBuilder();
+ if( previousReferences != null && previousReferences.getValueType() == JsonValue.ValueType.ARRAY )
+ {
+ JsonArray previousReferencesArray = (JsonArray) previousReferences;
+ for( int idx = 0; idx < previousReferencesArray.size(); idx++ )
+ {
+ String previousRef = previousReferencesArray.getString( idx );
+ if( !stringRef.equals( previousRef ) )
+ {
+ references.add( previousRef );
+ }
+ }
+ }
+ manyAssociations.add( stateName, references.build() );
+ builder.add( JSONKeys.PROPERTIES, state.get( JSONKeys.PROPERTIES ) );
+ builder.add( JSONKeys.ASSOCIATIONS, state.get( JSONKeys.ASSOCIATIONS ) );
+ builder.add( JSONKeys.MANY_ASSOCIATIONS, manyAssociations.build() );
+ builder.add( JSONKeys.NAMED_ASSOCIATIONS, state.get( JSONKeys.NAMED_ASSOCIATIONS ) );
+ state = builder.build();
+ }
+
+ void stateCloneAddNamedAssociation( String stateName, String name, EntityReference ref )
+ {
+ JsonObjectBuilder builder = stateShallowClone();
+ JsonObject previousNamedAssociations = state.getJsonObject( JSONKeys.NAMED_ASSOCIATIONS );
+ JsonObjectBuilder namedAssociations = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> previousNamedAssociation : previousNamedAssociations.entrySet() )
+ {
+ String key = previousNamedAssociation.getKey();
+ if( !key.equals( stateName ) )
+ {
+ namedAssociations.add( key, previousNamedAssociation.getValue() );
+ }
+ }
+ JsonValue previousReferences = previousNamedAssociations.get( stateName );
+ JsonObjectBuilder references = Json.createObjectBuilder();
+ String newRef = ref.identity().toString();
+ if( previousReferences == null || !( previousReferences instanceof JsonObject ) )
+ {
+ references.add( name, newRef );
+ }
+ else
+ {
+ JsonObject previousReferencesObject = (JsonObject) previousReferences;
+ for( Map.Entry<String, JsonValue> previousNamedReference : previousReferencesObject.entrySet() )
+ {
+ String key = previousNamedReference.getKey();
+ if( !key.equals( name ) )
+ {
+ references.add( key, previousNamedReference.getValue() );
+ }
+ }
+ references.add( name, ref.identity().toString() );
+ }
+ namedAssociations.add( stateName, references.build() );
+ builder.add( JSONKeys.PROPERTIES, state.get( JSONKeys.PROPERTIES ) );
+ builder.add( JSONKeys.ASSOCIATIONS, state.get( JSONKeys.ASSOCIATIONS ) );
+ builder.add( JSONKeys.MANY_ASSOCIATIONS, state.get( JSONKeys.MANY_ASSOCIATIONS ) );
+ builder.add( JSONKeys.NAMED_ASSOCIATIONS, namedAssociations.build() );
+ state = builder.build();
+ }
+
+ void stateCloneRemoveNamedAssociation( String stateName, String name )
+ {
+ JsonObjectBuilder builder = stateShallowClone();
+ JsonObjectBuilder namedAssociations = Json.createObjectBuilder();
+ JsonObject previousNamedAssociations = state.getJsonObject( JSONKeys.NAMED_ASSOCIATIONS );
+ for( Map.Entry<String, JsonValue> previousNamedAssociation : previousNamedAssociations.entrySet() )
+ {
+ String key = previousNamedAssociation.getKey();
+ if( !key.equals( stateName ) )
+ {
+ namedAssociations.add( key, previousNamedAssociation.getValue() );
+ }
+ }
+ JsonValue previousReferences = previousNamedAssociations.get( stateName );
+ JsonObjectBuilder references = Json.createObjectBuilder();
+ if( previousReferences != null && previousReferences.getValueType() == JsonValue.ValueType.OBJECT )
+ {
+ JsonObject previousReferencesObject = (JsonObject) previousReferences;
+ for( Map.Entry<String, JsonValue> previousNamedRef : previousReferencesObject.entrySet() )
+ {
+ String previousName = previousNamedRef.getKey();
+ if( !name.equals( previousName ) )
+ {
+ references.add( previousName, previousNamedRef.getValue() );
+ }
+ }
+ }
+ namedAssociations.add( stateName, references.build() );
+ builder.add( JSONKeys.PROPERTIES, state.get( JSONKeys.PROPERTIES ) );
+ builder.add( JSONKeys.ASSOCIATIONS, state.get( JSONKeys.ASSOCIATIONS ) );
+ builder.add( JSONKeys.MANY_ASSOCIATIONS, state.get( JSONKeys.MANY_ASSOCIATIONS ) );
+ builder.add( JSONKeys.NAMED_ASSOCIATIONS, namedAssociations.build() );
+ state = builder.build();
+ }
+
+ private JsonObjectBuilder stateShallowClone()
+ {
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ for( String cloneName : CLONE_NAMES )
+ {
+ JsonValue cloneValue = state.get( cloneName );
+ builder.add( cloneName, cloneValue == null ? JsonValue.NULL : cloneValue );
}
+ return builder;
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONManyAssociationState.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONManyAssociationState.java b/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONManyAssociationState.java
index b1efbc1..e9b99c4 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONManyAssociationState.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONManyAssociationState.java
@@ -21,39 +21,52 @@ package org.apache.polygene.spi.entitystore.helpers;
import java.util.Iterator;
import java.util.NoSuchElementException;
-import org.json.JSONArray;
-import org.json.JSONException;
+import javax.json.Json;
+import javax.json.JsonArray;
+import javax.json.JsonException;
+import javax.json.JsonObject;
+import javax.json.JsonValue;
import org.apache.polygene.api.entity.EntityReference;
import org.apache.polygene.spi.entity.ManyAssociationState;
import org.apache.polygene.spi.entitystore.EntityStoreException;
/**
* JSON implementation of ManyAssociationState.
- * <p>Backed by a JSONArray.</p>
+ * <p>Backed by a JsonArray.</p>
*/
public final class JSONManyAssociationState
implements ManyAssociationState
{
-
private final JSONEntityState entityState;
- private final JSONArray references;
+ private final String stateName;
- public JSONManyAssociationState( JSONEntityState entityState, JSONArray references )
+ /* package */ JSONManyAssociationState( JSONEntityState entityState, String stateName )
{
this.entityState = entityState;
- this.references = references;
+ this.stateName = stateName;
+ }
+
+ private JsonArray getReferences()
+ {
+ JsonObject manyAssociations = entityState.state().getJsonObject( JSONKeys.MANY_ASSOCIATIONS );
+ JsonValue references = manyAssociations.get( stateName );
+ if( references != null && references.getValueType() == JsonValue.ValueType.ARRAY )
+ {
+ return (JsonArray) references;
+ }
+ return Json.createArrayBuilder().build();
}
@Override
public int count()
{
- return references.length();
+ return getReferences().size();
}
@Override
public boolean contains( EntityReference entityReference )
{
- return indexOfReference( entityReference.toString() ) != -1;
+ return indexOfReference( entityReference.identity().toString() ) != -1;
}
@Override
@@ -65,12 +78,11 @@ public final class JSONManyAssociationState
{
return false;
}
- entityState.cloneStateIfGlobalStateLoaded();
- insertReference( idx, entityReference.identity().toString() );
+ entityState.stateCloneAddManyAssociation( idx, stateName, entityReference );
entityState.markUpdated();
return true;
}
- catch( JSONException e )
+ catch( JsonException e )
{
throw new EntityStoreException( e );
}
@@ -82,8 +94,7 @@ public final class JSONManyAssociationState
int refIndex = indexOfReference( entityReference.identity().toString() );
if( refIndex != -1 )
{
- entityState.cloneStateIfGlobalStateLoaded();
- references.remove( refIndex );
+ entityState.stateCloneRemoveManyAssociation( stateName, entityReference );
entityState.markUpdated();
return true;
}
@@ -93,14 +104,7 @@ public final class JSONManyAssociationState
@Override
public EntityReference get( int i )
{
- try
- {
- return EntityReference.parseEntityReference( references.getString( i ) );
- }
- catch( JSONException e )
- {
- throw new EntityStoreException( e );
- }
+ return EntityReference.parseEntityReference( getReferences().getString( i ) );
}
@Override
@@ -113,7 +117,7 @@ public final class JSONManyAssociationState
@Override
public boolean hasNext()
{
- return idx < references.length();
+ return idx < getReferences().size();
}
@Override
@@ -121,11 +125,11 @@ public final class JSONManyAssociationState
{
try
{
- EntityReference ref = EntityReference.parseEntityReference( references.getString( idx ) );
+ EntityReference ref = EntityReference.parseEntityReference( getReferences().getString( idx ) );
idx++;
return ref;
}
- catch( JSONException e )
+ catch( JsonException e )
{
throw new NoSuchElementException();
}
@@ -142,49 +146,19 @@ public final class JSONManyAssociationState
@Override
public String toString()
{
- return references.toString();
+ return getReferences().toString();
}
- private int indexOfReference( String enityIdentityAsString )
+ private int indexOfReference( String entityIdentityAsString )
{
- for( int idx = 0; idx < references.length(); idx++ )
+ JsonArray references = getReferences();
+ for( int idx = 0; idx < references.size(); idx++ )
{
- if( enityIdentityAsString.equals( references.opt( idx ) ) )
+ if( entityIdentityAsString.equals( references.getString( idx, null ) ) )
{
return idx;
}
}
return -1;
}
-
- private void insertReference( int insert, Object item )
- throws JSONException
- {
- if( insert < 0 || insert > references.length() )
- {
- throw new JSONException( "JSONArray[" + insert + "] is out of bounds." );
- }
- if( insert == references.length() )
- {
- // append
- references.put( item );
- }
- else
- {
- // insert (copy/insert/apply)
- JSONArray output = new JSONArray();
- for( int idx = 0; idx < references.length(); idx++ )
- {
- if( idx == insert )
- {
- output.put( item );
- }
- output.put( references.opt( idx ) );
- }
- for( int idx = 0; idx < output.length(); idx++ )
- {
- references.put( idx, output.opt( idx ) );
- }
- }
- }
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONMapEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONMapEntityStoreMixin.java b/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONMapEntityStoreMixin.java
index 82d4c05..a7f7690 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONMapEntityStoreMixin.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONMapEntityStoreMixin.java
@@ -14,8 +14,6 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
- *
*/
package org.apache.polygene.spi.entitystore.helpers;
@@ -24,12 +22,18 @@ import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Reader;
+import java.io.StringReader;
import java.io.Writer;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
+import java.util.function.Function;
import java.util.stream.Stream;
+import javax.json.Json;
+import javax.json.JsonObject;
+import javax.json.JsonObjectBuilder;
+import javax.json.JsonReader;
import org.apache.polygene.api.cache.CacheOptions;
import org.apache.polygene.api.common.Optional;
import org.apache.polygene.api.entity.EntityDescriptor;
@@ -42,13 +46,11 @@ import org.apache.polygene.api.injection.scope.Structure;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.injection.scope.Uses;
import org.apache.polygene.api.service.ServiceDescriptor;
-import org.apache.polygene.api.service.qualifier.Tagged;
import org.apache.polygene.api.structure.Application;
import org.apache.polygene.api.structure.ModuleDescriptor;
import org.apache.polygene.api.unitofwork.NoSuchEntityTypeException;
import org.apache.polygene.api.usecase.Usecase;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.spi.PolygeneSPI;
+import org.apache.polygene.serialization.javaxjson.JavaxJson;
import org.apache.polygene.spi.cache.Cache;
import org.apache.polygene.spi.cache.CachePool;
import org.apache.polygene.spi.cache.NullCache;
@@ -60,9 +62,7 @@ import org.apache.polygene.spi.entitystore.EntityStoreException;
import org.apache.polygene.spi.entitystore.EntityStoreSPI;
import org.apache.polygene.spi.entitystore.EntityStoreUnitOfWork;
import org.apache.polygene.spi.entitystore.StateCommitter;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.json.JSONTokener;
+import org.apache.polygene.spi.serialization.JsonSerialization;
/**
* Implementation of EntityStore that works with an implementation of MapEntityStore.
@@ -82,14 +82,10 @@ public class JSONMapEntityStoreMixin
private EntityStoreSPI entityStoreSpi;
@Structure
- private PolygeneSPI spi;
-
- @Structure
private Application application;
@Service
- @Tagged( ValueSerialization.Formats.JSON )
- private ValueSerialization valueSerialization;
+ private JsonSerialization serialization;
@Service
IdentityGenerator identityGenerator;
@@ -107,7 +103,6 @@ public class JSONMapEntityStoreMixin
private Cache<CacheState> cache;
protected String uuid;
- private int count;
public JSONMapEntityStoreMixin()
{
@@ -142,102 +137,109 @@ public class JSONMapEntityStoreMixin
// EntityStore
@Override
- public EntityStoreUnitOfWork newUnitOfWork( ModuleDescriptor module, Usecase usecaseMetaInfo, Instant currentTime )
+ public EntityStoreUnitOfWork newUnitOfWork( ModuleDescriptor module, Usecase usecase, Instant currentTime )
{
- return new DefaultEntityStoreUnitOfWork( module, entityStoreSpi, newUnitOfWorkId(), usecaseMetaInfo, currentTime );
+ return new DefaultEntityStoreUnitOfWork( module, entityStoreSpi, newUnitOfWorkId(), usecase, currentTime );
}
// EntityStoreSPI
@Override
- public EntityState newEntityState( EntityStoreUnitOfWork unitOfWork,
+ public EntityState newEntityState( EntityStoreUnitOfWork uow,
EntityReference reference,
EntityDescriptor entityDescriptor
)
{
try
{
- JSONObject state = new JSONObject();
- state.put( JSONKeys.IDENTITY, reference.identity() );
- state.put( JSONKeys.APPLICATION_VERSION, application.version() );
- state.put( JSONKeys.TYPE, entityDescriptor.types().findFirst().get().getName() );
- state.put( JSONKeys.VERSION, unitOfWork.identity() );
- state.put( JSONKeys.MODIFIED, unitOfWork.currentTime().toEpochMilli() );
- state.put( JSONKeys.PROPERTIES, new JSONObject() );
- state.put( JSONKeys.ASSOCIATIONS, new JSONObject() );
- state.put( JSONKeys.MANY_ASSOCIATIONS, new JSONObject() );
- state.put( JSONKeys.NAMED_ASSOCIATIONS, new JSONObject() );
- return new JSONEntityState( entityDescriptor.module(),
- valueSerialization,
- "",
- unitOfWork.currentTime(),
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ builder.add( JSONKeys.IDENTITY, reference.identity().toString() );
+ builder.add( JSONKeys.APPLICATION_VERSION, application.version() );
+ builder.add( JSONKeys.TYPE, entityDescriptor.types().findFirst().get().getName() );
+ builder.add( JSONKeys.VERSION, uow.identity().toString() );
+ builder.add( JSONKeys.MODIFIED, uow.currentTime().toEpochMilli() );
+ builder.add( JSONKeys.PROPERTIES, Json.createObjectBuilder().build() );
+ builder.add( JSONKeys.ASSOCIATIONS, Json.createObjectBuilder().build() );
+ builder.add( JSONKeys.MANY_ASSOCIATIONS, Json.createObjectBuilder().build() );
+ builder.add( JSONKeys.NAMED_ASSOCIATIONS, Json.createObjectBuilder().build() );
+ JsonObject state = builder.build();
+ return new JSONEntityState( entityDescriptor.module(), serialization,
+ "", uow.currentTime(),
reference,
- EntityStatus.NEW,
- entityDescriptor,
+ EntityStatus.NEW, entityDescriptor,
state );
}
- catch( JSONException e )
+ catch( Exception e )
{
throw new EntityStoreException( e );
}
}
@Override
- public synchronized EntityState entityStateOf( EntityStoreUnitOfWork unitOfWork,
+ public synchronized EntityState entityStateOf( EntityStoreUnitOfWork uow,
ModuleDescriptor module,
- EntityReference reference
- )
+ EntityReference reference )
{
- EntityState state = fetchCachedState( reference, module, unitOfWork.currentTime() );
- if( state != null )
+ try
{
- return state;
+ EntityState state = fetchCachedState( reference, module, uow.currentTime() );
+ if( state != null )
+ {
+ return state;
+ }
+ // Get state
+ try( Reader in = mapEntityStore.get( reference ) )
+ {
+ JSONEntityState loadedState = readEntityState( module, in );
+ if( loadedState.status() == EntityStatus.UPDATED )
+ {
+ List<JSONEntityState> migrated = new ArrayList<>( 1 );
+ migrated.add( loadedState );
+ synchMigratedEntities( migrated );
+ }
+ if( doCacheOnRead( uow ) )
+ {
+ cache.put( reference.identity().toString(), new CacheState( loadedState.state() ) );
+ }
+ return loadedState;
+ }
}
- // Get state
- Reader in = mapEntityStore.get( reference );
- JSONEntityState loadedState = readEntityState( module, in );
- if( doCacheOnRead( unitOfWork ) )
+ catch( EntityStoreException ex )
{
- cache.put( reference.identity().toString(), new CacheState( loadedState.state() ) );
+ throw ex;
+ }
+ catch( Exception ex )
+ {
+ throw new EntityStoreException( ex );
}
- return loadedState;
}
@Override
- public synchronized String versionOf( EntityStoreUnitOfWork unitOfWork,
- EntityReference reference
- )
+ public synchronized String versionOf( EntityStoreUnitOfWork uow, EntityReference reference )
{
CacheState cacheState = cache.get( reference.identity().toString() );
if( cacheState != null )
{
- try
- {
- return cacheState.json.getString( JSONKeys.VERSION );
- }
- catch( JSONException e )
- {
- // Should not be able to happen, unless internal error in the cache system.
- throw new EntityStoreException( e );
- }
+ return cacheState.json.getString( JSONKeys.VERSION );
}
- // Get state
- Reader entityState = mapEntityStore.get( reference );
try
{
- JSONObject jsonObject = new JSONObject( new JSONTokener( entityState ) );
- return jsonObject.getString( JSONKeys.VERSION );
+ // Get state
+ Reader entityState = mapEntityStore.get( reference );
+ return Json.createReader( entityState ).readObject().getString( JSONKeys.VERSION );
}
- catch( JSONException e )
+ catch( EntityStoreException ex )
{
- throw new EntityStoreException( e );
+ throw ex;
+ }
+ catch( Exception ex )
+ {
+ throw new EntityStoreException( ex );
}
}
@Override
- public StateCommitter applyChanges( final EntityStoreUnitOfWork unitOfWork,
- final Iterable<EntityState> state
- )
+ public StateCommitter applyChanges( EntityStoreUnitOfWork uow, Iterable<EntityState> state )
throws EntityStoreException
{
return new StateCommitter()
@@ -250,10 +252,9 @@ public class JSONMapEntityStoreMixin
mapEntityStore.applyChanges( new MapEntityStore.MapChanges()
{
@Override
- public void visitMap( MapEntityStore.MapChanger changer )
- throws IOException
+ public void visitMap( MapEntityStore.MapChanger changer ) throws Exception
{
- CacheOptions options = unitOfWork.usecase().metaInfo( CacheOptions.class );
+ CacheOptions options = uow.usecase().metaInfo( CacheOptions.class );
if( options == null )
{
options = CacheOptions.ALWAYS;
@@ -262,26 +263,35 @@ public class JSONMapEntityStoreMixin
for( EntityState entityState : state )
{
JSONEntityState state = (JSONEntityState) entityState;
+ String newVersion = uow.identity().toString();
+ Instant lastModified = uow.currentTime();
if( state.status().equals( EntityStatus.NEW ) )
{
- try (Writer writer = changer.newEntity( state.entityReference(), state.entityDescriptor() ))
+ try( Writer writer = changer.newEntity( state.entityReference(),
+ state.entityDescriptor() ) )
{
- writeEntityState( state, writer, unitOfWork.identity().toString(), unitOfWork.currentTime() );
+ writeEntityState( state, writer, newVersion, lastModified );
}
if( options.cacheOnNew() )
{
- cache.put( state.entityReference().identity().toString(), new CacheState( state.state() ) );
+ cache.put( state.entityReference().identity().toString(),
+ new CacheState( state.state() ) );
}
}
else if( state.status().equals( EntityStatus.UPDATED ) )
{
- try (Writer writer = changer.updateEntity( state.entityReference(), state.entityDescriptor() ))
+ MapEntityStore.MapChange mapChange = new MapEntityStore.MapChange(
+ state.entityReference(), state.entityDescriptor(),
+ state.version(), newVersion, lastModified
+ );
+ try( Writer writer = changer.updateEntity( mapChange ) )
{
- writeEntityState( state, writer, unitOfWork.identity().toString(), unitOfWork.currentTime() );
+ writeEntityState( state, writer, newVersion, lastModified );
}
if( options.cacheOnWrite() )
{
- cache.put( state.entityReference().identity().toString(), new CacheState( state.state() ) );
+ cache.put( state.entityReference().identity().toString(),
+ new CacheState( state.state() ) );
}
}
else if( state.status().equals( EntityStatus.REMOVED ) )
@@ -293,7 +303,7 @@ public class JSONMapEntityStoreMixin
}
} );
}
- catch( IOException e )
+ catch( Exception e )
{
throw new EntityStoreException( e );
}
@@ -309,11 +319,13 @@ public class JSONMapEntityStoreMixin
@Override
public Stream<EntityState> entityStates( ModuleDescriptor module )
{
- List<EntityState> migrated = new ArrayList<>();
- return mapEntityStore.entityStates().map(
- reader ->
+ try
+ {
+ Stream<Reader> stateStream = mapEntityStore.entityStates();
+ List<JSONEntityState> migrated = new ArrayList<>();
+ Function<Reader, EntityState> function = reader ->
{
- EntityState entity = readEntityState( module, reader );
+ JSONEntityState entity = readEntityState( module, reader );
if( entity.status() == EntityStatus.UPDATED )
{
migrated.add( entity );
@@ -324,42 +336,55 @@ public class JSONMapEntityStoreMixin
}
}
return entity;
- }
- ).onClose(
- () ->
+ };
+ Runnable closer = () ->
{
// Synch any remaining migrated entities
if( !migrated.isEmpty() )
{
synchMigratedEntities( migrated );
}
- }
- );
+ };
+ return stateStream.map( function ).onClose( closer );
+ }
+ catch( EntityStoreException ex )
+ {
+ throw ex;
+ }
+ catch( Exception ex )
+ {
+ throw new EntityStoreException( ex );
+ }
}
- private void synchMigratedEntities( final List<EntityState> migratedEntities )
+ private void synchMigratedEntities( List<JSONEntityState> migratedEntities )
{
try
{
- mapEntityStore.applyChanges( new MapEntityStore.MapChanges()
- {
- @Override
- public void visitMap( MapEntityStore.MapChanger changer )
- throws IOException
+ mapEntityStore.applyChanges(
+ changer ->
{
- for( EntityState migratedEntity : migratedEntities )
+ for( JSONEntityState state : migratedEntities )
{
- JSONEntityState state = (JSONEntityState) migratedEntity;
- try( Writer writer = changer.updateEntity( state.entityReference(), state.entityDescriptor() ) )
+ Instant lastModified = state.lastModified();
+ String version = state.version();
+ MapEntityStore.MapChange changeInfo = new MapEntityStore.MapChange(
+ state.entityReference(), state.entityDescriptor(),
+ version, version, lastModified
+ );
+ try( Writer writer = changer.updateEntity( changeInfo ) )
{
- writeEntityState( state, writer, state.version(), state.lastModified() );
+ writeEntityState( state, writer, version, lastModified );
}
}
- }
- } );
+ } );
migratedEntities.clear();
}
- catch( IOException ex )
+ catch( EntityStoreException ex )
+ {
+ throw ex;
+ }
+ catch( Exception ex )
{
throw new EntityStoreException( "Synchronization of Migrated Entities failed.", ex );
}
@@ -367,20 +392,18 @@ public class JSONMapEntityStoreMixin
protected Identity newUnitOfWorkId()
{
- return identityGenerator.generate(EntityStore.class);
+ return identityGenerator.generate( EntityStore.class );
}
- protected void writeEntityState(JSONEntityState state, Writer writer, String version, Instant lastModified )
+ protected void writeEntityState( JSONEntityState state, Writer writer, String version, Instant lastModified )
throws EntityStoreException
{
try
{
- JSONObject jsonState = state.state();
- jsonState.put( JSONKeys.VERSION, version );
- jsonState.put( JSONKeys.MODIFIED, lastModified.toEpochMilli() );
- writer.append( jsonState.toString() );
+ state.stateCloneWithVersionAndModified( version, lastModified );
+ writer.append( state.state().toString() );
}
- catch( JSONException | IOException e )
+ catch( IOException e )
{
throw new EntityStoreException( "Could not store EntityState", e );
}
@@ -391,37 +414,38 @@ public class JSONMapEntityStoreMixin
{
try
{
- JSONObject jsonObject = new JSONObject( new JSONTokener( entityState ) );
+ JsonObject parsedState = Json.createReader( entityState ).readObject();
+ JsonObjectBuilder jsonStateBuilder = JavaxJson.toBuilder( parsedState );
EntityStatus status = EntityStatus.LOADED;
- String version = jsonObject.getString( JSONKeys.VERSION );
- Instant modified = Instant.ofEpochMilli(jsonObject.getLong( JSONKeys.MODIFIED ));
- Identity identity = new StringIdentity(jsonObject.getString( JSONKeys.IDENTITY ));
+ String version = parsedState.getString( JSONKeys.VERSION );
+ Instant modified = Instant.ofEpochMilli( parsedState.getJsonNumber( JSONKeys.MODIFIED ).longValueExact() );
+ Identity identity = new StringIdentity( parsedState.getString( JSONKeys.IDENTITY ) );
- // Check if NamedAssociation is supported
- if( !jsonObject.has( JSONKeys.NAMED_ASSOCIATIONS ) )
+ // Check if version is correct
+ JsonObject state;
+ String currentAppVersion = parsedState.getString( JSONKeys.APPLICATION_VERSION, "0.0" );
+ if( currentAppVersion.equals( application.version() ) )
{
- jsonObject.put( JSONKeys.NAMED_ASSOCIATIONS, new JSONObject() );
+ state = jsonStateBuilder.build();
}
-
- // Check if version is correct
- String currentAppVersion = jsonObject.optString( JSONKeys.APPLICATION_VERSION, "0.0" );
- if( !currentAppVersion.equals( application.version() ) )
+ else
{
if( migration != null )
{
- migration.migrate( jsonObject, application.version(), this );
+ state = migration.migrate( jsonStateBuilder.build(), application.version(), this );
}
else
{
// Do nothing - set version to be correct
- jsonObject.put( JSONKeys.APPLICATION_VERSION, application.version() );
+ jsonStateBuilder.add( JSONKeys.APPLICATION_VERSION, application.version() );
+ state = jsonStateBuilder.build();
}
// State changed
status = EntityStatus.UPDATED;
}
- String type = jsonObject.getString( JSONKeys.TYPE );
+ String type = state.getString( JSONKeys.TYPE );
EntityDescriptor entityDescriptor = module.entityDescriptor( type );
if( entityDescriptor == null )
@@ -429,33 +453,40 @@ public class JSONMapEntityStoreMixin
throw new NoSuchEntityTypeException( type, module.name(), module.typeLookup() );
}
- return new JSONEntityState( module,
- valueSerialization,
- version,
- modified,
+ return new JSONEntityState( module, serialization,
+ version, modified,
EntityReference.create( identity ),
- status,
- entityDescriptor,
- jsonObject
+ status, entityDescriptor,
+ state
);
}
- catch( JSONException e )
+ catch( EntityStoreException ex )
{
- throw new EntityStoreException( e );
+ throw ex;
+ }
+ catch( Exception ex )
+ {
+ throw new EntityStoreException( ex );
}
}
@Override
- public JSONObject jsonStateOf( String id )
- throws IOException
+ public JsonObject jsonStateOf( String id )
{
- try (Reader reader = mapEntityStore.get( EntityReference.parseEntityReference( id ) ))
+ try( Reader reader = mapEntityStore.get( EntityReference.parseEntityReference( id ) ) )
+ {
+ try( JsonReader jsonReader = Json.createReader( reader ) )
+ {
+ return jsonReader.readObject();
+ }
+ }
+ catch( EntityStoreException ex )
{
- return new JSONObject( new JSONTokener( reader ) );
+ throw ex;
}
- catch( JSONException e )
+ catch( Exception ex )
{
- throw new IOException( e );
+ throw new EntityStoreException( ex );
}
}
@@ -464,15 +495,20 @@ public class JSONMapEntityStoreMixin
CacheState cacheState = cache.get( reference.identity().toString() );
if( cacheState != null )
{
- JSONObject data = cacheState.json;
+ JsonObject data = cacheState.json;
try
{
String type = data.getString( JSONKeys.TYPE );
EntityDescriptor entityDescriptor = module.entityDescriptor( type );
- Instant lastModified = Instant.ofEpochMilli(data.getLong(JSONKeys.MODIFIED));
- return new JSONEntityState( module, valueSerialization, data.getString( JSONKeys.VERSION ), lastModified, reference, EntityStatus.LOADED, entityDescriptor, data );
+ String version = data.getString( JSONKeys.VERSION );
+ Instant lastModified = Instant.ofEpochMilli( data.getJsonNumber( JSONKeys.MODIFIED ).longValueExact() );
+ return new JSONEntityState( module, serialization,
+ version, lastModified,
+ reference,
+ EntityStatus.LOADED, entityDescriptor,
+ data );
}
- catch( JSONException e )
+ catch( Exception e )
{
// Should not be able to happen, unless internal error in the cache system.
throw new EntityStoreException( e );
@@ -490,13 +526,13 @@ public class JSONMapEntityStoreMixin
public static class CacheState
implements Externalizable
{
- public JSONObject json;
+ public JsonObject json;
public CacheState()
{
}
- private CacheState( JSONObject state )
+ private CacheState( JsonObject state )
{
json = state;
}
@@ -512,14 +548,7 @@ public class JSONMapEntityStoreMixin
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException
{
- try
- {
- json = new JSONObject( in.readUTF() );
- }
- catch( JSONException e )
- {
- throw new IOException( e );
- }
+ json = Json.createReader( new StringReader( in.readUTF() ) ).readObject();
}
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONNamedAssociationState.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONNamedAssociationState.java b/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONNamedAssociationState.java
index d37bb9c..74ea667 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONNamedAssociationState.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/JSONNamedAssociationState.java
@@ -19,42 +19,56 @@
*/
package org.apache.polygene.spi.entitystore.helpers;
+import java.util.ArrayList;
import java.util.Iterator;
+import java.util.List;
import java.util.NoSuchElementException;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.Json;
+import javax.json.JsonException;
+import javax.json.JsonObject;
+import javax.json.JsonValue;
import org.apache.polygene.api.entity.EntityReference;
import org.apache.polygene.spi.entity.NamedAssociationState;
import org.apache.polygene.spi.entitystore.EntityStoreException;
/**
* JSON implementation of NamedAssociationState.
- * <p>Backed by a JSONObject.</p>
+ * <p>Backed by a JsonObject.</p>
*/
public final class JSONNamedAssociationState
implements NamedAssociationState
{
private final JSONEntityState entityState;
- private final JSONObject references;
+ private final String stateName;
- public JSONNamedAssociationState( JSONEntityState entityState, JSONObject references )
+ /* package */ JSONNamedAssociationState( JSONEntityState entityState, String stateName )
{
this.entityState = entityState;
- this.references = references;
+ this.stateName = stateName;
+ }
+
+ private JsonObject getReferences()
+ {
+ JsonObject namedAssociations = entityState.state().getJsonObject( JSONKeys.NAMED_ASSOCIATIONS );
+ JsonValue references = namedAssociations.get( stateName );
+ if( references != null && references.getValueType() == JsonValue.ValueType.OBJECT )
+ {
+ return (JsonObject) references;
+ }
+ return Json.createObjectBuilder().build();
}
@Override
public int count()
{
- return references.length();
+ return getReferences().size();
}
@Override
public boolean containsName( String name )
{
- return references.has( name );
+ return getReferences().containsKey( name );
}
@Override
@@ -62,16 +76,16 @@ public final class JSONNamedAssociationState
{
try
{
- if( references.has( name ) && entityReference.identity().toString().equals( references.getString( name ) ) )
+ if( containsName( name )
+ && entityReference.identity().toString().equals( getReferences().getString( name ) ) )
{
return false;
}
- entityState.cloneStateIfGlobalStateLoaded();
- references.put( name, entityReference.identity().toString() );
+ entityState.stateCloneAddNamedAssociation( stateName, name, entityReference );
entityState.markUpdated();
return true;
}
- catch( JSONException ex )
+ catch( JsonException ex )
{
throw new EntityStoreException( ex );
}
@@ -80,12 +94,11 @@ public final class JSONNamedAssociationState
@Override
public boolean remove( String name )
{
- if( !references.has( name ) )
+ if( !containsName( name ) )
{
return false;
}
- entityState.cloneStateIfGlobalStateLoaded();
- references.remove( name );
+ entityState.stateCloneRemoveNamedAssociation( stateName, name );
entityState.markUpdated();
return true;
}
@@ -93,29 +106,18 @@ public final class JSONNamedAssociationState
@Override
public EntityReference get( String name )
{
- try
- {
- return EntityReference.parseEntityReference( references.getString( name ) );
- }
- catch( JSONException ex )
- {
- return null;
- }
+ String stringRef = getReferences().getString( name, null );
+ return stringRef == null ? null : EntityReference.parseEntityReference( stringRef );
}
@Override
public String nameOf( EntityReference entityReference )
{
- JSONArray names = references.names();
- if( names == null )
- {
- return null;
- }
try
{
- for( int idx = 0; idx < names.length(); idx++ )
+ JsonObject references = getReferences();
+ for( String name : references.keySet() )
{
- String name = names.getString( idx );
if( entityReference.identity().toString().equals( references.getString( name ) ) )
{
return name;
@@ -123,7 +125,7 @@ public final class JSONNamedAssociationState
}
return null;
}
- catch( JSONException ex )
+ catch( JsonException ex )
{
throw new EntityStoreException( ex );
}
@@ -132,7 +134,7 @@ public final class JSONNamedAssociationState
@Override
public Iterator<String> iterator()
{
- final JSONArray names = references.names() == null ? new JSONArray() : references.names();
+ List<String> names = new ArrayList<>( getReferences().keySet() );
return new Iterator<String>()
{
private int idx = 0;
@@ -140,7 +142,7 @@ public final class JSONNamedAssociationState
@Override
public boolean hasNext()
{
- return idx < names.length();
+ return idx < names.size();
}
@Override
@@ -148,11 +150,11 @@ public final class JSONNamedAssociationState
{
try
{
- String next = names.getString( idx );
+ String next = names.get( idx );
idx++;
return next;
}
- catch( JSONException ex )
+ catch( JsonException ex )
{
throw new NoSuchElementException();
}
@@ -169,7 +171,6 @@ public final class JSONNamedAssociationState
@Override
public String toString()
{
- return references.toString();
+ return getReferences().toString();
}
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/MapEntityStore.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/MapEntityStore.java b/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/MapEntityStore.java
index a8ff1c9..901c2c1 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/MapEntityStore.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/MapEntityStore.java
@@ -22,48 +22,41 @@ package org.apache.polygene.spi.entitystore.helpers;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
+import java.time.Instant;
import java.util.stream.Stream;
import org.apache.polygene.api.entity.EntityDescriptor;
import org.apache.polygene.api.entity.EntityReference;
-import org.apache.polygene.spi.entitystore.EntityNotFoundException;
-import org.apache.polygene.spi.entitystore.EntityStoreException;
/**
* MapEntityStore.
*/
public interface MapEntityStore
{
-
/**
* @param entityReference The reference to the entity that we want to get.
* @return Entity state Reader
*/
- Reader get( EntityReference entityReference )
- throws EntityStoreException;
+ Reader get( EntityReference entityReference ) throws Exception;
/**
* @return All entities state Readers, must be closed
*/
- Stream<Reader> entityStates();
+ Stream<Reader> entityStates() throws Exception;
- void applyChanges( MapChanges changes )
- throws IOException;
+ void applyChanges( MapChanges changes ) throws Exception;
/**
* Changes to be applied on a MapEntityStore.
*/
interface MapChanges
{
-
/**
* Visitable MapChanges.
*
* @param changer Map changer
* @throws IOException on error
*/
- void visitMap( MapChanger changer )
- throws IOException;
-
+ void visitMap( MapChanger changer ) throws Exception;
}
/**
@@ -71,16 +64,65 @@ public interface MapEntityStore
*/
interface MapChanger
{
-
Writer newEntity( EntityReference ref, EntityDescriptor entityDescriptor )
- throws IOException;
+ throws Exception;
- Writer updateEntity( EntityReference ref, EntityDescriptor entityDescriptor )
- throws IOException;
+ Writer updateEntity( MapChange mapChange ) throws Exception;
void removeEntity( EntityReference ref, EntityDescriptor entityDescriptor )
- throws EntityNotFoundException;
-
+ throws Exception;
}
+ /**
+ * MapEntityStore change meta info.
+ *
+ * Implementations backed by a shared store can make use of this for e.g. optimistic locking.
+ */
+ class MapChange
+ {
+ private final EntityReference reference;
+ private final EntityDescriptor descriptor;
+ private final String previousVersion;
+ private final String newVersion;
+ private final Instant lastModified;
+
+ public MapChange( EntityReference reference, EntityDescriptor descriptor,
+ String previousVersion, String newVersion,
+ Instant lastModified )
+ {
+ this.reference = reference;
+ this.descriptor = descriptor;
+ this.previousVersion = previousVersion;
+ this.newVersion = newVersion;
+ this.lastModified = lastModified;
+ }
+
+ public EntityReference reference()
+ {
+ return reference;
+ }
+
+ public EntityDescriptor descriptor()
+ {
+ return descriptor;
+ }
+
+ /**
+ * @return null if the change is an insertion
+ */
+ public String previousVersion()
+ {
+ return previousVersion;
+ }
+
+ public String newVersion()
+ {
+ return newVersion;
+ }
+
+ public Instant lastModified()
+ {
+ return lastModified;
+ }
+ }
}
[07/50] [abbrv] polygene-java git commit: Add a basic automated test
for the yeoman generator
Posted by pa...@apache.org.
Add a basic automated test for the yeoman generator
npm based only
follows yeoman doc: http://yeoman.io/authoring/testing.html
to run the test:
cd tools/generator
npm install
npm test
The test generates an application and run ./gradlew build in it
It currently fails with a compilation error
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/a2736a6d
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/a2736a6d
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/a2736a6d
Branch: refs/heads/serialization-3.0
Commit: a2736a6dffd1b67ba940b22ec4cc531e2119a707
Parents: 0c7ee19
Author: Paul Merlin <pa...@apache.org>
Authored: Sat Mar 11 11:42:37 2017 +0100
Committer: Paul Merlin <pa...@apache.org>
Committed: Sat Mar 11 11:42:37 2017 +0100
----------------------------------------------------------------------
.../templates/DomainLayer/DomainModule/module.js | 2 +-
tools/generator-polygene/package.json | 10 ++++++++++
tools/generator-polygene/test/generator_test.js | 19 +++++++++++++++++++
3 files changed, 30 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a2736a6d/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js
index 3aea91c..0c6f1eb 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js
@@ -1,7 +1,7 @@
module.exports = {
write: function (p) {
-
+ if(!p.modules) return;
Object.keys(p.modules).forEach(function (moduleName, index) {
copyPolygeneDomainModule(p, moduleName, p.modules[moduleName])
});
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a2736a6d/tools/generator-polygene/package.json
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/package.json b/tools/generator-polygene/package.json
index 25e2d02..d410b9e 100644
--- a/tools/generator-polygene/package.json
+++ b/tools/generator-polygene/package.json
@@ -2,6 +2,9 @@
"name": "generator-polygene",
"version": "0.1.0",
"description": "",
+ "scripts": {
+ "test": "./node_modules/mocha/bin/mocha test/**/*_test.js"
+ },
"files": [
"app"
],
@@ -10,5 +13,12 @@
],
"dependencies": {
"yeoman-generator": "^0.24.1"
+ },
+ "devDependencies": {
+ "mocha": "3.2.0",
+ "path": "0.12.7",
+ "shelljs": "0.7.7",
+ "yeoman-assert": "3.0.0",
+ "yeoman-test": "1.6.0"
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a2736a6d/tools/generator-polygene/test/generator_test.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/test/generator_test.js b/tools/generator-polygene/test/generator_test.js
new file mode 100644
index 0000000..0e8ef8b
--- /dev/null
+++ b/tools/generator-polygene/test/generator_test.js
@@ -0,0 +1,19 @@
+var path = require('path');
+var helpers = require('yeoman-test');
+var assert = require('yeoman-assert');
+var shell = require('shelljs');
+
+// See http://yeoman.io/authoring/testing.html
+describe('polygene-generator', function () {
+ it('generates a buildable gradle project', function () {
+ return helpers.run(path.join(__dirname, '../app'))
+ .withPrompts({
+ name: 'test-project',
+ packageName: 'org.apache.polygene.generator.test'
+ })
+ .then(function(dir) {
+ assert.file(['gradlew', 'settings.gradle', 'build.gradle']);
+ assert(shell.exec(path.join(dir, 'gradlew') + ' build').code == 0);
+ });
+ });
+});
[50/50] [abbrv] polygene-java git commit: POLYGENE-191 Remove uneeded
Apache Johnzon dependency
Posted by pa...@apache.org.
POLYGENE-191 Remove uneeded Apache Johnzon dependency
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/afd1946b
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/afd1946b
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/afd1946b
Branch: refs/heads/serialization-3.0
Commit: afd1946b5dda236aaace9a1c0522929b6f10d210
Parents: a93e262
Author: Paul Merlin <pa...@apache.org>
Authored: Mon Feb 27 15:27:52 2017 +0100
Committer: Paul Merlin <pa...@apache.org>
Committed: Mon Mar 13 11:24:42 2017 +0100
----------------------------------------------------------------------
internals/testsupport-internal/build.gradle | 1 -
1 file changed, 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/afd1946b/internals/testsupport-internal/build.gradle
----------------------------------------------------------------------
diff --git a/internals/testsupport-internal/build.gradle b/internals/testsupport-internal/build.gradle
index 3878ee0..a38d41c 100644
--- a/internals/testsupport-internal/build.gradle
+++ b/internals/testsupport-internal/build.gradle
@@ -29,5 +29,4 @@ dependencies {
implementation libraries.docker_junit
runtimeOnly polygene.core.runtime
- runtimeOnly libraries.johnzon // TODO Quid?
}
[03/50] [abbrv] polygene-java git commit: Restructuring of the yeoman
generator,
to make it more easy to work with and demand naming in extensions to be
unified.
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/RealmService.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/RealmService.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/RealmService.tmpl
new file mode 100644
index 0000000..d009a21
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/RealmService.tmpl
@@ -0,0 +1,48 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.model.security;
+
+@Mixins( MyRealmMixin.class )
+public interface RealmService
+ extends Realm, ServiceComposite, ServiceActivation
+{
+ class Mixin
+ extends SimpleAccountRealm
+ implements ServiceActivation
+ {
+
+ private final PasswordService passwordService;
+
+ public Mixin()
+ {
+ super();
+ passwordService = new DefaultPasswordService();
+ PasswordMatcher matcher = new PasswordMatcher();
+ matcher.setPasswordService( passwordService );
+ setCredentialsMatcher( matcher );
+ }
+
+ public void activateService()
+ throws Exception
+ {
+ // Create a test account
+ addAccount( "foo", passwordService.encryptPassword( "bar" ) );
+ }
+ }
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/SecurityRepository.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/SecurityRepository.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/SecurityRepository.tmpl
new file mode 100644
index 0000000..5910c7c
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/SecurityRepository.tmpl
@@ -0,0 +1,63 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.model.security;
+
+import java.util.List;
+import org.apache.polygene.api.concern.Concerns;
+import org.apache.polygene.api.identity.Identity;
+import org.apache.polygene.api.identity.StringIdentity;
+import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
+import org.apache.polygene.api.unitofwork.concern.UnitOfWorkConcern;
+import org.apache.polygene.api.unitofwork.concern.UnitOfWorkPropagation;
+
+@Concerns( UnitOfWorkConcern.class )
+@Mixins( { SecurityRepository.EntiyStoreBackedMixin.class } )
+public interface SecurityRepository
+{
+ @UnitOfWorkPropagation
+ boolean verifyPassword( String user, String password );
+
+ @UnitOfWorkPropagation
+ List<String> findRoleNamesOfUser( String name );
+
+
+ class EntityStoreBackedSecurityRepositoryMixin
+ implements SecurityRepository
+ {
+ @Structure
+ private UnitOfWorkFactory uowf;
+
+ @Override
+ @UnitOfWorkPropagation
+ public boolean verifyPassword( String userName, String password )
+ {
+ Identity identity = new StringIdentity("User-" + userName );
+ User user = uow.currentUnitOfWork(User.class, identity );
+ return user.verify( password );
+ }
+
+ @UnitOfWorkPropagation
+ public List<String> findRoleNamesOfUser( String name )
+ {
+ }
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/User.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/User.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/User.tmpl
new file mode 100644
index 0000000..f5008cd
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/User.tmpl
@@ -0,0 +1,51 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.model.security;
+
+import org.apache.polygene.api.injection.scope.This
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.property.Property;
+
+@Mixins( { User.Mixin } )
+public interface User
+{
+
+ interface State
+ {
+ @Concerns( EncryptedStringPropertyConcern.class )
+ Property<String> password();
+
+ ManyAssociation<Group> memberOf();
+ }
+
+ class Mixin
+ implements User
+ {
+ @Service
+ private HashingService hashing;
+
+ @This
+ private State state;
+
+
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/bootstrap.tmpl
new file mode 100644
index 0000000..7513044
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/bootstrap.tmpl
@@ -0,0 +1,53 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.bootstrap.domain;
+
+import org.apache.polygene.api.common.Visibility;
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.LayerAssembly;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.bootstrap.layered.ModuleAssembler;
+import org.apache.polygene.library.shiro.assembly.StandaloneShiroAssembler;
+
+import <%= packageName %>.model.security.SecurityRepository;
+import <%= packageName %>.model.security.HardcodedSecurityRepositoryMixin;
+
+public class SecurityModule
+ implements ModuleAssembler
+{
+ public static String NAME;
+
+ @Override
+ public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
+ throws AssemblyException
+ {
+ module.services( SecurityRepository.class )
+ .withMixins( HardcodedSecurityRepositoryMixin.class )
+ .visibleIn( Visibility.application )
+ .instantiateOnStartup();
+
+ new StandaloneShiroAssembler().
+ withConfig( configModule, Visibility.layer ).
+ assemble( module );
+ module.services( RealmService.class );
+
+ return module;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/module.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/module.js b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/module.js
new file mode 100644
index 0000000..5d21aaa
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/module.js
@@ -0,0 +1,28 @@
+module.exports = {
+
+ write: function (p) {
+ if( p.hasFeature("security")) {
+
+ p.copyTemplate(p.ctx,
+ 'DomainLayer/SecurityModule/bootstrap.tmpl',
+ 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/domain/SecurityModule.java');
+
+ copyFile(p, "CryptoConfiguration");
+ copyFile(p, "CryptoException");
+ copyFile(p, "CryptoService");
+ copyFile(p, "EncryptedStringPropertyConcern");
+ copyFile(p, "EntityStoreBackedSecurityRepositoryMixin");
+ copyFile(p, "Group");
+ copyFile(p, "RealmService");
+ copyFile(p, "SecurityRepository");
+ copyFile(p, "User");
+ }
+ }
+
+};
+
+function copyFile(p, clazz) {
+ p.copyTemplate(p.ctx,
+ 'DomainLayer/SecurityModule/' + clazz + '.tmpl',
+ 'model/src/main/java/' + p.javaPackageDir + '/model/security/' + clazz + '.java');
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/bootstrap.tmpl b/tools/generator-polygene/app/templates/DomainLayer/bootstrap.tmpl
index 517942a..63401be 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/bootstrap.tmpl
@@ -31,8 +31,10 @@ public class DomainLayer extends LayeredLayerAssembler
public LayerAssembly assemble(LayerAssembly layer)
throws AssemblyException
{
- createModule( layer, CrudModule.class );
<% if( hasFeature( 'rest api' ) ) { %>
+ createModule( layer, CrudModule.class );
+<% } %>
+<% if( hasFeature( 'security' ) ) { %>
createModule( layer, SecurityModule.class );
<% } %>
return layer;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/layer.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/layer.js b/tools/generator-polygene/app/templates/DomainLayer/layer.js
new file mode 100644
index 0000000..3a32039
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/layer.js
@@ -0,0 +1,10 @@
+
+module.exports = {
+
+ write: function (p) {
+ p.copyTemplate(p.ctx,
+ 'DomainLayer/bootstrap.tmpl',
+ 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/domain/DomainLayer.java');
+ p.copyModules(__dirname );
+ }
+};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainModule/Crud.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainModule/Crud.tmpl b/tools/generator-polygene/app/templates/DomainModule/Crud.tmpl
deleted file mode 100644
index 95eed76..0000000
--- a/tools/generator-polygene/app/templates/DomainModule/Crud.tmpl
+++ /dev/null
@@ -1,41 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.model.<%= polygene.current.name %>;
-
-import org.apache.polygene.api.injection.scope.This;
-import org.apache.polygene.api.mixin.Mixins;
-import org.apache.polygene.api.property.Property;
-
-@Mixins( { <%= polygene.current.clazz.name %>.Mixin.class } )
-public interface <%= polygene.current.clazz.name %>
-{
- interface State
- {
- Property<String> name(); // Sample hidden property
- }
-
- class Mixin
- implements <%= polygene.current.clazz.name %>
- {
- @This
- private State state; // Sample reference to hidden property
-
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainModule/Entity.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainModule/Entity.tmpl b/tools/generator-polygene/app/templates/DomainModule/Entity.tmpl
deleted file mode 100644
index 9262cad..0000000
--- a/tools/generator-polygene/app/templates/DomainModule/Entity.tmpl
+++ /dev/null
@@ -1,41 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.model.<%= polygene.current.name %>;
-
-import org.apache.polygene.api.injection.scope.This
-import org.apache.polygene.api.mixin.Mixins;
-import org.apache.polygene.api.property.Property;
-
-@Mixins( { <%= polygene.current.clazz.name %>.Mixin } )
-public interface <%= polygene.current.clazz.name %>
-{
- interface State
- {
- Property<String> name(); // Sample hidden property
- }
-
- class Mixin
- implements <%= polygene.current.clazz.name %>
- {
- @This
- private State state; // Sample reference to hidden property
-
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainModule/Object.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainModule/Object.tmpl b/tools/generator-polygene/app/templates/DomainModule/Object.tmpl
deleted file mode 100644
index 27d6119..0000000
--- a/tools/generator-polygene/app/templates/DomainModule/Object.tmpl
+++ /dev/null
@@ -1,33 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.model.<%= polygene.current.name %>;
-
-import org.apache.polygene.api.injection.scope.This
-import org.apache.polygene.api.mixin.Mixins;
-
-public class <%= polygene.current.clazz.name %>
-{
- @Uses
- private String name; // Sample @Uses injection
-
- @Structure
- private ValueBuilderFactory vbf; // Sample @Structure injection
-
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainModule/Service.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainModule/Service.tmpl b/tools/generator-polygene/app/templates/DomainModule/Service.tmpl
deleted file mode 100644
index 0edefdc..0000000
--- a/tools/generator-polygene/app/templates/DomainModule/Service.tmpl
+++ /dev/null
@@ -1,36 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.model.<%= polygene.current.name %>;
-
-import org.apache.polygene.api.injection.scope.Structure;
-import org.apache.polygene.api.mixin.Mixins;
-import org.apache.polygene.api.value.ValueBuilderFactory;
-
-@Mixins( { <%= polygene.current.clazz.name %>.Mixin.class } )
-public interface <%= polygene.current.clazz.name %>
-{
- class Mixin
- implements <%= polygene.current.clazz.name %>
- {
- @Structure
- private ValueBuilderFactory vbf;
- }
-}
-
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainModule/Value.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainModule/Value.tmpl b/tools/generator-polygene/app/templates/DomainModule/Value.tmpl
deleted file mode 100644
index 9262cad..0000000
--- a/tools/generator-polygene/app/templates/DomainModule/Value.tmpl
+++ /dev/null
@@ -1,41 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.model.<%= polygene.current.name %>;
-
-import org.apache.polygene.api.injection.scope.This
-import org.apache.polygene.api.mixin.Mixins;
-import org.apache.polygene.api.property.Property;
-
-@Mixins( { <%= polygene.current.clazz.name %>.Mixin } )
-public interface <%= polygene.current.clazz.name %>
-{
- interface State
- {
- Property<String> name(); // Sample hidden property
- }
-
- class Mixin
- implements <%= polygene.current.clazz.name %>
- {
- @This
- private State state; // Sample reference to hidden property
-
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/DomainModule/bootstrap.tmpl
deleted file mode 100644
index 54bc82d..0000000
--- a/tools/generator-polygene/app/templates/DomainModule/bootstrap.tmpl
+++ /dev/null
@@ -1,85 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.bootstrap.domain;
-
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.LayerAssembly;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.bootstrap.layered.ModuleAssembler;
-<% for( var idx in polygene.current.cruds) { %><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.cruds[idx].name + ";" %><% } %>
-<% for( var idx in polygene.current.values) { %><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.values[idx].name + ";" %><% } %>
-<% for( var idx in polygene.current.entities) { %><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.entities[idx].name + ";" %><% } %>
-<% for( var idx in polygene.current.transients) { %><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.transients[idx].name + ";" %><% } %>
-<% for( var idx in polygene.current.objects) { %><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.objects[idx].name + ";" %><% } %>
-<% for( var idx in polygene.current.services) { %><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.services[idx].name + ";" %><% } %>
-
-import static org.apache.polygene.api.common.Visibility.layer;
-import static org.apache.polygene.api.common.Visibility.application;
-
-public class <%- firstUpper(polygene.current.name) %>Module
- implements ModuleAssembler
-{
- @Override
- public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
- throws AssemblyException
- {
-<% if( polygene.current.cruds ) { %>
- <% for( var value in polygene.current.cruds ) { %>
- <% var crud1 = polygene.current.cruds[value]; %>
- module.values(<%- crud1.name + ".class" %>)<% if( crud1.visibility ) {%><%-".visibleIn(" + crud1.visibility +")"%><% } %>;
- <% } %>
- <% for( var value in polygene.current.cruds ) { %>
- <% var crud2 = polygene.current.cruds[value]; %>
- module.entities(<%= crud2.name + ".class" %>)<% if( crud2.visibility ) {%><%-".visibleIn(" + crud2.visibility +")"%><% } %>;
- <% } %>
-<% } %>
-<% if( polygene.current.values ) { %>
- <% for( var value in polygene.current.values ) { %>
- <% var v = polygene.current.current[value]; %>
- module.values(<%= v.name + ".class" %>)<% if( v.visibility ) {%><%-".visibleIn(" + v.visibility +")"%><% } %>;
- <% } %>
-<% } %>
-<% if( polygene.current.entities ) { %>
- <% for( var value in polygene.current.entities ) { %>
- <% var entity = polygene.current.entities[value]; %>
- module.values(<%= entity.name + ".class" %>)<% if( entity.visibility ) {%><%-".visibleIn(" + entity.visibility +")"%><% } %>;
- <% } %>
-<% } %>
-<% if( polygene.current.transients ) { %>
- <% for( var value in polygene.current.transients ) { %>
- <% var trans = polygene.current.transients[value]; %>
- module.values(<%= trans.name + ".class" %>)<% if( trans.visibility ) {%><%-".visibleIn(" + trans.visibility +")"%><% } %>;
- <% } %>
-<% } %>
-<% if( polygene.current.objects ) { %>
- <% for( var value in polygene.current.objects ) { %>
- <% var obj = polygene.current.objects[value]; %>
- module.values(<%= obj.name + ".class" %>)<% if( obj.visibility ) {%><%-".visibleIn(" + obj.visibility +")"%><% } %>;
- <% } %>
-<% } %>
-<% if( polygene.current.services ) { %>
- <% for( var value in polygene.current.services ) { %>
- <% var service = polygene.current.services[value]; %>
- module.values(<%= service.name + ".class" %>)<% if( service.visibility ) {%><%-".visibleIn(" + service.visibility +")"%><% } %>;
- <% } %>
-<% } %>
- return module;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/FileConfigurationModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/FileConfigurationModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/FileConfigurationModule/bootstrap.tmpl
deleted file mode 100644
index ab2ad2c..0000000
--- a/tools/generator-polygene/app/templates/FileConfigurationModule/bootstrap.tmpl
+++ /dev/null
@@ -1,41 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.bootstrap.infrastructure;
-
-import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.LayerAssembly;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.bootstrap.layered.ModuleAssembler;
-import org.apache.polygene.library.fileconfig.FileConfigurationAssembler;
-
-public class FileConfigurationModule
- implements ModuleAssembler
-{
- public static String NAME;
-
- @Override
- public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
- throws AssemblyException
- {
- new FileConfigurationAssembler().visibleIn( Visibility.layer ).assemble( module );
- return module;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/Hero.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/Hero.tmpl b/tools/generator-polygene/app/templates/Heroes/Hero.tmpl
deleted file mode 100644
index c3c7ec9..0000000
--- a/tools/generator-polygene/app/templates/Heroes/Hero.tmpl
+++ /dev/null
@@ -1,28 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.model.heroes;
-
-import org.apache.polygene.api.identity.HasIdentity;
-import org.apache.polygene.api.property.Property;
-
-public interface Hero extends HasIdentity
-{
- Property<String> name();
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/app.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/app.tmpl b/tools/generator-polygene/app/templates/Heroes/app.tmpl
deleted file mode 100644
index 10fced4..0000000
--- a/tools/generator-polygene/app/templates/Heroes/app.tmpl
+++ /dev/null
@@ -1,103 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.app;
-
-import java.lang.reflect.UndeclaredThrowableException;
-import org.apache.polygene.api.structure.Application;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.layered.LayeredApplicationAssembler;
-import org.apache.polygene.library.restlet.PolygeneRestApplication;
-import org.restlet.Context;
-import org.restlet.routing.Filter;
-import org.restlet.routing.Router;
-import org.restlet.security.Enroler;
-import org.restlet.security.Verifier;
-
-import <%= packageName %>.bootstrap.HeroesApplicationAssembler;
-import <%= packageName %>.bootstrap.connectivity.ConnectivityLayer;
-import <%= packageName %>.bootstrap.connectivity.RestApiModule;
-import <%= packageName %>.model.heroes.Hero;
-import <%= packageName %>.rest.security.SimpleEnroler;
-import <%= packageName %>.rest.security.SimpleVerifier;
-
-public class Heroes extends ZrestApplication
-{
-
- public Heroes( Context context )
- throws AssemblyException
- {
- super( context );
- }
-
- @Override
- protected void addRoutes( Router router )
- {
- addResourcePath( "heroes", Hero.class, "/" );
- }
-
- @Override
- protected LayeredApplicationAssembler createApplicationAssembler( String mode )
- throws AssemblyException
- {
- if( mode != null )
- {
- return new HeroesApplicationAssembler( Application.Mode.valueOf( mode ) );
- }
- return new HeroesApplicationAssembler( Application.Mode.production );
- }
-
- @Override
- protected Verifier createVerifier()
- {
- return newObject( SimpleVerifier.class );
- }
-
- @Override
- protected Enroler createEnroler()
- {
- return newObject( SimpleEnroler.class, this );
- }
-
- @Override
- protected String getConnectivityLayer()
- {
- return ConnectivityLayer.NAME;
- }
-
- @Override
- protected String getConnectivityModule()
- {
- return RestApiModule.NAME;
- }
-
- private <T> T newObject( Class<T> type, Object... uses )
- {
- try
- {
- T instamce = type.newInstance();
- objectFactory.injectTo( instamce, uses );
- return instamce;
- }
- catch( Exception e )
- {
- throw new UndeclaredThrowableException( e );
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/bootstrap.tmpl b/tools/generator-polygene/app/templates/Heroes/bootstrap.tmpl
deleted file mode 100644
index f8bf77e..0000000
--- a/tools/generator-polygene/app/templates/Heroes/bootstrap.tmpl
+++ /dev/null
@@ -1,63 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.bootstrap;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-
-import org.apache.polygene.bootstrap.ApplicationAssembly;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.LayerAssembly;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.bootstrap.layered.LayeredApplicationAssembler;
-
-import <%= packageName %>.bootstrap.connectivity.ConnectivityLayer;
-import <%= packageName %>.bootstrap.domain.DomainLayer;
-import <%= packageName %>.bootstrap.config.ConfigurationLayer;
-import <%= packageName %>.bootstrap.infrastructure.InfrastructureLayer;
-
-public class HeroesApplicationAssembler extends LayeredApplicationAssembler
-{
- private static final String NAME = "Heroes";
- private static final String VERSION = "1.0.alpha";
-
- public HeroesApplicationAssembler( Application.Mode mode )
- throws AssemblyException
- {
- super( NAME, VERSION, mode );
- }
-
- @Override
- protected void assembleLayers( ApplicationAssembly assembly )
- throws AssemblyException
- {
- LayerAssembly configLayer = createLayer( ConfigurationLayer.class );
- ModuleAssembly configModule = assemblerOf( ConfigurationLayer.class ).configModule();
- LayerAssembly domainLayer = createLayer( DomainLayer.class );
- LayerAssembly infraLayer = new InfrastructureLayer( configModule ).assemble( assembly.layer( InfrastructureLayer.NAME ) );
- LayerAssembly connectivityLayer = createLayer( ConnectivityLayer.class );
- connectivityLayer.uses( domainLayer );
- domainLayer.uses( infraLayer );
- infraLayer.uses( configLayer );
- }
-}
-
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/web.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/web.tmpl b/tools/generator-polygene/app/templates/Heroes/web.tmpl
deleted file mode 100644
index dda4f37..0000000
--- a/tools/generator-polygene/app/templates/Heroes/web.tmpl
+++ /dev/null
@@ -1,54 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<%#
- ~ Licensed to the Apache Software Foundation (ASF) under one
- ~ or more contributor license agreements. See the NOTICE file
- ~ distributed with this work for additional information
- ~ regarding copyright ownership. The ASF licenses this file
- ~ to you under the Apache License, Version 2.0 (the
- ~ "License"); you may not use this file except in compliance
- ~ with the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- ~
- ~
-%>
-<web-app xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
- version="2.5">
-
- <display-name><%= polygene.name %></display-name>
-
-
- <servlet>
- <servlet-name>Restlet</servlet-name>
- <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class>
- <init-param>
- <param-name>org.apache.polygene.runtime.mode</param-name>
- <param-value>development</param-value>
- </init-param>
- <init-param>
- <!-- Application class name -->
- <param-name>org.restlet.application</param-name>
- <param-value><%= packageName %>.app.Heroes</param-value>
- </init-param>
- <init-param>
- <!-- Protocols to be bound to-->
- <param-name>org.restlet.clients</param-name>
- <param-value>HTTP HTTPS</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>Restlet</servlet-name>
- <url-pattern>/api/1/*</url-pattern>
- </servlet-mapping>
-
-</web-app>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/app.component.css
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/app.component.css b/tools/generator-polygene/app/templates/Heroes/webapp/app/app.component.css
deleted file mode 100644
index cb651f5..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/app.component.css
+++ /dev/null
@@ -1,34 +0,0 @@
-nav a {
- padding: 5px 10px;
- text-decoration: none;
- margin-top: 10px;
- display: inline-block;
- background-color: #eee;
- border-radius: 4px;
-}
-nav a:visited, a:link {
- color: #607D8B;
-}
-nav a:hover {
- color: #039be5;
- background-color: #CFD8DC;
-}
-nav a.router-link-active {
- color: #039be5;
-}
-h1 {
- font-size: 1.2em;
- color: #999;
- margin-bottom: 0;
-}
-h2 {
- font-size: 2em;
- margin-top: 0;
- padding-top: 0;
-}
-
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/app.component.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/app.component.js b/tools/generator-polygene/app/templates/Heroes/webapp/app/app.component.js
deleted file mode 100644
index 18aeea4..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/app.component.js
+++ /dev/null
@@ -1,41 +0,0 @@
-"use strict";
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var core_1 = require('angular2/core');
-var router_1 = require('angular2/router');
-var heroes_component_1 = require('./heroes.component');
-var hero_detail_component_1 = require('./hero-detail.component');
-var dashboard_component_1 = require('./dashboard.component');
-var hero_service_1 = require('./hero.service');
-var AppComponent = (function () {
- function AppComponent() {
- this.title = 'Tour of Heroes';
- }
- AppComponent = __decorate([
- core_1.Component({
- selector: 'my-app',
- template: "\n <h1>{{title}}</h1>\n <nav>\n <a [routerLink]=\"['Dashboard']\">Dashboard</a>\n <a [routerLink]=\"['Heroes']\">Heroes</a>\n </nav>\n <router-outlet></router-outlet>\n ",
- styleUrls: ['app/app.component.css'],
- directives: [router_1.ROUTER_DIRECTIVES],
- providers: [hero_service_1.HeroService]
- }),
- router_1.RouteConfig([
- // {path: '/', redirectTo: ['Dashboard'] },
- { path: '/dashboard', name: 'Dashboard', component: dashboard_component_1.DashboardComponent, useAsDefault: true },
- { path: '/heroes', name: 'Heroes', component: heroes_component_1.HeroesComponent },
- { path: '/detail/:id', name: 'HeroDetail', component: hero_detail_component_1.HeroDetailComponent }
- ])
- ], AppComponent);
- return AppComponent;
-}());
-exports.AppComponent = AppComponent;
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
-//# sourceMappingURL=app.component.js.map
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/app.component.js.map
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/app.component.js.map b/tools/generator-polygene/app/templates/Heroes/webapp/app/app.component.js.map
deleted file mode 100644
index bade57d..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/app.component.js.map
+++ /dev/null
@@ -1 +0,0 @@
-{"version":3,"file":"app.component.js","sourceRoot":"","sources":["app.component.ts"],"names":[],"mappings":";;;;;;;AAAA,qBAAwB,eAAe,CAAC,CAAA;AACxC,uBAA6C,iBAAiB,CAAC,CAAA;AAC/D,iCAA8B,oBAAoB,CAAC,CAAA;AACnD,sCAAkC,yBAAyB,CAAC,CAAA;AAC5D,oCAAiC,uBAAuB,CAAC,CAAA;AACzD,6BAA0B,gBAAgB,CAAC,CAAA;AAsB3C;IAAA;QACE,UAAK,GAAG,gBAAgB,CAAC;IAC3B,CAAC;IAtBD;QAAC,gBAAS,CAAC;YACT,QAAQ,EAAE,QAAQ;YAClB,QAAQ,EAAE,kMAOT;YACD,SAAS,EAAE,CAAC,uBAAuB,CAAC;YACpC,UAAU,EAAE,CAAC,0BAAiB,CAAC;YAC/B,SAAS,EAAE,CAAC,0BAAW,CAAC;SACzB,CAAC;QACD,oBAAW,CAAC;YACX,2CAA2C;YAC3C,EAAC,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,WAAW,EAAE,SAAS,EAAE,wCAAkB,EAAE,YAAY,EAAE,IAAI,EAAC;YAC1F,EAAC,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,QAAQ,EAAE,SAAS,EAAE,kCAAe,EAAC;YAC7D,EAAC,IAAI,EAAE,aAAa,EAAE,IAAI,EAAE,YAAY,EAAE,SAAS,EAAE,2CAAmB,EAAC;SAC1E,CAAC;oBAAA;IAGF,mBAAC;AAAD,CAAC,AAFD,IAEC;AAFY,oBAAY,eAExB,CAAA;AAGD;;;;EAIE"}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/app.component.ts
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/app.component.ts b/tools/generator-polygene/app/templates/Heroes/webapp/app/app.component.ts
deleted file mode 100644
index 222874b..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/app.component.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import {Component} from 'angular2/core';
-import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
-import {HeroesComponent} from './heroes.component';
-import {HeroDetailComponent} from './hero-detail.component';
-import {DashboardComponent} from './dashboard.component';
-import {HeroService} from './hero.service';
-
-@Component({
- selector: 'my-app',
- template: `
- <h1>{{title}}</h1>
- <nav>
- <a [routerLink]="['Dashboard']">Dashboard</a>
- <a [routerLink]="['Heroes']">Heroes</a>
- </nav>
- <router-outlet></router-outlet>
- `,
- styleUrls: ['app/app.component.css'],
- directives: [ROUTER_DIRECTIVES],
- providers: [HeroService]
-})
-@RouteConfig([
- // {path: '/', redirectTo: ['Dashboard'] },
- {path: '/dashboard', name: 'Dashboard', component: DashboardComponent, useAsDefault: true},
- {path: '/heroes', name: 'Heroes', component: HeroesComponent},
- {path: '/detail/:id', name: 'HeroDetail', component: HeroDetailComponent}
-])
-export class AppComponent {
- title = 'Tour of Heroes';
-}
-
-
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.css
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.css b/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.css
deleted file mode 100644
index b9d3215..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.css
+++ /dev/null
@@ -1,67 +0,0 @@
-[class*='col-'] {
- float: left;
-}
-*, *:after, *:before {
- -webkit-box-sizing: border-box;
- -moz-box-sizing: border-box;
- box-sizing: border-box;
-}
-h3 {
- text-align: center; margin-bottom: 0;
-}
-[class*='col-'] {
- padding-right: 20px;
- padding-bottom: 20px;
-}
-[class*='col-']:last-of-type {
- padding-right: 0;
-}
-.grid {
- margin: 0;
-}
-.col-1-4 {
- width: 25%;
-}
-.module {
- padding: 20px;
- text-align: center;
- color: #eee;
- max-height: 120px;
- min-width: 120px;
- background-color: #607D8B;
- border-radius: 2px;
-}
-h4 {
- position: relative;
-}
-.module:hover {
- background-color: #EEE;
- cursor: pointer;
- color: #607d8b;
-}
-.grid-pad {
- padding: 10px 0;
-}
-.grid-pad > [class*='col-']:last-of-type {
- padding-right: 20px;
-}
-@media (max-width: 600px) {
- .module {
- font-size: 10px;
- max-height: 75px; }
-}
-@media (max-width: 1024px) {
- .grid {
- margin: 0;
- }
- .module {
- min-width: 60px;
- }
-}
-
-
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.html
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.html b/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.html
deleted file mode 100644
index 3fc7517..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<h3>Top Heroes</h3>
-<div class="grid grid-pad">
- <div *ngFor="#hero of heroes" class="col-1-4" (click)="gotoDetail(hero)">
- <div class="module hero">
- <h4>{{hero.name}}</h4>
- </div>
- </div>
-</div>
-
-
-<!--
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
--->
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.js b/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.js
deleted file mode 100644
index 9c69780..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.js
+++ /dev/null
@@ -1,38 +0,0 @@
-"use strict";
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var core_1 = require('angular2/core');
-var DashboardComponent = (function () {
- function DashboardComponent(_heroService, _router) {
- this._heroService = _heroService;
- this._router = _router;
- this.heroes = [];
- }
- DashboardComponent.prototype.ngOnInit = function () {
- var _this = this;
- this._heroService.getHeroes().then(function (heroes) { return _this.heroes = heroes.slice(1, 5); });
- };
- DashboardComponent.prototype.gotoDetail = function (hero) {
- var link = ['HeroDetail', { id: hero.id }];
- this._router.navigate(link);
- };
- DashboardComponent = __decorate([
- core_1.Component({
- selector: 'my-dashboard',
- templateUrl: 'app/dashboard.component.html',
- styleUrls: ['app/dashboard.component.css']
- })
- ], DashboardComponent);
- return DashboardComponent;
-}());
-exports.DashboardComponent = DashboardComponent;
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
-//# sourceMappingURL=dashboard.component.js.map
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.js.map
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.js.map b/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.js.map
deleted file mode 100644
index 5bc16f0..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.js.map
+++ /dev/null
@@ -1 +0,0 @@
-{"version":3,"file":"dashboard.component.js","sourceRoot":"","sources":["dashboard.component.ts"],"names":[],"mappings":";;;;;;;AAAA,qBAAgC,eAAe,CAAC,CAAA;AAUhD;IAGE,4BAAoB,YAAyB,EAAU,OAAe;QAAlD,iBAAY,GAAZ,YAAY,CAAa;QAAU,YAAO,GAAP,OAAO,CAAQ;QAFtE,WAAM,GAAW,EAAE,CAAC;IAEsD,CAAC;IAE3E,qCAAQ,GAAR;QAAA,iBAEC;QADC,IAAI,CAAC,YAAY,CAAC,SAAS,EAAE,CAAC,IAAI,CAAC,UAAA,MAAM,IAAI,OAAA,KAAI,CAAC,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAC,CAAC,CAAC,EAA/B,CAA+B,CAAC,CAAC;IAChF,CAAC;IAED,uCAAU,GAAV,UAAW,IAAU;QACnB,IAAI,IAAI,GAAG,CAAC,YAAY,EAAE,EAAE,EAAE,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,CAAC;QAC3C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC;IAjBH;QAAC,gBAAS,CAAC;YACT,QAAQ,EAAE,cAAc;YACxB,WAAW,EAAE,8BAA8B;YAC3C,SAAS,EAAE,CAAC,6BAA6B,CAAC;SAC3C,CAAC;0BAAA;IAcF,yBAAC;AAAD,CAAC,AAbD,IAaC;AAbY,0BAAkB,qBAa9B,CAAA;AAGD;;;;EAIE"}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.ts
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.ts b/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.ts
deleted file mode 100644
index c8160d1..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/dashboard.component.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import {Component, OnInit} from 'angular2/core';
-import {Router} from 'angular2/router';
-import {Hero} from './hero';
-import {HeroService} from './hero.service';
-
-@Component({
- selector: 'my-dashboard',
- templateUrl: 'app/dashboard.component.html',
- styleUrls: ['app/dashboard.component.css']
-})
-export class DashboardComponent implements OnInit {
- heroes: Hero[] = [];
-
- constructor(private _heroService: HeroService, private _router: Router) { }
-
- ngOnInit() {
- this._heroService.getHeroes().then(heroes => this.heroes = heroes.slice(1,5));
- }
-
- gotoDetail(hero: Hero) {
- let link = ['HeroDetail', { id: hero.id }];
- this._router.navigate(link);
- }
-}
-
-
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.css
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.css b/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.css
deleted file mode 100644
index 2a0e285..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.css
+++ /dev/null
@@ -1,36 +0,0 @@
-label {
- display: inline-block;
- width: 3em;
- margin: .5em 0;
- color: #607D8B;
- font-weight: bold;
-}
-input {
- height: 2em;
- font-size: 1em;
- padding-left: .4em;
-}
-button {
- margin-top: 20px;
- font-family: Arial;
- background-color: #eee;
- border: none;
- padding: 5px 10px;
- border-radius: 4px;
- cursor: pointer; cursor: hand;
-}
-button:hover {
- background-color: #cfd8dc;
-}
-button:disabled {
- background-color: #eee;
- color: #ccc;
- cursor: auto;
-}
-
-
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.html
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.html b/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.html
deleted file mode 100644
index 1e85e75..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<div *ngIf="hero">
- <h2>{{hero.name}} details!</h2>
- <div>
- <label>id: </label>{{hero.id}}</div>
- <div>
- <label>name: </label>
- <input [(ngModel)]="hero.name" placeholder="name"/>
- </div>
- <button (click)="goBack()">Back</button>
-</div>
-
-<!--
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
--->
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.js b/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.js
deleted file mode 100644
index 56d5fa5..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.js
+++ /dev/null
@@ -1,37 +0,0 @@
-"use strict";
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var core_1 = require('angular2/core');
-var HeroDetailComponent = (function () {
- function HeroDetailComponent(_heroService, _routeParams) {
- this._heroService = _heroService;
- this._routeParams = _routeParams;
- }
- HeroDetailComponent.prototype.ngOnInit = function () {
- var _this = this;
- var id = +this._routeParams.get('id');
- this._heroService.getHero(id).then(function (hero) { return _this.hero = hero; });
- };
- HeroDetailComponent.prototype.goBack = function () {
- window.history.back();
- };
- HeroDetailComponent = __decorate([
- core_1.Component({
- selector: 'my-hero-detail',
- templateUrl: 'app/hero-detail.component.html',
- styleUrls: ['app/hero-detail.component.css']
- })
- ], HeroDetailComponent);
- return HeroDetailComponent;
-}());
-exports.HeroDetailComponent = HeroDetailComponent;
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
-//# sourceMappingURL=hero-detail.component.js.map
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.js.map
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.js.map b/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.js.map
deleted file mode 100644
index 3928563..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.js.map
+++ /dev/null
@@ -1 +0,0 @@
-{"version":3,"file":"hero-detail.component.js","sourceRoot":"","sources":["hero-detail.component.ts"],"names":[],"mappings":";;;;;;;AAAA,qBAAgC,eAAe,CAAC,CAAA;AAWhD;IAGE,6BAAoB,YAAyB,EACnC,YAAyB;QADf,iBAAY,GAAZ,YAAY,CAAa;QACnC,iBAAY,GAAZ,YAAY,CAAa;IACnC,CAAC;IAED,sCAAQ,GAAR;QAAA,iBAGC;QAFC,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACtC,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,UAAA,IAAI,IAAI,OAAA,KAAI,CAAC,IAAI,GAAG,IAAI,EAAhB,CAAgB,CAAC,CAAC;IAC/D,CAAC;IAED,oCAAM,GAAN;QACE,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;IACxB,CAAC;IAnBH;QAAC,gBAAS,CAAC;YACT,QAAQ,EAAE,gBAAgB;YAC1B,WAAW,EAAE,gCAAgC;YAC7C,SAAS,EAAE,CAAC,+BAA+B,CAAC;SAC7C,CAAC;2BAAA;IAgBF,0BAAC;AAAD,CAAC,AAfD,IAeC;AAfY,2BAAmB,sBAe/B,CAAA;AAGD;;;;EAIE"}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.ts
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.ts b/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.ts
deleted file mode 100644
index 0181847..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero-detail.component.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import {Component, OnInit} from 'angular2/core';
-import {RouteParams} from 'angular2/router';
-
-import {Hero} from './hero';
-import {HeroService} from './hero.service';
-
-@Component({
- selector: 'my-hero-detail',
- templateUrl: 'app/hero-detail.component.html',
- styleUrls: ['app/hero-detail.component.css']
-})
-export class HeroDetailComponent implements OnInit {
- hero: Hero;
-
- constructor(private _heroService: HeroService,
- private _routeParams: RouteParams) {
- }
-
- ngOnInit() {
- let id = +this._routeParams.get('id');
- this._heroService.getHero(id).then(hero => this.hero = hero);
- }
-
- goBack() {
- window.history.back();
- }
-}
-
-
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.js b/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.js
deleted file mode 100644
index 0c6fe2e..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.js
+++ /dev/null
@@ -1,13 +0,0 @@
-"use strict";
-var Hero = (function () {
- function Hero() {
- }
- return Hero;
-}());
-exports.Hero = Hero;
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
-//# sourceMappingURL=hero.js.map
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.js.map
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.js.map b/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.js.map
deleted file mode 100644
index 4a29533..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.js.map
+++ /dev/null
@@ -1 +0,0 @@
-{"version":3,"file":"hero.js","sourceRoot":"","sources":["hero.ts"],"names":[],"mappings":";AAAA;IAAA;IAGA,CAAC;IAAD,WAAC;AAAD,CAAC,AAHD,IAGC;AAHY,YAAI,OAGhB,CAAA;AAGD;;;;EAIE"}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.service.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.service.js b/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.service.js
deleted file mode 100644
index 3f92669..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.service.js
+++ /dev/null
@@ -1,30 +0,0 @@
-"use strict";
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var core_1 = require('angular2/core');
-var mock_heroes_1 = require('./mock-heroes');
-var HeroService = (function () {
- function HeroService() {
- }
- HeroService.prototype.getHeroes = function () {
- return Promise.resolve(mock_heroes_1.HEROES);
- };
- HeroService.prototype.getHero = function (id) {
- return Promise.resolve(mock_heroes_1.HEROES).then(function (heroes) { return heroes.filter(function (hero) { return hero.id === id; })[0]; });
- };
- HeroService = __decorate([
- core_1.Injectable()
- ], HeroService);
- return HeroService;
-}());
-exports.HeroService = HeroService;
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
-//# sourceMappingURL=hero.service.js.map
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.service.js.map
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.service.js.map b/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.service.js.map
deleted file mode 100644
index 2485ba7..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.service.js.map
+++ /dev/null
@@ -1 +0,0 @@
-{"version":3,"file":"hero.service.js","sourceRoot":"","sources":["hero.service.ts"],"names":[],"mappings":";;;;;;;AAAA,qBAAyB,eAAe,CAAC,CAAA;AACzC,4BAAyB,eAAe,CAAC,CAAA;AAGzC;IAAA;IAUA,CAAC;IATC,+BAAS,GAAT;QACE,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,oBAAM,CAAC,CAAC;IACjC,CAAC;IAEF,6BAAO,GAAP,UAAQ,EAAU;QACf,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,oBAAM,CAAC,CAAC,IAAI,CACjC,UAAA,MAAM,IAAI,OAAA,MAAM,CAAC,MAAM,CAAC,UAAA,IAAI,IAAI,OAAA,IAAI,CAAC,EAAE,KAAK,EAAE,EAAd,CAAc,CAAC,CAAC,CAAC,CAAC,EAAxC,CAAwC,CACnD,CAAC;IACJ,CAAC;IAVH;QAAC,iBAAU,EAAE;mBAAA;IAWb,kBAAC;AAAD,CAAC,AAVD,IAUC;AAVY,mBAAW,cAUvB,CAAA;AAGD;;;;EAIE"}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.service.ts
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.service.ts b/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.service.ts
deleted file mode 100644
index aee78a1..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.service.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import {Injectable} from 'angular2/core';
-import {HEROES} from './mock-heroes';
-
-@Injectable()
-export class HeroService {
- getHeroes() {
- return Promise.resolve(HEROES);
- }
-
- getHero(id: number) {
- return Promise.resolve(HEROES).then(
- heroes => heroes.filter(hero => hero.id === id)[0]
- );
- }
-}
-
-
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.ts
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.ts b/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.ts
deleted file mode 100644
index 812726c..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/hero.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-export class Hero {
- id: number;
- name: string;
-}
-
-
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.css
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.css b/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.css
deleted file mode 100644
index 98e7ecc..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.css
+++ /dev/null
@@ -1,66 +0,0 @@
-.selected {
- background-color: #CFD8DC !important;
- color: white;
-}
-.heroes {
- margin: 0 0 2em 0;
- list-style-type: none;
- padding: 0;
- width: 15em;
-}
-.heroes li {
- cursor: pointer;
- position: relative;
- left: 0;
- background-color: #EEE;
- margin: .5em;
- padding: .3em 0;
- height: 1.6em;
- border-radius: 4px;
-}
-.heroes li:hover {
- color: #607D8B;
- background-color: #DDD;
- left: .1em;
-}
-.heroes li.selected:hover {
- background-color: #BBD8DC !important;
- color: white;
-}
-.heroes .text {
- position: relative;
- top: -3px;
-}
-.heroes .badge {
- display: inline-block;
- font-size: small;
- color: white;
- padding: 0.8em 0.7em 0 0.7em;
- background-color: #607D8B;
- line-height: 1em;
- position: relative;
- left: -1px;
- top: -4px;
- height: 1.8em;
- margin-right: .8em;
- border-radius: 4px 0 0 4px;
-}
-button {
- font-family: Arial;
- background-color: #eee;
- border: none;
- padding: 5px 10px;
- border-radius: 4px;
- cursor: pointer;
- cursor: hand;
-}
-button:hover {
- background-color: #cfd8dc;
-}
-
-
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.html
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.html b/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.html
deleted file mode 100644
index 0688e6a..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.html
+++ /dev/null
@@ -1,21 +0,0 @@
-<div>
- <h2>My Heroes</h2>
- <ul class="heroes">
- <li *ngFor="#hero of heroes"
- [class.selected]="hero === selectedHero"
- (click)="onSelect(hero)">
- <span class="badge">{{hero.id}}</span> {{hero.name}}
- </li>
- </ul>
- <div *ngIf="selectedHero">
- <h2>{{selectedHero.name | uppercase}} is my hero</h2>
- <button (click)="gotoDetail()">View Details</button>
- </div>
-</div>
-
-
-<!--
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
--->
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.js b/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.js
deleted file mode 100644
index a4c1363..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.js
+++ /dev/null
@@ -1,42 +0,0 @@
-"use strict";
-var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
-};
-var core_1 = require('angular2/core');
-var hero_detail_component_1 = require('./hero-detail.component');
-var HeroesComponent = (function () {
- function HeroesComponent(_heroService, _router) {
- this._heroService = _heroService;
- this._router = _router;
- }
- HeroesComponent.prototype.getHeroes = function () {
- var _this = this;
- this._heroService.getHeroes().then(function (heroes) { return _this.heroes = heroes; });
- };
- HeroesComponent.prototype.gotoDetail = function () {
- this._router.navigate(['HeroDetail', { id: this.selectedHero.id }]);
- };
- HeroesComponent.prototype.ngOnInit = function () {
- this.getHeroes();
- };
- HeroesComponent.prototype.onSelect = function (hero) { this.selectedHero = hero; };
- HeroesComponent = __decorate([
- core_1.Component({
- selector: 'my-heroes',
- templateUrl: 'app/heroes.component.html',
- styleUrls: ['app/heroes.component.css'],
- directives: [hero_detail_component_1.HeroDetailComponent]
- })
- ], HeroesComponent);
- return HeroesComponent;
-}());
-exports.HeroesComponent = HeroesComponent;
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
-//# sourceMappingURL=heroes.component.js.map
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.js.map
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.js.map b/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.js.map
deleted file mode 100644
index ca03d9d..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.js.map
+++ /dev/null
@@ -1 +0,0 @@
-{"version":3,"file":"heroes.component.js","sourceRoot":"","sources":["heroes.component.ts"],"names":[],"mappings":";;;;;;;AAAA,qBAAgC,eAAe,CAAC,CAAA;AAGhD,sCAAkC,yBAAyB,CAAC,CAAA;AAS5D;IAIE,yBAAoB,YAAyB,EAAU,OAAe;QAAlD,iBAAY,GAAZ,YAAY,CAAa;QAAU,YAAO,GAAP,OAAO,CAAQ;IAAI,CAAC;IAE3E,mCAAS,GAAT;QAAA,iBAEC;QADC,IAAI,CAAC,YAAY,CAAC,SAAS,EAAE,CAAC,IAAI,CAAC,UAAA,MAAM,IAAI,OAAA,KAAI,CAAC,MAAM,GAAG,MAAM,EAApB,CAAoB,CAAC,CAAC;IACrE,CAAC;IAED,oCAAU,GAAV;QACE,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,YAAY,EAAE,EAAE,EAAE,EAAE,IAAI,CAAC,YAAY,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;IACtE,CAAC;IAED,kCAAQ,GAAR;QACE,IAAI,CAAC,SAAS,EAAE,CAAC;IACnB,CAAC;IAED,kCAAQ,GAAR,UAAS,IAAU,IAAI,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,CAAC,CAAC;IAxBpD;QAAC,gBAAS,CAAC;YACT,QAAQ,EAAE,WAAW;YACrB,WAAW,EAAE,2BAA2B;YACxC,SAAS,EAAE,CAAC,0BAA0B,CAAC;YACvC,UAAU,EAAE,CAAC,2CAAmB,CAAC;SAClC,CAAC;uBAAA;IAoBF,sBAAC;AAAD,CAAC,AAnBD,IAmBC;AAnBY,uBAAe,kBAmB3B,CAAA;AAGD;;;;EAIE"}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.ts
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.ts b/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.ts
deleted file mode 100644
index 0002025..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/heroes.component.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import {Component, OnInit} from 'angular2/core';
-import {Router} from 'angular2/router';
-import {HeroService} from './hero.service';
-import {HeroDetailComponent} from './hero-detail.component';
-import {Hero} from './hero';
-
-@Component({
- selector: 'my-heroes',
- templateUrl: 'app/heroes.component.html',
- styleUrls: ['app/heroes.component.css'],
- directives: [HeroDetailComponent]
-})
-export class HeroesComponent implements OnInit {
- heroes: Hero[];
- selectedHero: Hero;
-
- constructor(private _heroService: HeroService, private _router: Router) { }
-
- getHeroes() {
- this._heroService.getHeroes().then(heroes => this.heroes = heroes);
- }
-
- gotoDetail() {
- this._router.navigate(['HeroDetail', { id: this.selectedHero.id }]);
- }
-
- ngOnInit() {
- this.getHeroes();
- }
-
- onSelect(hero: Hero) { this.selectedHero = hero; }
-}
-
-
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/main.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/main.js b/tools/generator-polygene/app/templates/Heroes/webapp/app/main.js
deleted file mode 100644
index 9b4c297..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/main.js
+++ /dev/null
@@ -1,15 +0,0 @@
-"use strict";
-var browser_1 = require('angular2/platform/browser');
-var router_1 = require('angular2/router');
-var hero_service_1 = require('./hero.service');
-var app_component_1 = require('./app.component');
-browser_1.bootstrap(app_component_1.AppComponent, [
- router_1.ROUTER_PROVIDERS,
- hero_service_1.HeroService
-]);
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
-//# sourceMappingURL=main.js.map
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/main.js.map
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/main.js.map b/tools/generator-polygene/app/templates/Heroes/webapp/app/main.js.map
deleted file mode 100644
index c830f42..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/main.js.map
+++ /dev/null
@@ -1 +0,0 @@
-{"version":3,"file":"main.js","sourceRoot":"","sources":["main.ts"],"names":[],"mappings":";AAAA,wBAAwB,2BAA2B,CAAC,CAAA;AACpD,uBAA+B,iBAAiB,CAAC,CAAA;AACjD,6BAA0B,gBAAgB,CAAC,CAAA;AAC3C,8BAA2B,iBAAiB,CAAC,CAAA;AAE7C,mBAAS,CAAC,4BAAY,EAAE;IACtB,yBAAgB;IAChB,0BAAW;CACZ,CAAC,CAAC;AAGH;;;;EAIE"}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/main.ts
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/main.ts b/tools/generator-polygene/app/templates/Heroes/webapp/app/main.ts
deleted file mode 100644
index 95e2d0b..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/main.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import {bootstrap} from 'angular2/platform/browser';
-import {ROUTER_PROVIDERS} from 'angular2/router';
-import {HeroService} from './hero.service';
-import {AppComponent} from './app.component';
-
-bootstrap(AppComponent, [
- ROUTER_PROVIDERS,
- HeroService
-]);
-
-
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/mock-heroes.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/mock-heroes.js b/tools/generator-polygene/app/templates/Heroes/webapp/app/mock-heroes.js
deleted file mode 100644
index 9fe1f8a..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/mock-heroes.js
+++ /dev/null
@@ -1,19 +0,0 @@
-"use strict";
-exports.HEROES = [
- { "id": 11, "name": "Mr. Nice" },
- { "id": 12, "name": "Narco" },
- { "id": 13, "name": "Bombasto" },
- { "id": 14, "name": "Celeritas" },
- { "id": 15, "name": "Magneta" },
- { "id": 16, "name": "RubberMan" },
- { "id": 17, "name": "Dynama" },
- { "id": 18, "name": "Dr IQ" },
- { "id": 19, "name": "Magma" },
- { "id": 20, "name": "Tornado" }
-];
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
-//# sourceMappingURL=mock-heroes.js.map
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/mock-heroes.js.map
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/mock-heroes.js.map b/tools/generator-polygene/app/templates/Heroes/webapp/app/mock-heroes.js.map
deleted file mode 100644
index dc81a97..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/mock-heroes.js.map
+++ /dev/null
@@ -1 +0,0 @@
-{"version":3,"file":"mock-heroes.js","sourceRoot":"","sources":["mock-heroes.ts"],"names":[],"mappings":";AAEW,cAAM,GAAW;IAC3B,EAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,UAAU,EAAC;IAC9B,EAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,OAAO,EAAC;IAC3B,EAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,UAAU,EAAC;IAC9B,EAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,WAAW,EAAC;IAC/B,EAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,SAAS,EAAC;IAC7B,EAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,WAAW,EAAC;IAC/B,EAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAC;IAC5B,EAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,OAAO,EAAC;IAC3B,EAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,OAAO,EAAC;IAC3B,EAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,SAAS,EAAC;CAC7B,CAAC;AAGF;;;;EAIE"}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/app/mock-heroes.ts
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/app/mock-heroes.ts b/tools/generator-polygene/app/templates/Heroes/webapp/app/mock-heroes.ts
deleted file mode 100644
index 673cf53..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/app/mock-heroes.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { Hero } from './hero';
-
-export var HEROES: Hero[] = [
- {"id": 11, "name": "Mr. Nice"},
- {"id": 12, "name": "Narco"},
- {"id": 13, "name": "Bombasto"},
- {"id": 14, "name": "Celeritas"},
- {"id": 15, "name": "Magneta"},
- {"id": 16, "name": "RubberMan"},
- {"id": 17, "name": "Dynama"},
- {"id": 18, "name": "Dr IQ"},
- {"id": 19, "name": "Magma"},
- {"id": 20, "name": "Tornado"}
-];
-
-
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/index.html
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/index.html b/tools/generator-polygene/app/templates/Heroes/webapp/index.html
deleted file mode 100644
index 753dd48..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/index.html
+++ /dev/null
@@ -1,41 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <script>document.write('<base href="' + document.location + '" />');</script>
- <title>Angular 2 Tour of Heroes</title>
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link rel="stylesheet" href="styles.css">
-
- <!-- IE required polyfills, in this exact order -->
- <script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.35.0/es6-shim.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.26/system-polyfills.js"></script>
- <script src="https://npmcdn.com/angular2@2.0.0-beta.15/es6/dev/src/testing/shims_for_IE.js"></script>
-
- <script src="https://code.angularjs.org/2.0.0-beta.15/angular2-polyfills.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.26/system.js"></script>
- <script src="https://npmcdn.com/typescript@1.8.10/lib/typescript.js"></script>
- <script src="https://code.angularjs.org/2.0.0-beta.15/Rx.js"></script>
- <script src="https://code.angularjs.org/2.0.0-beta.15/angular2.dev.js"></script>
- <script src="https://code.angularjs.org/2.0.0-beta.15/router.dev.js"></script>
- <script>
- System.config({
- transpiler: 'typescript',
- typescriptOptions: { emitDecoratorMetadata: true },
- packages: {'app': {defaultExtension: 'ts'}}
- });
- System.import('app/main')
- .then(null, console.error.bind(console));
- </script>
- </head>
-
- <body>
- <my-app>Loading...</my-app>
- </body>
-</html>
-
-
-<!--
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
--->
\ No newline at end of file
[16/50] [abbrv] polygene-java git commit: Cleaned up the 'security'
feature. Introduced a 'applicationtype' and starting to bind the 'Rest API'
together. Slowly getting there.
Posted by pa...@apache.org.
Cleaned up the 'security' feature. Introduced a 'applicationtype' and starting to bind the 'Rest API' together. Slowly getting there.
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/01949a6d
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/01949a6d
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/01949a6d
Branch: refs/heads/serialization-3.0
Commit: 01949a6d6625631f931def905510c0498d0e3bde
Parents: 70eeb7e
Author: niclas <ni...@spicter.com>
Authored: Sun Mar 12 20:07:56 2017 +0800
Committer: niclas <ni...@spicter.com>
Committed: Sun Mar 12 20:07:56 2017 +0800
----------------------------------------------------------------------
.../restlet/PolygeneRestApplication.java | 8 ---
.../library/shiro/domain/permissions/Role.java | 6 +-
tools/generator-polygene/app/index.js | 76 +++++++++-----------
.../ConfigModule/bootstrap.tmpl | 2 +-
.../templates/ConfigurationLayer/bootstrap.tmpl | 2 +-
.../RestApiModule/DefaultEnroler.tmpl | 6 +-
.../RestApiModule/DefaultVerifier.tmpl | 4 +-
.../RestApiModule/NullEnroler.tmpl | 2 +-
.../RestApiModule/NullVerifier.tmpl | 2 +-
.../RestApiModule/bootstrap.tmpl | 10 +--
.../ConnectivityLayer/RestApiModule/module.js | 2 +-
.../RestApiModule/web.xml.tmpl | 46 ++++++++++++
.../templates/ConnectivityLayer/bootstrap.tmpl | 4 +-
.../DomainLayer/CrudModule/bootstrap.tmpl | 2 +-
.../templates/DomainLayer/CrudModule/module.js | 8 ++-
.../DomainLayer/DomainModule/Configuration.tmpl | 2 +-
.../DomainLayer/DomainModule/Crud.tmpl | 2 +-
.../DomainLayer/DomainModule/Entity.tmpl | 2 +-
.../DomainLayer/DomainModule/Object.tmpl | 2 +-
.../DomainLayer/DomainModule/Service.tmpl | 2 +-
.../DomainLayer/DomainModule/Transient.tmpl | 2 +-
.../DomainLayer/DomainModule/Value.tmpl | 2 +-
.../DomainLayer/DomainModule/bootstrap.tmpl | 16 ++---
.../SecurityModule/CryptoConfiguration.tmpl | 7 +-
.../SecurityModule/CryptoException.tmpl | 2 +-
.../SecurityModule/CryptoService.tmpl | 33 +++++----
.../EncryptedStringPropertyConcern.tmpl | 2 +-
...ntityStoreBackedSecurityRepositoryMixin.tmpl | 60 ----------------
.../DomainLayer/SecurityModule/Group.tmpl | 23 ++----
.../SecurityModule/RealmService.tmpl | 27 +++++--
.../SecurityModule/SecurityRepository.tmpl | 24 ++++---
.../DomainLayer/SecurityModule/User.tmpl | 28 ++++----
.../DomainLayer/SecurityModule/UserFactory.tmpl | 55 ++++++++++++++
.../DomainLayer/SecurityModule/bootstrap.tmpl | 32 ++++++---
.../DomainLayer/SecurityModule/module.js | 2 +-
.../app/templates/DomainLayer/bootstrap.tmpl | 4 +-
.../CachingModule/bootstrap.tmpl | 2 +-
.../FileConfigurationModule/bootstrap.tmpl | 2 +-
.../IndexingModule/bootstrap.tmpl | 2 +-
.../MetricsModule/bootstrap.tmpl | 2 +-
.../SerializationModule/bootstrap.tmpl | 2 +-
.../StorageModule/bootstrap.tmpl | 2 +-
.../InfrastructureLayer/bootstrap.tmpl | 2 +-
.../templates/buildtool/gradle-bootstrap.tmpl | 2 +-
.../app/templates/buildtool/gradle-model.tmpl | 12 +++-
.../app/templates/buildtool/gradle-rest.tmpl | 4 +-
tools/generator-polygene/test/generator_test.js | 17 ++---
47 files changed, 305 insertions(+), 253 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/PolygeneRestApplication.java
----------------------------------------------------------------------
diff --git a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/PolygeneRestApplication.java b/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/PolygeneRestApplication.java
index 291cfba..4df326f 100644
--- a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/PolygeneRestApplication.java
+++ b/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/PolygeneRestApplication.java
@@ -152,14 +152,6 @@ public abstract class PolygeneRestApplication extends org.restlet.Application
{
guard.setEnroler( enroler );
}
-
- // In the future, look into JAAS approach.
-// Configuration jaasConfig = Configuration.getConfiguration();
-// JaasVerifier verifier = new JaasVerifier( "BasicJaasAuthenticationApplication");
-// verifier.setConfiguration( jaasConfig);
-// verifier.setUserPrincipalClassName("com.sun.security.auth.UserPrincipal");
-// guard.setVerifier(verifier);
-
return createInterceptors( guard );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/libraries/shiro-core/src/main/java/org/apache/polygene/library/shiro/domain/permissions/Role.java
----------------------------------------------------------------------
diff --git a/libraries/shiro-core/src/main/java/org/apache/polygene/library/shiro/domain/permissions/Role.java b/libraries/shiro-core/src/main/java/org/apache/polygene/library/shiro/domain/permissions/Role.java
index d111795..85c7b02 100644
--- a/libraries/shiro-core/src/main/java/org/apache/polygene/library/shiro/domain/permissions/Role.java
+++ b/libraries/shiro-core/src/main/java/org/apache/polygene/library/shiro/domain/permissions/Role.java
@@ -32,7 +32,7 @@ import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
@Mixins( Role.Mixin.class )
public interface Role
- extends EntityComposite
+ extends EntityComposite
{
Property<String> name();
@@ -42,8 +42,8 @@ public interface Role
RoleAssignment assignTo( RoleAssignee assignee );
- public abstract class Mixin
- implements Role
+ abstract class Mixin
+ implements Role
{
@Structure
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/index.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/index.js b/tools/generator-polygene/app/index.js
index 583edbf..b1a12c1 100644
--- a/tools/generator-polygene/app/index.js
+++ b/tools/generator-polygene/app/index.js
@@ -59,8 +59,8 @@ module.exports = generators.Base.extend(
polygene = importModel(this.options.import);
polygene.name = polygene.name ? polygene.name : firstUpper(this.appname);
polygene.packageName = polygene.packageName ? polygene.packageName : ("com.acme." + this.appname);
- polygene.singletonApp = false; // not supported yet
- polygene.features = polygene.features ? polygene.features : ['rest api'];
+ polygene.applicationtype = "Rest API";
+ polygene.features = polygene.features ? polygene.features : [];
polygene.modules = polygene.modules ? polygene.modules : {};
polygene.indexing = polygene.indexing ? polygene.indexing : null;
polygene.entitystore = polygene.entitystore ? polygene.entitystore : null;
@@ -91,6 +91,16 @@ module.exports = generators.Base.extend(
},
{
type: 'list',
+ name: 'applicationtype',
+ choices: [
+ 'Command Line',
+ 'Rest API'
+ ],
+ message: 'what type of application do you want to create?',
+ default: polygene.applicationtype ? polygene.applicationtype : "Rest API"
+ },
+ {
+ type: 'list',
name: 'entitystore',
choices: [
'Cassandra',
@@ -162,7 +172,6 @@ module.exports = generators.Base.extend(
type: 'checkbox',
name: 'features',
choices: [
- 'rest api'
, 'security'
// ,'version migration'
// ,'logging'
@@ -188,22 +197,22 @@ module.exports = generators.Base.extend(
this.log('Caching:', answers.caching);
this.log('Serialization:', answers.serialization);
this.log('Features:', answers.features);
- polygene.name = answers.name;
- polygene.entitystore = answers.entitystore;
- polygene.indexing = answers.indexing;
- polygene.caching = answers.caching;
- polygene.serialization = answers.serialization;
- polygene.metrics = answers.metrics;
- polygene.packageName = answers.packageName;
- polygene.features = answers.features;
- polygene.javaPackageDir = polygene.javaPackageDir ? polygene.javaPackageDir : polygene.packageName.replace(/[.]/g, '/');
- polygene.singletonApp = false;
+ polygene = answers;
+ // polygene.name = answers.name;
+ // polygene.entitystore = answers.entitystore;
+ // polygene.indexing = answers.indexing;
+ // polygene.caching = answers.caching;
+ // polygene.serialization = answers.serialization;
+ // polygene.metrics = answers.metrics;
+ // polygene.packageName = answers.packageName;
+ // polygene.features = answers.features;
}.bind(this)
);
}
},
writing: function () {
+ polygene.javaPackageDir = polygene.packageName.replace(/[.]/g, '/');
polygene.ctx = this;
fs.readdir(__dirname + "/templates", function (err, files) {
files.forEach(function (directory) {
@@ -222,23 +231,6 @@ module.exports = generators.Base.extend(
}
);
-
-function hasEntityStore(esType) {
- return polygene.entitystore === esType;
-}
-
-function hasIndexing(indexingType) {
- return polygene.indexing === indexingType;
-}
-
-function hasCaching(cachingType) {
- return polygene.caching === cachingType;
-}
-
-function hasSerialization(serializer) {
- return polygene.serialization === serializer;
-}
-
function hasFeature(feature) {
return polygene.features.indexOf(feature) >= 0;
}
@@ -248,14 +240,14 @@ function firstUpper(text) {
}
function importModel(filename) {
- if ( typeof filename !== 'string' ) {
+ if (typeof filename !== 'string') {
filename = "./model.json";
}
return JSON.parse(fs.readFileSync(filename, 'utf8'));
}
function exportModel(filename) {
- if ( typeof filename !== 'string' ) {
+ if (typeof filename !== 'string') {
filename = "exported-model.json";
}
delete polygene.current;
@@ -273,11 +265,7 @@ function assignFunctions(polygene) {
ctx.templatePath(from),
ctx.destinationPath(to),
{
- packageName: polygene.packageName,
hasFeature: hasFeature,
- hasEntityStore: hasEntityStore,
- hasIndexing: hasIndexing,
- hasCaching: hasCaching,
firstUpper: firstUpper,
polygene: polygene
}
@@ -380,32 +368,32 @@ function assignFunctions(polygene) {
state.push('Property' + '<' + polygene.typeNameOnly(prop.type) + "> " + prop.name + "();")
imported[prop.type] = imported[prop.type];
var yamlDefault;
- if( prop.type === "java.lang.String" ) {
+ if (prop.type === "java.lang.String") {
yamlDefault = '""';
}
- else if( prop.type === "java.lang.Boolean" ) {
+ else if (prop.type === "java.lang.Boolean") {
yamlDefault = 'false';
}
- else if( prop.type === "java.lang.Long" ) {
+ else if (prop.type === "java.lang.Long") {
yamlDefault = '0';
}
- else if( prop.type === "java.lang.Integer" ) {
+ else if (prop.type === "java.lang.Integer") {
yamlDefault = '0';
}
- else if( prop.type === "java.lang.Double" ) {
+ else if (prop.type === "java.lang.Double") {
yamlDefault = '0.0';
}
- else if( prop.type === "java.lang.Float" ) {
+ else if (prop.type === "java.lang.Float") {
yamlDefault = '0.0';
}
else {
yamlDefault = '\n # TODO: complex configuration type. ';
}
- yaml.push( prop.name + " : " + yamlDefault);
+ yaml.push(prop.name + " : " + yamlDefault);
}
} else {
state.push('Property<String> name(); // TODO: remove sample property')
- yaml.push( 'name : "sample config value"' );
+ yaml.push('name : "sample config value"');
}
current.state = state;
current.yaml = yaml;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl
index 0c925da..37eecfa 100644
--- a/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.bootstrap.config;
+package <%= polygene.packageName %>.bootstrap.config;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.bootstrap.AssemblyException;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/ConfigurationLayer/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConfigurationLayer/bootstrap.tmpl b/tools/generator-polygene/app/templates/ConfigurationLayer/bootstrap.tmpl
index bb81a83..d83ae32 100644
--- a/tools/generator-polygene/app/templates/ConfigurationLayer/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/ConfigurationLayer/bootstrap.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.bootstrap.config;
+package <%= polygene.packageName %>.bootstrap.config;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.LayerAssembly;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/DefaultEnroler.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/DefaultEnroler.tmpl b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/DefaultEnroler.tmpl
index c469137..31d4588 100644
--- a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/DefaultEnroler.tmpl
+++ b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/DefaultEnroler.tmpl
@@ -16,8 +16,8 @@
* limitations under the License.
*
*
--%>
-package <%= packageName %>.rest.security;
+%>
+package <%= polygene.packageName %>.rest.security;
import java.util.ArrayList;
import java.util.List;
@@ -27,7 +27,7 @@ import org.restlet.Application;
import org.restlet.data.ClientInfo;
import org.restlet.security.Enroler;
import org.restlet.security.Role;
-import <%= packageName %>.model.security.SecurityRepository;
+import <%= polygene.packageName %>.model.security.SecurityRepository;
public class DefaultEnroler
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/DefaultVerifier.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/DefaultVerifier.tmpl b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/DefaultVerifier.tmpl
index 256b39d..e31e240 100644
--- a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/DefaultVerifier.tmpl
+++ b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/DefaultVerifier.tmpl
@@ -17,12 +17,12 @@
*
*
-%>
-package <%= packageName %>.rest.security;
+package <%= polygene.packageName %>.rest.security;
import org.apache.polygene.api.injection.scope.Service;
import org.restlet.security.SecretVerifier;
import org.restlet.security.Verifier;
-import <%= packageName %>.model.security.SecurityRepository;
+import <%= polygene.packageName %>.model.security.SecurityRepository;
public class DefaultVerifier extends SecretVerifier
implements Verifier
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/NullEnroler.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/NullEnroler.tmpl b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/NullEnroler.tmpl
index 8076289..c24ddce 100644
--- a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/NullEnroler.tmpl
+++ b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/NullEnroler.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.rest.security;
+package <%= polygene.packageName %>.rest.security;
import org.restlet.data.ClientInfo;
import org.restlet.security.Enroler;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/NullVerifier.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/NullVerifier.tmpl b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/NullVerifier.tmpl
index e7af254..5d6b349 100644
--- a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/NullVerifier.tmpl
+++ b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/NullVerifier.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.rest.security;
+package <%= polygene.packageName %>.rest.security;
import org.restlet.security.SecretVerifier;
import org.restlet.security.Verifier;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/bootstrap.tmpl
index d2ad313..0594546 100644
--- a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/bootstrap.tmpl
@@ -17,14 +17,14 @@
*
*
-%>
-package <%= packageName %>.bootstrap.connectivity;
+package <%= polygene.packageName %>.bootstrap.connectivity;
<% if( hasFeature('security') ) { %>
-import <%= packageName %>.rest.security.DefaultEnroler;
-import <%= packageName %>.rest.security.DefaultVerifier;
+import <%= polygene.packageName %>.rest.security.DefaultEnroler;
+import <%= polygene.packageName %>.rest.security.DefaultVerifier;
<% } else { %>
-import <%= packageName %>.rest.security.NullEnroler;
-import <%= packageName %>.rest.security.NullVerifier;
+import <%= polygene.packageName %>.rest.security.NullEnroler;
+import <%= polygene.packageName %>.rest.security.NullVerifier;
<% } %>
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.LayerAssembly;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/module.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/module.js b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/module.js
index 8524da3..4a2af7d 100644
--- a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/module.js
+++ b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/module.js
@@ -2,7 +2,7 @@
module.exports = {
write: function (p) {
- if (p.hasFeature("rest api")) {
+ if (p.applicationtype === 'Rest API') {
p.copyTemplate(p.ctx,
'ConnectivityLayer/RestApiModule/bootstrap.tmpl',
'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/connectivity/RestApiModule.java');
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/web.xml.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/web.xml.tmpl b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/web.xml.tmpl
new file mode 100644
index 0000000..d650933
--- /dev/null
+++ b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/web.xml.tmpl
@@ -0,0 +1,46 @@
+<%#
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ ~
+ ~
+%><?xml version="1.0" encoding="UTF-8"?>
+<web-app xmlns="http://java.sun.com/xml/ns/javaee"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
+ version="2.5">
+
+ <display-name><%= polygene.name %></display-name>
+<% if( polygene.hasFeature( "security" ) { %>
+ <listener>
+ <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
+ </listener>
+<% } %>
+<% if( polygene.hasFeature( "security" ) { %>
+ <filter>
+ <filter-name>ShiroFilter</filter-name>
+ <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
+ </filter>
+<% } %>
+<% if( polygene.hasFeature( "security" ) { %>
+ <-- Filter all web requests. This filter mapping is typically declared
+ before all others to ensure any other filters are secured as well: -->
+ <filter-mapping>
+ <filter-name>ShiroFilter</filter-name>
+ <url-pattern>/*</url-pattern>
+ </filter-mapping>
+<% } %>
+
+</web-app>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/ConnectivityLayer/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConnectivityLayer/bootstrap.tmpl b/tools/generator-polygene/app/templates/ConnectivityLayer/bootstrap.tmpl
index 941e77e..efe2d4d 100644
--- a/tools/generator-polygene/app/templates/ConnectivityLayer/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/ConnectivityLayer/bootstrap.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.bootstrap.connectivity;
+package <%= polygene.packageName %>.bootstrap.connectivity;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.LayerAssembly;
@@ -33,7 +33,7 @@ public class ConnectivityLayer extends LayeredLayerAssembler
public LayerAssembly assemble( LayerAssembly layer )
throws AssemblyException
{
-<% if( hasFeature('rest api') ) { %>
+<% if( polygene.applicationtype === 'Rest API' ) { %>
createModule( layer, RestApiModule.class );
<% } -%>
return layer;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/CrudModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/CrudModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/DomainLayer/CrudModule/bootstrap.tmpl
index 0877723..2c50918 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/CrudModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/CrudModule/bootstrap.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.bootstrap.domain;
+package <%= polygene.packageName %>.bootstrap.domain;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.LayerAssembly;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/CrudModule/module.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/CrudModule/module.js b/tools/generator-polygene/app/templates/DomainLayer/CrudModule/module.js
index acc509a..6c930d9 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/CrudModule/module.js
+++ b/tools/generator-polygene/app/templates/DomainLayer/CrudModule/module.js
@@ -2,8 +2,10 @@
module.exports = {
write: function (p) {
- p.copyTemplate(p.ctx,
- 'DomainLayer/CrudModule/bootstrap.tmpl',
- 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/domain/CrudModule.java');
+ if( p.applicationtype === 'Rest API' ) {
+ p.copyTemplate(p.ctx,
+ 'DomainLayer/CrudModule/bootstrap.tmpl',
+ 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/domain/CrudModule.java');
+ }
}
};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Configuration.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Configuration.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Configuration.tmpl
index 071ee7b..b5ab022 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Configuration.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Configuration.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.model.<%= polygene.current.name %>;
+package <%= polygene.packageName %>.model.<%= polygene.current.name %>;
import org.apache.polygene.api.property.Property;
<%
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl
index df53506..2abd6b3 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.model.<%= polygene.current.name %>;
+package <%= polygene.packageName %>.model.<%= polygene.current.name %>;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl
index df53506..2abd6b3 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.model.<%= polygene.current.name %>;
+package <%= polygene.packageName %>.model.<%= polygene.current.name %>;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Object.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Object.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Object.tmpl
index 9ff4e00..d51cdf5 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Object.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Object.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.model.<%= polygene.current.name %>;
+package <%= polygene.packageName %>.model.<%= polygene.current.name %>;
import org.apache.polygene.api.injection.scope.Structure;
import org.apache.polygene.api.injection.scope.Uses;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Service.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Service.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Service.tmpl
index 5710441..67c989b 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Service.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Service.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.model.<%= polygene.current.name %>;
+package <%= polygene.packageName %>.model.<%= polygene.current.name %>;
import org.apache.polygene.api.configuration.Configuration;
import org.apache.polygene.api.injection.scope.Structure;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Transient.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Transient.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Transient.tmpl
index 1fae121..ffb1660 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Transient.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Transient.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.model.<%= polygene.current.name %>;
+package <%= polygene.packageName %>.model.<%= polygene.current.name %>;
import org.apache.polygene.api.injection.scope.Uses;
import org.apache.polygene.api.mixin.Mixins;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
index 34a95b0..3d3baea 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.model.<%= polygene.current.name %>;
+package <%= polygene.packageName %>.model.<%= polygene.current.name %>;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl
index 17b391a..092d683 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.bootstrap.domain;
+package <%= polygene.packageName %>.bootstrap.domain;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.LayerAssembly;
@@ -25,32 +25,32 @@ import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.bootstrap.layered.ModuleAssembler;
<% for( var idx in polygene.current.cruds) {
-%><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.cruds[idx].name + ";" %>
+%><%= "import " + polygene.packageName + ".model." + polygene.current.name + "." + polygene.current.cruds[idx].name + ";" %>
<%
}
for( var idx in polygene.current.values) {
-%><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.values[idx].name + ";" %>
+%><%= "import " + polygene.packageName + ".model." + polygene.current.name + "." + polygene.current.values[idx].name + ";" %>
<%
}
for( var idx in polygene.current.entities) {
-%><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.entities[idx].name + ";" %>
+%><%= "import " + polygene.packageName + ".model." + polygene.current.name + "." + polygene.current.entities[idx].name + ";" %>
<%
}
for( var idx in polygene.current.transients) {
-%><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.transients[idx].name + ";" %>
+%><%= "import " + polygene.packageName + ".model." + polygene.current.name + "." + polygene.current.transients[idx].name + ";" %>
<%
}
for( var idx in polygene.current.objects) {
-%><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.objects[idx].name + ";" %>
+%><%= "import " + polygene.packageName + ".model." + polygene.current.name + "." + polygene.current.objects[idx].name + ";" %>
<%
}
for( var idx in polygene.current.services) {
-%><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.services[idx].name + ";" %>
-<%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.configurationClassName(polygene.current.services[idx].name) + ";" %>
+%><%= "import " + polygene.packageName + ".model." + polygene.current.name + "." + polygene.current.services[idx].name + ";" %>
+<%= "import " + polygene.packageName + ".model." + polygene.current.name + "." + polygene.configurationClassName(polygene.current.services[idx].name) + ";" %>
<%
} %>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoConfiguration.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoConfiguration.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoConfiguration.tmpl
index 89883a2..3262390 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoConfiguration.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoConfiguration.tmpl
@@ -17,18 +17,19 @@
*
*
-%>
-package <%= packageName %>.model.security;
+package <%= polygene.packageName %>.model.security;
+import org.apache.polygene.api.configuration.ConfigurationComposite;
import org.apache.polygene.api.property.Property;
import org.apache.polygene.api.common.Optional;
-public class CryptoConfiguration
+public interface CryptoConfiguration extends ConfigurationComposite
{
@Optional
Property<String> digestAlgorithm();
@Optional
- Property<String> digestAlgorithm();
+ Property<String> encryptionAlgorithm();
Property<String> secret1();
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoException.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoException.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoException.tmpl
index 00ec8f8..d6e8d38 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoException.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoException.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.model.security;
+package <%= polygene.packageName %>.model.security;
public class CryptoException extends RuntimeException
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoService.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoService.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoService.tmpl
index 4bc72c2..588e70d 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoService.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoService.tmpl
@@ -17,13 +17,15 @@
*
*
-%>
-package <%= packageName %>.model.security;
+package <%= polygene.packageName %>.model.security;
import java.security.MessageDigest;
-import java.crypto.Cipher;
-import java.crypto.spec.IvParameterSpec;
-import java.crypto.spec.SecretKeySpec;
+import javax.crypto.Cipher;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+import org.apache.polygene.api.injection.scope.This;
+import org.apache.polygene.api.configuration.Configuration;
import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.property.Property;
@@ -34,31 +36,35 @@ public interface CryptoService
String decrypt( String encrypted );
- class CryptoMixin
+ class Mixin
implements CryptoService
{
- private byte[] keyBytes;
- private byte[] ivBytes;
+ private SecretKeySpec key;
+ private IvParameterSpec ivSpec;
private Cipher cipher;
private MessageDigest digest;
- public CryptoMixin(Configuration<CryptoConfiguration> configuration)
+ public Mixin( @This Configuration<CryptoConfiguration> configuration)
throws Exception
{
- CryptoConfiguration config = configuration.configuration().get();
+ CryptoConfiguration config = configuration.get();
String digestAlgorithm = config.digestAlgorithm().get();
if( digestAlgorithm == null )
+ {
digestAlgorithm = "SHA-1";
- digest = MessageDigest.getInstance( );
+ }
+ digest = MessageDigest.getInstance( digestAlgorithm );
byte[] keyBytes = hashed( config.secret1().get() );
byte[] ivBytes = hashed( config.secret2().get() );
- SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
- IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
+ key = new SecretKeySpec(keyBytes, "DES");
+ ivSpec = new IvParameterSpec(ivBytes);
String encryptionAlgorithm = config.encryptionAlgorithm().get();
if( encryptionAlgorithm == null )
+ {
encryptionAlgorithm = "AES";
+ }
cipher = Cipher.getInstance( encryptionAlgorithm );
}
@@ -88,7 +94,8 @@ public interface CryptoService
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] encrypted = encryptedString.getBytes();
- byte[] decrypted = new byte[cipher.getOutputSize(enc_len)];
+ int enc_len = encrypted.length;
+ byte[] decrypted = new byte[cipher.getOutputSize(encrypted.length)];
int dec_len = cipher.update(encrypted, 0, enc_len, decrypted, 0);
dec_len += cipher.doFinal(decrypted, dec_len);
return new String( decrypted, 0, dec_len );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/EncryptedStringPropertyConcern.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/EncryptedStringPropertyConcern.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/EncryptedStringPropertyConcern.tmpl
index 4083a39..5db973c 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/EncryptedStringPropertyConcern.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/EncryptedStringPropertyConcern.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.model.security;
+package <%= polygene.packageName %>.model.security;
import org.apache.polygene.api.concern.ConcernOf;
import org.apache.polygene.api.property.Property;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/EntityStoreBackedSecurityRepositoryMixin.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/EntityStoreBackedSecurityRepositoryMixin.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/EntityStoreBackedSecurityRepositoryMixin.tmpl
deleted file mode 100644
index 56c4a5c..0000000
--- a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/EntityStoreBackedSecurityRepositoryMixin.tmpl
+++ /dev/null
@@ -1,60 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.model.security;
-
-import java.util.Collections;
-import java.util.List;
-import org.apache.polygene.api.unitofwork.concern.UnitOfWorkPropagation;
-
-public class EntityStoreBackedSecurityRepositoryMixin
- implements SecurityRepository
-{
- @Structure
- private UnitOfWorkFactory uowf;
-
- @Override
- @UnitOfWorkPropagation
- public boolean verifyPassword( String userName, String password )
- {
- Identity identity = new StringIdentity("User-" + userName );
- User user = uow.currentUnitOfWork(User.class, identity );
-
- if( userName.equals("admin") && password.equals("secret") )
- {
- return true;
- }
- if( userName.equals("user") && password.equals("123") )
- {
- return true;
- }
- return false;
- }
-
- @UnitOfWorkPropagation
- public List<String> findRoleNamesOfUser( String name )
- {
- if( "admin".equals( name ) )
- {
- return Collections.singletonList("admin");
- }
- return Collections.singletonList("user");
- }
-}
-
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/Group.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/Group.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/Group.tmpl
index 8e0aba8..ea212d2 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/Group.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/Group.tmpl
@@ -16,26 +16,11 @@
* limitations under the License.
*
*
--%>
-package <%= packageName %>.model.security;
+%>
+package <%= polygene.packageName %>.model.security;
-import org.apache.polygene.api.injection.scope.This;
-import org.apache.polygene.api.mixin.Mixins;
-import org.apache.polygene.api.property.Property;
+import org.apache.polygene.library.shiro.domain.permissions.RoleAssignee;
-@Mixins( { Group.Mixin } )
-public interface Group
+public interface Group extends RoleAssignee
{
- interface State
- {
- Property<String> password();
- }
-
- class Mixin
- implements Group
- {
- @This
- private State state; // Sample reference to hidden property
-
- }
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/RealmService.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/RealmService.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/RealmService.tmpl
index 875f35b..106975f 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/RealmService.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/RealmService.tmpl
@@ -17,15 +17,23 @@
*
*
-%>
-package <%= packageName %>.model.security;
+package <%= polygene.packageName %>.model.security;
-@Mixins( MyRealmMixin.class )
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.service.ServiceActivation;
+
+import org.apache.shiro.authc.credential.DefaultPasswordService;
+import org.apache.shiro.authc.credential.PasswordMatcher;
+import org.apache.shiro.authc.credential.PasswordService;
+import org.apache.shiro.realm.Realm;
+import org.apache.shiro.realm.SimpleAccountRealm;
+
+@Mixins( RealmService.Mixin.class )
public interface RealmService
- extends Realm, ServiceComposite, ServiceActivation
+ extends Realm, ServiceActivation
{
- class Mixin
- extends SimpleAccountRealm
- implements ServiceActivation
+ class Mixin extends SimpleAccountRealm
+ implements ServiceActivation
{
private final PasswordService passwordService;
@@ -42,8 +50,13 @@ public interface RealmService
public void activateService()
throws Exception
{
- // Create a test account
+ // Create a test account
addAccount( "foo", passwordService.encryptPassword( "bar" ) );
}
+
+ public void passivateService()
+ throws Exception
+ {
+ }
}
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/SecurityRepository.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/SecurityRepository.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/SecurityRepository.tmpl
index 5910c7c..06eb69c 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/SecurityRepository.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/SecurityRepository.tmpl
@@ -17,18 +17,24 @@
*
*
-%>
-package <%= packageName %>.model.security;
+package <%= polygene.packageName %>.model.security;
+import java.util.Collections;
import java.util.List;
import org.apache.polygene.api.concern.Concerns;
import org.apache.polygene.api.identity.Identity;
import org.apache.polygene.api.identity.StringIdentity;
+import org.apache.polygene.api.injection.scope.Structure;
+import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
import org.apache.polygene.api.unitofwork.concern.UnitOfWorkConcern;
import org.apache.polygene.api.unitofwork.concern.UnitOfWorkPropagation;
+import org.apache.shiro.SecurityUtils;
+import org.apache.shiro.authc.UsernamePasswordToken;
+import org.apache.shiro.subject.Subject;
@Concerns( UnitOfWorkConcern.class )
-@Mixins( { SecurityRepository.EntiyStoreBackedMixin.class } )
+@Mixins( { SecurityRepository.ShiroBackedSecurityRepositoryMixin.class } )
public interface SecurityRepository
{
@UnitOfWorkPropagation
@@ -38,7 +44,7 @@ public interface SecurityRepository
List<String> findRoleNamesOfUser( String name );
- class EntityStoreBackedSecurityRepositoryMixin
+ class ShiroBackedSecurityRepositoryMixin
implements SecurityRepository
{
@Structure
@@ -48,16 +54,18 @@ public interface SecurityRepository
@UnitOfWorkPropagation
public boolean verifyPassword( String userName, String password )
{
- Identity identity = new StringIdentity("User-" + userName );
- User user = uow.currentUnitOfWork(User.class, identity );
- return user.verify( password );
+ Subject currentUser = SecurityUtils.getSubject();
+ return currentUser.isAuthenticated();
}
@UnitOfWorkPropagation
public List<String> findRoleNamesOfUser( String name )
{
+ if( "admin".equals( name ) )
+ {
+ return Collections.singletonList("admin");
+ }
+ return Collections.singletonList("user");
}
}
-
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/User.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/User.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/User.tmpl
index 32f2db1..08db130 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/User.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/User.tmpl
@@ -16,36 +16,36 @@
* limitations under the License.
*
*
--%>
-package <%= packageName %>.model.security;
+%>
+package <%= polygene.packageName %>.model.security;
+import org.apache.polygene.api.association.ManyAssociation;
+import org.apache.polygene.api.concern.Concerns;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.property.Property;
+import org.apache.polygene.library.shiro.domain.passwords.PasswordSecurable;
+import org.apache.polygene.library.shiro.domain.permissions.RoleAssignee;
-@Mixins( { User.Mixin } )
-public interface User
+@Mixins( { User.GroupsMixin.class } )
+public interface User extends PasswordSecurable, RoleAssignee
{
+ boolean isMemberOf( Group group );
interface State
{
- @Concerns( EncryptedStringPropertyConcern.class )
- Property<String> password();
-
ManyAssociation<Group> memberOf();
}
- class Mixin
+ abstract class GroupsMixin
implements User
{
- @Service
- private HashingService hashing;
-
@This
private State state;
-
+ public boolean isMemberOf( Group group )
+ {
+ return state.memberOf().contains( group );
+ }
}
-
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/UserFactory.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/UserFactory.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/UserFactory.tmpl
new file mode 100644
index 0000000..298950e
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/UserFactory.tmpl
@@ -0,0 +1,55 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= polygene.packageName %>.model.security;
+
+import org.apache.polygene.api.entity.EntityBuilder;
+import org.apache.polygene.api.injection.scope.Structure;
+import org.apache.polygene.api.injection.scope.Service;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
+
+import org.apache.shiro.authc.credential.PasswordService;
+
+@Mixins( UserFactory.Mixin.class )
+public interface UserFactory
+{
+
+ User createNewUser( String username, String password );
+
+ class Mixin
+ implements UserFactory
+ {
+ @Structure
+ private UnitOfWorkFactory uowf;
+
+ @Service
+ private PasswordService passwordService;
+
+ @Override
+ public User createNewUser( String username, String password )
+ {
+ EntityBuilder<User> userBuilder = uowf.currentUnitOfWork().newEntityBuilder( User.class );
+ User user = userBuilder.instance();
+ user.subjectIdentifier().set( username );
+ user.password().set( passwordService.encryptPassword( password ) );
+ return userBuilder.newInstance();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/bootstrap.tmpl
index 7513044..e60c563 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/bootstrap.tmpl
@@ -17,17 +17,21 @@
*
*
-%>
-package <%= packageName %>.bootstrap.domain;
+package <%= polygene.packageName %>.bootstrap.domain;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.LayerAssembly;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.bootstrap.layered.ModuleAssembler;
+import org.apache.polygene.library.shiro.assembly.PasswordDomainAssembler;
+import org.apache.polygene.library.shiro.assembly.PermissionsDomainAssembler;
import org.apache.polygene.library.shiro.assembly.StandaloneShiroAssembler;
-
-import <%= packageName %>.model.security.SecurityRepository;
-import <%= packageName %>.model.security.HardcodedSecurityRepositoryMixin;
+import org.apache.polygene.library.shiro.ini.ShiroIniConfiguration;
+import <%= polygene.packageName %>.model.security.RealmService;
+import <%= polygene.packageName %>.model.security.SecurityRepository;
+import <%= polygene.packageName %>.model.security.User;
+import <%= polygene.packageName %>.model.security.UserFactory;
public class SecurityModule
implements ModuleAssembler
@@ -39,15 +43,27 @@ public class SecurityModule
throws AssemblyException
{
module.services( SecurityRepository.class )
- .withMixins( HardcodedSecurityRepositoryMixin.class )
.visibleIn( Visibility.application )
.instantiateOnStartup();
- new StandaloneShiroAssembler().
- withConfig( configModule, Visibility.layer ).
- assemble( module );
+ new StandaloneShiroAssembler()
+ .withConfig( module, Visibility.layer )
+ .assemble( module );
module.services( RealmService.class );
+ module.forMixin( ShiroIniConfiguration.class )
+ .declareDefaults()
+ .iniResourcePath().set( "classpath:standalone-shiro.ini" );
+
+ new PasswordDomainAssembler()
+ .withConfig( module, Visibility.layer )
+ .assemble( module );
+
+ new PermissionsDomainAssembler().assemble( module );
+
+ module.entities( User.class );
+ module.services( UserFactory.class );
+
return module;
}
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/module.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/module.js b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/module.js
index 5d21aaa..1ba7360 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/module.js
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/module.js
@@ -11,11 +11,11 @@ module.exports = {
copyFile(p, "CryptoException");
copyFile(p, "CryptoService");
copyFile(p, "EncryptedStringPropertyConcern");
- copyFile(p, "EntityStoreBackedSecurityRepositoryMixin");
copyFile(p, "Group");
copyFile(p, "RealmService");
copyFile(p, "SecurityRepository");
copyFile(p, "User");
+ copyFile(p, "UserFactory");
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/DomainLayer/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/bootstrap.tmpl b/tools/generator-polygene/app/templates/DomainLayer/bootstrap.tmpl
index 68be6f3..638941f 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/bootstrap.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.bootstrap.domain;
+package <%= polygene.packageName %>.bootstrap.domain;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.LayerAssembly;
@@ -31,7 +31,7 @@ public class DomainLayer extends LayeredLayerAssembler
public LayerAssembly assemble( LayerAssembly layer )
throws AssemblyException
{
-<% if( hasFeature( 'rest api' ) ) {
+<% if( polygene.applicationtype === 'Rest API' ) {
%> createModule( layer, CrudModule.class );<%
}
for( var mod in polygene.modules ) {%>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/InfrastructureLayer/CachingModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/CachingModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/CachingModule/bootstrap.tmpl
index 4945277..d9d86a9 100644
--- a/tools/generator-polygene/app/templates/InfrastructureLayer/CachingModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/CachingModule/bootstrap.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.bootstrap.infrastructure;
+package <%= polygene.packageName %>.bootstrap.infrastructure;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.bootstrap.AssemblyException;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/InfrastructureLayer/FileConfigurationModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/FileConfigurationModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/FileConfigurationModule/bootstrap.tmpl
index ab2ad2c..380cc19 100644
--- a/tools/generator-polygene/app/templates/InfrastructureLayer/FileConfigurationModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/FileConfigurationModule/bootstrap.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.bootstrap.infrastructure;
+package <%= polygene.packageName %>.bootstrap.infrastructure;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.bootstrap.AssemblyException;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/InfrastructureLayer/IndexingModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/IndexingModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/IndexingModule/bootstrap.tmpl
index c7e1975..6648c9f 100644
--- a/tools/generator-polygene/app/templates/InfrastructureLayer/IndexingModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/IndexingModule/bootstrap.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.bootstrap.infrastructure;
+package <%= polygene.packageName %>.bootstrap.infrastructure;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.bootstrap.AssemblyException;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/InfrastructureLayer/MetricsModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/MetricsModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/MetricsModule/bootstrap.tmpl
index a4d3919..d06c9cc 100644
--- a/tools/generator-polygene/app/templates/InfrastructureLayer/MetricsModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/MetricsModule/bootstrap.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.bootstrap.infrastructure;
+package <%= polygene.packageName %>.bootstrap.infrastructure;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.bootstrap.AssemblyException;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl
index 62b3586..f75dc3a 100644
--- a/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.bootstrap.infrastructure;
+package <%= polygene.packageName %>.bootstrap.infrastructure;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.bootstrap.AssemblyException;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/InfrastructureLayer/StorageModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/StorageModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/StorageModule/bootstrap.tmpl
index 997fe3b..5cde992 100644
--- a/tools/generator-polygene/app/templates/InfrastructureLayer/StorageModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/StorageModule/bootstrap.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.bootstrap.infrastructure;
+package <%= polygene.packageName %>.bootstrap.infrastructure;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.bootstrap.AssemblyException;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/InfrastructureLayer/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/bootstrap.tmpl
index d02d6a9..cead6b3 100644
--- a/tools/generator-polygene/app/templates/InfrastructureLayer/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/bootstrap.tmpl
@@ -17,7 +17,7 @@
*
*
-%>
-package <%= packageName %>.bootstrap.infrastructure;
+package <%= polygene.packageName %>.bootstrap.infrastructure;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.LayerAssembly;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/buildtool/gradle-bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/buildtool/gradle-bootstrap.tmpl b/tools/generator-polygene/app/templates/buildtool/gradle-bootstrap.tmpl
index bc0a651..fa3630a 100644
--- a/tools/generator-polygene/app/templates/buildtool/gradle-bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/buildtool/gradle-bootstrap.tmpl
@@ -26,7 +26,7 @@ dependencies {
compile "org.apache.polygene.libraries:org.apache.polygene.library.fileconfig:$polygeneVersion"
-<% if( hasFeature( 'rest api' ) ) { %>
+<% if( polygene.applicationtype === 'Rest API' ) { %>
compile "org.apache.polygene.libraries:org.apache.polygene.library.restlet:$polygeneVersion"
<% } %>
compile "org.apache.polygene.extensions:org.apache.polygene.extension.entitystore-<%= polygene.entitystore.toLowerCase() %>:$polygeneVersion"
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/buildtool/gradle-model.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/buildtool/gradle-model.tmpl b/tools/generator-polygene/app/templates/buildtool/gradle-model.tmpl
index 7f75b20..7b7243a 100644
--- a/tools/generator-polygene/app/templates/buildtool/gradle-model.tmpl
+++ b/tools/generator-polygene/app/templates/buildtool/gradle-model.tmpl
@@ -18,6 +18,12 @@
*
-%>
-// dependencies {
-// compile "org.restlet.jee:org.restlet:2.3.4"
-// }
+dependencies {
+
+<% if( hasFeature( 'security' ) ) {
+%> compile "org.apache.polygene.libraries:org.apache.polygene.library.shiro-core:$polygeneVersion"
+<% } %>
+<% if( polygene.applicationtype === 'Rest API' ) {
+%> compile "org.apache.polygene.libraries:org.apache.polygene.library.restlet:$polygeneVersion"
+<% } %>
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/app/templates/buildtool/gradle-rest.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/buildtool/gradle-rest.tmpl b/tools/generator-polygene/app/templates/buildtool/gradle-rest.tmpl
index 82afa09..d07ac02 100644
--- a/tools/generator-polygene/app/templates/buildtool/gradle-rest.tmpl
+++ b/tools/generator-polygene/app/templates/buildtool/gradle-rest.tmpl
@@ -22,6 +22,8 @@ dependencies {
compile project( ":model" )
compile "org.apache.polygene.core:org.apache.polygene.core.api:$polygeneVersion"
- compile "org.apache.polygene.libraries:org.apache.polygene.library.restlet:$polygeneVersion"
+<% if( polygene.applicationtype === 'Rest API' ) {
+%> compile "org.apache.polygene.libraries:org.apache.polygene.library.restlet:$polygeneVersion"
+<% } %>
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/01949a6d/tools/generator-polygene/test/generator_test.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/test/generator_test.js b/tools/generator-polygene/test/generator_test.js
index 07b9c84..d5f2b58 100644
--- a/tools/generator-polygene/test/generator_test.js
+++ b/tools/generator-polygene/test/generator_test.js
@@ -5,17 +5,8 @@ var shell = require('shelljs');
//See http://yeoman.io/authoring/testing.html
-describe('polygene-generator-defaults', function () {
- this.timeout(10000);
- it('generates a Gradle buildable Apache Polygene project', function () {
- return helpers.run(path.join(__dirname, '../app'))
- .withPrompts({
- name: 'test-project',
- packageName: 'org.apache.polygene.generator.test'
- })
- .then(buildAndVerify);
- });
-});
+// test with all defaults first.
+test();
var entityStores = [
'Cassandra',
@@ -104,7 +95,7 @@ entityStores.forEach(function (entitystore) {
});
function test(entityStore, indexing, serialization, caching, metrics, features) {
- describe('polygene-generator-default-and-' + entityStore.toLowerCase() + "-entitystore", function () {
+ describe('polygene-generator', function () {
this.timeout(10000);
it('generates a Gradle buildable Apache Polygene project with '
+ entityStore + 'EntityStore, '
@@ -115,10 +106,10 @@ function test(entityStore, indexing, serialization, caching, metrics, features)
+ ' and ' + features + '.',
function () {
return helpers.run(path.join(__dirname, '../app'))
+ .inDir(path.join(__dirname, '../build/test-project'))
.withPrompts({
name: 'test-project',
packageName: 'org.apache.polygene.generator.test',
-
entitystore: entityStore,
serialization: serialization,
indexing: indexing,
[45/50] [abbrv] polygene-java git commit: Serialization
implementation details cleanup
Posted by pa...@apache.org.
Serialization implementation details cleanup
remove unused imports, prefer final fields, introduce constants where
appropriate, uniform Java serialization and Base64 encoding etc\u2026
POLYGENE-231
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/9485717f
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/9485717f
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/9485717f
Branch: refs/heads/serialization-3.0
Commit: 9485717fc8a447a5f793d55d4b9ee76d35590242
Parents: 55916ef
Author: Paul Merlin <pa...@apache.org>
Authored: Mon Mar 13 10:04:25 2017 +0100
Committer: Paul Merlin <pa...@apache.org>
Committed: Mon Mar 13 11:24:42 2017 +0100
----------------------------------------------------------------------
.../serialization/javaxjson/JavaxJson.java | 2 ++
.../javaxjson/JavaxJsonAdapters.java | 2 +-
.../javaxjson/JavaxJsonDeserializer.java | 9 ++++-----
.../javaxjson/JavaxJsonSerializer.java | 18 ++++++------------
.../javaxjson/JavaxJsonSettings.java | 4 ++--
.../spi/serialization/JsonDeserializer.java | 5 ++---
.../spi/serialization/XmlDeserializer.java | 5 -----
.../javaxxml/JavaxXmlDeserializer.java | 9 ++++-----
.../javaxxml/JavaxXmlSerializer.java | 13 ++++++-------
.../msgpack/MessagePackDeserializer.java | 11 ++++++-----
.../msgpack/MessagePackSerializer.java | 14 ++++++++------
11 files changed, 41 insertions(+), 51 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/9485717f/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJson.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJson.java b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJson.java
index 3c44864..3e7ad6f 100644
--- a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJson.java
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJson.java
@@ -33,6 +33,8 @@ import javax.json.JsonValue;
*/
public class JavaxJson
{
+ public static JsonValue EMPTY_STRING = toJsonString( "" );
+
/**
* Create a {@link JsonObjectBuilder} populated with the state of a {@link JsonObject}.
*
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/9485717f/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonAdapters.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonAdapters.java b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonAdapters.java
index fdc9d27..a46accd 100644
--- a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonAdapters.java
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonAdapters.java
@@ -38,7 +38,7 @@ public interface JavaxJsonAdapters
class Mixin implements JavaxJsonAdapters
{
- private Map<ValueType, JavaxJsonAdapter<?>> adapters = new LinkedHashMap<>();
+ private final Map<ValueType, JavaxJsonAdapter<?>> adapters = new LinkedHashMap<>();
@Override
public void registerAdapter( ValueType valueType, JavaxJsonAdapter<?> adapter )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/9485717f/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java
index a1e5d75..2d8cc53 100644
--- a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java
@@ -158,7 +158,8 @@ public class JavaxJsonDeserializer extends AbstractTextDeserializer implements J
return (T) deserializeValueComposite( module, valueDescriptor.valueType(), object );
}
case STRING:
- return (T) deserializeBase64( asString( json ) );
+ byte[] bytes = Base64.getDecoder().decode( asString( json ).getBytes( UTF_8 ) );
+ return (T) deserializeJava( bytes );
default:
throw new SerializationException( "Don't know how to deserialize " + valueType + " from " + json );
}
@@ -285,17 +286,15 @@ public class JavaxJsonDeserializer extends AbstractTextDeserializer implements J
};
}
- private Object deserializeBase64( String inputString )
+ private Object deserializeJava( byte[] bytes )
{
- byte[] bytes = inputString.getBytes( UTF_8 );
- bytes = Base64.getDecoder().decode( bytes );
try( ObjectInputStream oin = new ObjectInputStream( new ByteArrayInputStream( bytes ) ) )
{
return oin.readObject();
}
catch( IOException | ClassNotFoundException ex )
{
- throw new SerializationException( "Unable to deserialize Base64 serialized " + inputString, ex );
+ throw new SerializationException( "Unable to deserialize using Java serialization", ex );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/9485717f/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java
index 07294a9..93a9077 100644
--- a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java
@@ -20,7 +20,6 @@ package org.apache.polygene.serialization.javaxjson;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
-import java.io.UncheckedIOException;
import java.util.Base64;
import java.util.Map;
import java.util.function.Function;
@@ -32,7 +31,6 @@ import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
-import javax.json.JsonString;
import javax.json.JsonValue;
import org.apache.polygene.api.PolygeneAPI;
import org.apache.polygene.api.association.AssociationStateHolder;
@@ -41,6 +39,7 @@ import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.injection.scope.Uses;
import org.apache.polygene.api.serialization.Converter;
import org.apache.polygene.api.serialization.Converters;
+import org.apache.polygene.api.serialization.SerializationException;
import org.apache.polygene.api.service.ServiceDescriptor;
import org.apache.polygene.api.type.ArrayType;
import org.apache.polygene.api.type.MapType;
@@ -111,8 +110,8 @@ public class JavaxJsonSerializer extends AbstractTextSerializer implements JsonS
return serializeStream( options, (Stream<?>) object );
}
// Fallback to Java Serialization in Base 64
- // Include all arrays!
- return serializeBase64( object );
+ byte[] bytes = Base64.getEncoder().encode( serializeJava( object ) );
+ return JavaxJson.toJsonString( new String( bytes, UTF_8 ) );
}
private JsonObject serializeValueComposite( Options options, Object composite, boolean root )
@@ -219,23 +218,18 @@ public class JavaxJsonSerializer extends AbstractTextSerializer implements JsonS
return builder.build();
}
- private JsonString serializeBase64( Object object )
- {
- byte[] bytes = Base64.getEncoder().encode( javaSerialization( object ) );
- return JavaxJson.toJsonString( new String( bytes, UTF_8 ) );
- }
-
- private byte[] javaSerialization( Object object )
+ private byte[] serializeJava( Object object )
{
ByteArrayOutputStream bout = new ByteArrayOutputStream();
try( ObjectOutputStream out = new ObjectOutputStream( bout ) )
{
out.writeUnshared( object );
+ out.flush();
return bout.toByteArray();
}
catch( IOException ex )
{
- throw new UncheckedIOException( ex );
+ throw new SerializationException( "Unable to serialize using Java serialization", ex );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/9485717f/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSettings.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSettings.java b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSettings.java
index 266bd99..e0f993d 100644
--- a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSettings.java
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSettings.java
@@ -56,13 +56,13 @@ public class JavaxJsonSettings
public JavaxJsonSettings withTypeInfoPropertyName( String typeInfoPropertyName )
{
- setTypeInfoPropertyName( typeInfoPropertyName );
+ this.typeInfoPropertyName = typeInfoPropertyName;
return this;
}
public JavaxJsonSettings withJsonAdapter( ValueType valueType, JavaxJsonAdapter<?> adapter )
{
- getAdapters().put( valueType, adapter );
+ adapters.put( valueType, adapter );
return this;
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/9485717f/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonDeserializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonDeserializer.java
index 84c8993..a0dac71 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonDeserializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonDeserializer.java
@@ -34,6 +34,7 @@ import javax.json.stream.JsonParsingException;
import org.apache.polygene.api.serialization.Deserializer;
import org.apache.polygene.api.structure.ModuleDescriptor;
import org.apache.polygene.api.type.ValueType;
+import org.apache.polygene.serialization.javaxjson.JavaxJson;
import org.apache.polygene.spi.module.ModuleSpi;
import static java.util.stream.Collectors.joining;
@@ -157,8 +158,6 @@ public interface JsonDeserializer extends Deserializer
return outOfStructureFunction.apply( stateString );
}
// Empty state string?
- JsonValue emptyJsonString = Json.createReader( new StringReader( "{\"empty\":\"\"}" ) )
- .readObject().get( "empty" );
- return fromJson( module, valueType, emptyJsonString );
+ return fromJson( module, valueType, JavaxJson.EMPTY_STRING );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/9485717f/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlDeserializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlDeserializer.java
index c7ac42b..9e559c8 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlDeserializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlDeserializer.java
@@ -28,12 +28,7 @@ import javax.xml.parsers.ParserConfigurationException;
import org.apache.polygene.api.serialization.Deserializer;
import org.apache.polygene.api.serialization.SerializationException;
import org.apache.polygene.api.structure.ModuleDescriptor;
-import org.apache.polygene.api.type.CollectionType;
-import org.apache.polygene.api.type.EnumType;
-import org.apache.polygene.api.type.MapType;
-import org.apache.polygene.api.type.ValueCompositeType;
import org.apache.polygene.api.type.ValueType;
-import org.apache.polygene.api.value.ValueDescriptor;
import org.apache.polygene.spi.module.ModuleSpi;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/9485717f/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
index f477a8c..146d763 100644
--- a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
@@ -315,22 +315,21 @@ public class JavaxXmlDeserializer extends AbstractTextDeserializer implements Xm
}
if( xml.getNodeType() == Node.CDATA_SECTION_NODE )
{
- return deserializeBase64( xml.getNodeValue() );
+ byte[] bytes = Base64.getDecoder().decode( xml.getNodeValue().getBytes( UTF_8 ) );
+ return deserializeJava( bytes );
}
throw new SerializationException( "Don't know how to deserialize " + valueType + " from " + xml );
}
- private Object deserializeBase64( String inputString )
+ private Object deserializeJava( byte[] bytes )
{
- byte[] bytes = inputString.getBytes( UTF_8 );
- bytes = Base64.getDecoder().decode( bytes );
try( ObjectInputStream oin = new ObjectInputStream( new ByteArrayInputStream( bytes ) ) )
{
return oin.readObject();
}
catch( IOException | ClassNotFoundException ex )
{
- throw new SerializationException( "Unable to deserialize Base64 serialized " + inputString, ex );
+ throw new SerializationException( "Unable to deserialize using Java serialization", ex );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/9485717f/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java
index 49f1fa0..576647b 100644
--- a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java
@@ -20,7 +20,6 @@ package org.apache.polygene.serialization.javaxxml;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
-import java.io.UncheckedIOException;
import java.util.Base64;
import java.util.Map;
import java.util.function.Function;
@@ -139,8 +138,8 @@ public class JavaxXmlSerializer extends AbstractTextSerializer implements XmlSer
return serializeStream( document, options, (Stream<?>) object );
}
// Fallback to Java Serialization in Base 64
- // Include all arrays!
- return serializeBase64( document, object );
+ byte[] bytes = Base64.getEncoder().encode( serializeJava( object ) );
+ return document.createCDATASection( new String( bytes, UTF_8 ) );
}
private <T> Node serializeValueComposite( Document document, Options options, T composite, boolean root )
@@ -280,18 +279,18 @@ public class JavaxXmlSerializer extends AbstractTextSerializer implements XmlSer
return collectionElement;
}
- private <T> Node serializeBase64( Document document, T object )
+ private byte[] serializeJava( Object object )
{
ByteArrayOutputStream bout = new ByteArrayOutputStream();
try( ObjectOutputStream out = new ObjectOutputStream( bout ) )
{
out.writeUnshared( object );
- byte[] bytes = Base64.getEncoder().encode( bout.toByteArray() );
- return document.createCDATASection( new String( bytes, UTF_8 ) );
+ out.flush();
+ return bout.toByteArray();
}
catch( IOException ex )
{
- throw new UncheckedIOException( ex );
+ throw new SerializationException( "Unable to serialize using Java serialization", ex );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/9485717f/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
index 7a82751..9d5c9df 100644
--- a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
+++ b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
@@ -56,7 +56,6 @@ import org.apache.polygene.spi.serialization.AbstractBinaryDeserializer;
import org.msgpack.core.MessagePack;
import org.msgpack.core.MessageUnpacker;
import org.msgpack.value.ArrayValue;
-import org.msgpack.value.BinaryValue;
import org.msgpack.value.ImmutableValue;
import org.msgpack.value.MapValue;
import org.msgpack.value.Value;
@@ -285,7 +284,7 @@ public interface MessagePackDeserializer extends Deserializer
switch( value.getValueType() )
{
case BINARY:
- return deserializeJava( value.asBinaryValue() );
+ return deserializeJava( value.asBinaryValue().asByteArray() );
case MAP:
MapValue mapValue = value.asMapValue();
Optional<String> typeInfo = mapValue
@@ -313,14 +312,16 @@ public interface MessagePackDeserializer extends Deserializer
}
}
- private Object deserializeJava( BinaryValue value )
- throws IOException, ClassNotFoundException
+ private Object deserializeJava( byte[] bytes )
{
- byte[] bytes = value.asByteArray();
try( ObjectInputStream oin = new ObjectInputStream( new ByteArrayInputStream( bytes ) ) )
{
return oin.readObject();
}
+ catch( IOException | ClassNotFoundException ex )
+ {
+ throw new SerializationException( "Unable to deserialize using Java serialization", ex );
+ }
}
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/9485717f/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java
index c01ef29..ea66ad0 100644
--- a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java
+++ b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java
@@ -45,7 +45,6 @@ import org.apache.polygene.spi.serialization.AbstractBinarySerializer;
import org.msgpack.core.MessagePack;
import org.msgpack.core.MessagePacker;
import org.msgpack.value.ArrayValue;
-import org.msgpack.value.BinaryValue;
import org.msgpack.value.MapValue;
import org.msgpack.value.Value;
import org.msgpack.value.ValueFactory;
@@ -124,8 +123,7 @@ public interface MessagePackSerializer extends Serializer
return serializeStream( options, (Stream<?>) object );
}
// Fallback to Java Serialization
- // Include all arrays!
- return serializeJava( object );
+ return ValueFactory.newBinary( serializeJava( object ) );
}
catch( IOException ex )
{
@@ -203,14 +201,18 @@ public interface MessagePackSerializer extends Serializer
.collect( toList() ) );
}
- private BinaryValue serializeJava( Object object ) throws IOException
+ private byte[] serializeJava( Object object )
{
ByteArrayOutputStream bout = new ByteArrayOutputStream();
try( ObjectOutputStream out = new ObjectOutputStream( bout ) )
{
out.writeUnshared( object );
- byte[] bytes = bout.toByteArray();
- return ValueFactory.newBinary( bytes );
+ out.flush();
+ return bout.toByteArray();
+ }
+ catch( IOException ex )
+ {
+ throw new SerializationException( "Unable to serialize using Java serialization", ex );
}
}
}
[42/50] [abbrv] polygene-java git commit: Finish jooq & liquibase
powered SQL ES
Posted by pa...@apache.org.
Finish jooq & liquibase powered SQL ES
POLYGENE-153
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/e3f025e4
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/e3f025e4
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/e3f025e4
Branch: refs/heads/serialization-3.0
Commit: e3f025e47922e1fb647c4c30844f0420ea701c97
Parents: 3d4805f
Author: Paul Merlin <pa...@apache.org>
Authored: Mon Feb 27 14:03:36 2017 +0100
Committer: Paul Merlin <pa...@apache.org>
Committed: Mon Mar 13 11:24:42 2017 +0100
----------------------------------------------------------------------
extensions/entitystore-sql/build.gradle | 9 +-
extensions/entitystore-sql/src/docs/es-sql.txt | 14 +-
.../sql/SQLMapEntityStoreConfiguration.java | 47 +++
.../sql/SQLMapEntityStoreMapping.java | 69 ----
.../entitystore/sql/SQLMapEntityStoreMixin.java | 124 +++----
.../sql/SQLMapEntityStoreService.java | 4 +-
.../AbstractSQLMapEntityStoreAssembler.java | 42 ++-
.../sql/internal/DatabaseSQLService.java | 96 ------
.../internal/DatabaseSQLServiceCoreMixin.java | 159 ---------
.../sql/internal/DatabaseSQLServiceSpi.java | 81 -----
.../sql/internal/DatabaseSQLServiceState.java | 33 --
.../DatabaseSQLServiceStatementsMixin.java | 113 -------
.../sql/internal/DatabaseSQLStringsBuilder.java | 325 -------------------
.../DerbySQLDatabaseSQLServiceMixin.java | 67 ----
.../internal/H2SQLDatabaseSQLServiceMixin.java | 64 ----
.../internal/MySQLDatabaseSQLServiceMixin.java | 68 ----
.../PostgreSQLDatabaseSQLServiceMixin.java | 64 ----
.../internal/PostgreSQLStringBuilderMixin.java | 45 ---
.../sql/internal/SQLEntityState.java | 189 -----------
.../internal/SQLiteDatabaseSQLServiceMixin.java | 66 ----
.../polygene/entitystore/sql/internal/SQLs.java | 29 --
.../entitystore/sql/internal/package.html | 24 --
.../polygene/entitystore/sql/changelog.xml | 37 +++
.../sql/DerbySQLEntityStoreTest.java | 17 +-
.../entitystore/sql/MySQLEntityStoreTest.java | 14 +-
.../sql/PostgreSQLEntityStoreTest.java | 12 +-
.../entitystore/sql/SQLiteEntityStoreTest.java | 3 +-
.../test/resources/mysql-datasource.properties | 2 +-
.../sql/SQLIndexingEngineConfiguration.java | 31 ++
.../AbstractSQLIndexQueryAssembler.java | 4 +-
.../support/skeletons/AbstractSQLStartup.java | 13 +-
.../postgresql/PostgreSQLDBIntegrityTest.java | 6 +-
libraries/sql-liquibase/build.gradle | 4 +-
.../sql/liquibase/LiquibaseAssembler.java | 16 +-
.../sql/liquibase/LiquibaseConfiguration.java | 12 +-
.../library/sql/liquibase/LiquibaseService.java | 133 ++++----
.../sql/liquibase/LiquibaseServiceTest.java | 7 +-
.../library/sql/common/SQLConfiguration.java | 4 -
...taSourceConfigurationManagerServiceTest.java | 18 +-
.../apache/polygene/sample/sqlsupport/Main.java | 8 -
.../sql/DerbySQLEntityStorePerformanceTest.java | 35 +-
.../PostgreSQLEntityStorePerformanceTest.java | 34 +-
42 files changed, 373 insertions(+), 1769 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/build.gradle b/extensions/entitystore-sql/build.gradle
index 15553dc..0c11fcd 100644
--- a/extensions/entitystore-sql/build.gradle
+++ b/extensions/entitystore-sql/build.gradle
@@ -29,22 +29,15 @@ dependencies {
api polygene.library( 'sql' )
api libraries.jooq
- implementation libraries.slf4j_api
implementation polygene.library( 'sql-liquibase' )
- // TODO Remove java SQL generator dependency
- implementation libraries.javaSqlGenerator
- implementation( libraries.javaSqlGeneratorImpl ) {
- exclude group: 'junit'
- }
-
runtimeOnly polygene.core.runtime
testImplementation polygene.internals.testsupport
testImplementation polygene.library( 'sql-dbcp' )
- testImplementation libraries.derby // Needed at compile time for polite test shutdown
testRuntimeOnly libraries.logback
+ testRuntimeOnly libraries.derby
testRuntimeOnly libraries.h2
testRuntimeOnly libraries.mysql_connector
testRuntimeOnly libraries.postgres
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/docs/es-sql.txt
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/docs/es-sql.txt b/extensions/entitystore-sql/src/docs/es-sql.txt
index 50e9f31..90a7175 100644
--- a/extensions/entitystore-sql/src/docs/es-sql.txt
+++ b/extensions/entitystore-sql/src/docs/es-sql.txt
@@ -30,6 +30,8 @@ EntityStore service backed by a SQL database.
This extension fully leverage the <<library-sql>> meaning that you must use it to assemble your DataSource and that you
get <<library-circuitbreaker,Circuit Breaker>> and <<library-jmx, JMX>> integration for free.
+The database schema is managed using <<library-sql-liquibase>>.
+
TIP: See the <<sample-sql-support>> that demonstrate combined use of <<library-sql>>, <<extension-es-sql>> and
<<extension-indexing-sql>>.
@@ -44,15 +46,17 @@ The following SQL databases are supported:
Each entity state is stored as a single row so maximum number of entities is the maximum number of rows per table
supported by the underlying SQL database.
-Implementations per database Vendor share a generic codebase but can override about everything SQL. As a consequence
-they can have strong differences in terms of performance if they use vendor specific extensions.
-
include::../../build/docs/buildinfo/artifact.txt[]
== Configuration ==
-SQL EntityStore Configuration is optional and provides only one configuration property: `schemaName` defaulted to
-'polygene_es'. On SQL databases that don't support schemas this configuration property is simply ignored.
+Here are the available configuration properties:
+
+[snippet,java]
+----
+source=extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreConfiguration.java
+tag=assembly
+----
The assembly snippets below show the DataSource assembly alongside the SQL EntityStore assembly. Remember to configure
the DataSource properly, see <<library-sql>> and <<howto-configure-service>>.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreConfiguration.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreConfiguration.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreConfiguration.java
new file mode 100644
index 0000000..cd832c0
--- /dev/null
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreConfiguration.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.entitystore.sql;
+
+import org.apache.polygene.api.common.UseDefaults;
+import org.apache.polygene.api.property.Property;
+import org.apache.polygene.library.sql.common.SQLConfiguration;
+
+// START SNIPPET: config
+public interface SQLMapEntityStoreConfiguration extends SQLConfiguration
+{
+ /**
+ * Name of the database schema to use.
+ * Ignored on SQL databases that don't support schemas.
+ */
+ @UseDefaults( "POLYGENE_ES" )
+ @Override
+ Property<String> schemaName();
+
+ /**
+ * Name of the entities table.
+ */
+ @UseDefaults( "POLYGENE_ENTITIES" )
+ Property<String> entityTableName();
+
+ /**
+ * Defines whether the database schema and table should be created if not already present.
+ */
+ @UseDefaults( "true" )
+ Property<Boolean> createIfMissing();
+}
+// END SNIPPET: config
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMapping.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMapping.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMapping.java
deleted file mode 100644
index 67f6066..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMapping.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.polygene.entitystore.sql;
-
-import org.jooq.DataType;
-import org.jooq.impl.SQLDataType;
-
-/**
- * Mapping for the entities table.
- *
- * If you change this once the table is created you'll have to ALTER it yourself.
- */
-public interface SQLMapEntityStoreMapping
-{
- default String defaultSchemaName()
- {
- return "POLYGENE_ES";
- }
-
- default String tableName()
- {
- return "POLYGENE_ENTITIES";
- }
-
- default String identityColumnName()
- {
- return "ENTITY_IDENTITY";
- }
-
- default String versionColumnName()
- {
- return "ENTITY_VERSION";
- }
-
- default String stateColumnName()
- {
- return "ENTITY_STATE";
- }
-
- default DataType<String> identityDataType()
- {
- return SQLDataType.VARCHAR( 64 );
- }
-
- default DataType<String> versionDataType()
- {
- return SQLDataType.VARCHAR( 64 );
- }
-
- default DataType<String> stateDataType()
- {
- return SQLDataType.VARCHAR( 10 * 1024 );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java
index 7e08daf..77a7640 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java
@@ -22,13 +22,17 @@ import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
+import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
-import java.util.Objects;
import java.util.stream.Stream;
import javax.json.Json;
import javax.sql.DataSource;
-import org.apache.polygene.api.common.Optional;
+import liquibase.Contexts;
+import liquibase.Liquibase;
+import liquibase.database.Database;
+import liquibase.database.ObjectQuotingStrategy;
+import liquibase.exception.LiquibaseException;
import org.apache.polygene.api.configuration.Configuration;
import org.apache.polygene.api.entity.EntityDescriptor;
import org.apache.polygene.api.entity.EntityReference;
@@ -37,9 +41,8 @@ import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.injection.scope.Uses;
import org.apache.polygene.api.service.ServiceActivation;
import org.apache.polygene.api.service.ServiceDescriptor;
-import org.apache.polygene.library.sql.common.SQLConfiguration;
+import org.apache.polygene.library.sql.liquibase.LiquibaseService;
import org.apache.polygene.spi.entitystore.EntityNotFoundException;
-import org.apache.polygene.spi.entitystore.EntityStoreException;
import org.apache.polygene.spi.entitystore.helpers.JSONKeys;
import org.apache.polygene.spi.entitystore.helpers.MapEntityStore;
import org.jooq.DSLContext;
@@ -51,26 +54,27 @@ import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.conf.Settings;
import org.jooq.impl.DSL;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-// TODO Implement optimistic locking! Maybe as a SPI helper (in-progress)
-// TODO Add schema version data into the DB, check it
-// TODO Remove old SQL ES Code
+// TODO Remove old SQL ES Code and spurious dependencies
public class SQLMapEntityStoreMixin
implements ServiceActivation, MapEntityStore
{
- private static final Logger LOGGER = LoggerFactory.getLogger( SQLMapEntityStoreService.class );
+ private static final String TABLE_NAME_LIQUIBASE_PARAMETER = "es-sql.table";
+ private static final String IDENTITY_COLUMN_NAME = "ENTITY_IDENTITY";
+ private static final String VERSION_COLUMN_NAME = "ENTITY_VERSION";
+ private static final String STATE_COLUMN_NAME = "ENTITY_STATE";
@Service
private DataSource dataSource;
+ @Service
+ private LiquibaseService liquibaseService;
+
@Uses
private ServiceDescriptor descriptor;
@This
- @Optional
- private Configuration<SQLConfiguration> configuration;
+ private Configuration<SQLMapEntityStoreConfiguration> configuration;
private Schema schema;
private Table<Record> table;
@@ -82,40 +86,64 @@ public class SQLMapEntityStoreMixin
@Override
public void activateService() throws Exception
{
+ configuration.refresh();
+ SQLMapEntityStoreConfiguration config = configuration.get();
+
+ // Prepare jooq DSL
SQLDialect dialect = descriptor.metaInfo( SQLDialect.class );
Settings settings = descriptor.metaInfo( Settings.class );
- SQLMapEntityStoreMapping mapping = descriptor.metaInfo( SQLMapEntityStoreMapping.class );
- String schemaName = getConfiguredSchemaName( mapping.defaultSchemaName() );
- if( schemaName == null )
- {
- throw new EntityStoreException( "Schema name must not be null." );
- }
- schema = DSL.schema( DSL.name( schemaName.toUpperCase() ) );
+ String schemaName = config.schemaName().get();
+ String tableName = config.entityTableName().get();
+ schema = DSL.schema( DSL.name( schemaName ) );
table = DSL.table(
dialect.equals( SQLDialect.SQLITE )
- ? DSL.name( mapping.tableName() )
- : DSL.name( schema.getName(), mapping.tableName() )
+ ? DSL.name( tableName )
+ : DSL.name( schema.getName(), tableName )
);
- identityColumn = DSL.field( mapping.identityColumnName(), String.class );
- versionColumn = DSL.field( mapping.versionColumnName(), String.class );
- stateColumn = DSL.field( mapping.stateColumnName(), String.class );
-
+ identityColumn = DSL.field( DSL.name( IDENTITY_COLUMN_NAME ), String.class );
+ versionColumn = DSL.field( DSL.name( VERSION_COLUMN_NAME ), String.class );
+ stateColumn = DSL.field( DSL.name( STATE_COLUMN_NAME ), String.class );
dsl = DSL.using( dataSource, dialect, settings );
- if( !dialect.equals( SQLDialect.SQLITE )
- && dsl.meta().getSchemas().stream().noneMatch( s -> schema.getName().equals( s.getName() ) ) )
+ // Eventually create schema and apply Liquibase changelog
+ if( config.createIfMissing().get() )
{
- dsl.createSchema( schema ).execute();
+ if( !dialect.equals( SQLDialect.SQLITE )
+ && dsl.meta().getSchemas().stream().noneMatch( s -> schema.getName().equalsIgnoreCase( s.getName() ) ) )
+ {
+ dsl.createSchema( schema ).execute();
+ }
+
+ applyLiquibaseChangelog( dialect );
}
+ }
- if( dsl.meta().getTables().stream().noneMatch( t -> table.getName().equals( t.getName() ) ) )
+ private void applyLiquibaseChangelog( SQLDialect dialect ) throws SQLException, LiquibaseException
+ {
+ Liquibase liquibase = liquibaseService.newConnectedLiquibase();
+ Database db = liquibase.getDatabase();
+ db.setObjectQuotingStrategy( ObjectQuotingStrategy.QUOTE_ALL_OBJECTS );
+ try
{
- dsl.createTable( table )
- .column( identityColumn, mapping.identityDataType().nullable( false ) )
- .column( versionColumn, mapping.versionDataType().nullable( false ) )
- .column( stateColumn, mapping.stateDataType().nullable( false ) )
- .constraint( DSL.constraint( "ENTITY_IDENTITY_CONSTRAINT" ).primaryKey( identityColumn ) )
- .execute();
+ if( !dialect.equals( SQLDialect.SQLITE ) )
+ {
+ if( db.supportsSchemas() )
+ {
+ db.setDefaultSchemaName( schema.getName() );
+ db.setLiquibaseSchemaName( schema.getName() );
+ }
+ if( db.supportsCatalogs() )
+ {
+ db.setDefaultCatalogName( schema.getName() );
+ db.setLiquibaseCatalogName( schema.getName() );
+ }
+ }
+ liquibase.getChangeLogParameters().set( TABLE_NAME_LIQUIBASE_PARAMETER, table.getName() );
+ liquibase.update( new Contexts() );
+ }
+ finally
+ {
+ db.close();
}
}
@@ -210,30 +238,4 @@ public class SQLMapEntityStoreMixin
} );
dsl.batch( operations ).execute();
}
-
-
- /**
- * Configuration is optional at both assembly and runtime.
- */
- protected String getConfiguredSchemaName( String defaultSchemaName )
- {
- if( configuration == null )
- {
- Objects.requireNonNull( defaultSchemaName, "default schema name" );
- LOGGER.debug( "No configuration, will use default schema name: '{}'", defaultSchemaName );
- return defaultSchemaName;
- }
- String result = configuration.get().schemaName().get();
- if( result == null )
- {
- Objects.requireNonNull( defaultSchemaName, "default schema name" );
- result = defaultSchemaName;
- LOGGER.debug( "No database schema name in configuration, will use default: '{}'", defaultSchemaName );
- }
- else
- {
- LOGGER.debug( "Will use configured database schema name: '{}'", result );
- }
- return result;
- }
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreService.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreService.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreService.java
index 0ff1e59..7c770df 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreService.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreService.java
@@ -19,9 +19,10 @@ package org.apache.polygene.entitystore.sql;
import org.apache.polygene.api.concern.Concerns;
import org.apache.polygene.api.configuration.Configuration;
+import org.apache.polygene.api.injection.scope.Uses;
import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.service.ServiceActivation;
-import org.apache.polygene.api.service.ServiceComposite;
+import org.apache.polygene.api.service.ServiceDescriptor;
import org.apache.polygene.spi.entitystore.ConcurrentModificationCheckConcern;
import org.apache.polygene.spi.entitystore.EntityStateVersions;
import org.apache.polygene.spi.entitystore.EntityStore;
@@ -39,7 +40,6 @@ public interface SQLMapEntityStoreService
JSONMapEntityStoreActivation,
EntityStore,
EntityStateVersions,
- ServiceComposite,
Configuration
{
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/AbstractSQLMapEntityStoreAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/AbstractSQLMapEntityStoreAssembler.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/AbstractSQLMapEntityStoreAssembler.java
index 4e205d1..aac6dfc 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/AbstractSQLMapEntityStoreAssembler.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/AbstractSQLMapEntityStoreAssembler.java
@@ -22,10 +22,12 @@ import org.apache.polygene.api.identity.StringIdentity;
import org.apache.polygene.bootstrap.Assemblers;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.entitystore.sql.SQLMapEntityStoreMapping;
+import org.apache.polygene.entitystore.sql.SQLMapEntityStoreConfiguration;
import org.apache.polygene.entitystore.sql.SQLMapEntityStoreService;
-import org.apache.polygene.library.sql.common.SQLConfiguration;
+import org.apache.polygene.library.sql.liquibase.LiquibaseAssembler;
+import org.apache.polygene.library.sql.liquibase.LiquibaseConfiguration;
import org.jooq.SQLDialect;
+import org.jooq.conf.RenderNameStyle;
import org.jooq.conf.Settings;
/**
@@ -35,6 +37,9 @@ public abstract class AbstractSQLMapEntityStoreAssembler<AssemblerType>
extends Assemblers.VisibilityIdentityConfig<AssemblerType>
{
public static final Identity DEFAULT_ENTITYSTORE_IDENTITY = new StringIdentity( "entitystore-sql" );
+ private static final String DEFAULT_CHANGELOG_PATH = "org/apache/polygene/entitystore/sql/changelog.xml";
+
+ private String changelogPath = DEFAULT_CHANGELOG_PATH;
@Override
public void assemble( ModuleAssembly module )
@@ -49,37 +54,44 @@ public abstract class AbstractSQLMapEntityStoreAssembler<AssemblerType>
{
throw new AssemblyException( "Settings must not be null" );
}
- SQLMapEntityStoreMapping mapping = getMapping();
- if( settings == null )
+
+ String identity = ( hasIdentity() ? identity() : DEFAULT_ENTITYSTORE_IDENTITY ).toString();
+
+ LiquibaseAssembler liquibase = new LiquibaseAssembler().identifiedBy( identity + "-liquibase" );
+ if( hasConfig() )
{
- throw new AssemblyException( "SQLMapEntityStoreSchema must not be null" );
+ liquibase.withConfig( configModule(), configVisibility() );
+ LiquibaseConfiguration liquibaseconfig = configModule().forMixin( LiquibaseConfiguration.class )
+ .declareDefaults();
+ liquibaseconfig.changeLog().set( changelogPath );
}
+ liquibase.assemble( module );
module.services( SQLMapEntityStoreService.class )
- .identifiedBy( ( hasIdentity() ? identity() : DEFAULT_ENTITYSTORE_IDENTITY ).toString() )
+ .identifiedBy( identity )
.visibleIn( visibility() )
.setMetaInfo( dialect )
- .setMetaInfo( settings )
- .setMetaInfo( mapping );
+ .setMetaInfo( settings );
if( hasConfig() )
{
- configModule().entities( SQLConfiguration.class ).visibleIn( configVisibility() );
+ configModule().entities( SQLMapEntityStoreConfiguration.class ).visibleIn( configVisibility() );
}
}
- protected Settings getSettings()
+ public AssemblerType withLiquibaseChangelog( String changelogPath )
{
- return new Settings();
+ this.changelogPath = changelogPath;
+ return (AssemblerType) this;
}
- protected SQLDialect getSQLDialect()
+ protected Settings getSettings()
{
- return SQLDialect.DEFAULT;
+ return new Settings().withRenderNameStyle( RenderNameStyle.QUOTED );
}
- protected SQLMapEntityStoreMapping getMapping()
+ protected SQLDialect getSQLDialect()
{
- return new SQLMapEntityStoreMapping() {};
+ return SQLDialect.DEFAULT;
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLService.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLService.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLService.java
deleted file mode 100644
index fddb19f..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLService.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.sql.internal;
-
-import java.io.Reader;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import org.apache.polygene.api.entity.EntityReference;
-import org.apache.polygene.api.service.ServiceComposite;
-
-@SuppressWarnings( "PublicInnerClass" )
-public interface DatabaseSQLService
-{
- interface DatabaseSQLServiceComposite extends DatabaseSQLService, ServiceComposite
- {
- }
-
- final class EntityValueResult
- {
- private final Reader reader;
-
- EntityValueResult( Reader reader )
- {
- this.reader = reader;
- }
-
- /**
- * @return the reader
- */
- public Reader getReader()
- {
- return reader;
- }
- }
-
- void startDatabase()
- throws Exception;
-
- void stopDatabase()
- throws Exception;
-
- Connection getConnection()
- throws SQLException;
-
- PreparedStatement prepareGetEntityStatement( Connection connection )
- throws SQLException;
-
- PreparedStatement prepareGetAllEntitiesStatement( Connection connection )
- throws SQLException;
-
- PreparedStatement prepareInsertEntityStatement( Connection connection )
- throws SQLException;
-
- PreparedStatement prepareUpdateEntityStatement( Connection connection )
- throws SQLException;
-
- PreparedStatement prepareRemoveEntityStatement( Connection connection )
- throws SQLException;
-
- void populateGetEntityStatement( PreparedStatement ps, EntityReference ref )
- throws SQLException;
-
- void populateGetAllEntitiesStatement( PreparedStatement ps )
- throws SQLException;
-
- void populateInsertEntityStatement( PreparedStatement ps, EntityReference ref, String entity )
- throws SQLException;
-
- void populateUpdateEntityStatement( PreparedStatement ps, EntityReference ref, String entity )
- throws SQLException;
-
- void populateRemoveEntityStatement( PreparedStatement ps, EntityReference ref )
- throws SQLException;
-
- Reader getEntityStateReader( ResultSet rs )
- throws SQLException;
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceCoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceCoreMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceCoreMixin.java
deleted file mode 100644
index 3c37457..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceCoreMixin.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.sql.internal;
-
-import java.sql.Connection;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.Objects;
-import javax.sql.DataSource;
-import org.apache.polygene.api.configuration.Configuration;
-import org.apache.polygene.api.injection.scope.Service;
-import org.apache.polygene.api.injection.scope.Structure;
-import org.apache.polygene.api.injection.scope.This;
-import org.apache.polygene.api.injection.scope.Uses;
-import org.apache.polygene.api.service.ServiceDescriptor;
-import org.apache.polygene.api.structure.Application;
-import org.apache.polygene.api.structure.Application.Mode;
-import org.apache.polygene.library.sql.common.SQLConfiguration;
-import org.apache.polygene.library.sql.common.SQLUtil;
-import org.apache.polygene.spi.entitystore.EntityStoreException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.sql.generation.api.vendor.SQLVendor;
-
-@SuppressWarnings( "ProtectedField" )
-public abstract class DatabaseSQLServiceCoreMixin
- implements DatabaseSQLService
-{
-
- private static final Logger LOGGER = LoggerFactory.getLogger( DatabaseSQLServiceCoreMixin.class );
-
- @Structure
- private Application application;
-
- @Service
- private DataSource dataSource;
-
- @This
- private DatabaseSQLServiceState state;
-
- @This
- protected DatabaseSQLServiceSpi spi;
-
- @This
- private DatabaseSQLStringsBuilder sqlStrings;
-
- @Uses
- private ServiceDescriptor descriptor;
-
- @This
- private Configuration<SQLConfiguration> configuration;
-
- @Override
- public Connection getConnection()
- throws SQLException
- {
- return dataSource.getConnection();
- }
-
- @Override
- public void startDatabase()
- throws Exception
- {
- Connection connection = getConnection();
- String schema = this.getConfiguredSchemaName( SQLs.DEFAULT_SCHEMA_NAME );
- if ( schema == null ) {
- throw new EntityStoreException( "Schema name must not be null." );
- } else {
- state.schemaName().set( schema );
- state.vendor().set( this.descriptor.metaInfo( SQLVendor.class ) );
-
- sqlStrings.init();
-
- if ( !spi.schemaExists( connection ) ) {
- LOGGER.debug( "Database Schema '{}' NOT found!", schema );
- Statement stmt = null;
- try {
- stmt = connection.createStatement();
- for ( String sql : sqlStrings.buildSQLForSchemaCreation() ) {
- stmt.execute( sql );
- }
- } finally {
- SQLUtil.closeQuietly( stmt );
- }
- LOGGER.debug( "Database Schema '{}' created", schema );
- }
-
- if ( !spi.tableExists( connection ) ) {
- Statement stmt = null;
- try {
- stmt = connection.createStatement();
- for ( String sql : sqlStrings.buildSQLForTableCreation() ) {
- stmt.execute( sql );
- }
- for ( String sql : sqlStrings.buildSQLForIndexCreation() ) {
- stmt.execute( sql );
- }
- } finally {
- SQLUtil.closeQuietly( stmt );
- }
- LOGGER.trace( "Table {} created", SQLs.TABLE_NAME );
- }
-
- connection.setAutoCommit( false );
-
- }
-
- SQLUtil.closeQuietly( connection );
-
- }
-
- @Override
- public void stopDatabase()
- throws Exception
- {
- if ( Mode.production == application.mode() ) {
- // NOOP
- }
- }
-
- /**
- * Configuration is optional at both assembly and runtime.
- */
- protected String getConfiguredSchemaName( String defaultSchemaName )
- {
- if ( configuration == null ) {
- Objects.requireNonNull( defaultSchemaName, "default schema name" );
- LOGGER.debug( "No configuration, will use default schema name: '{}'", defaultSchemaName );
- return defaultSchemaName;
- }
- String result = configuration.get().schemaName().get();
- if ( result == null ) {
- Objects.requireNonNull( defaultSchemaName, "default schema name" );
- result = defaultSchemaName;
- LOGGER.debug( "No database schema name in configuration, will use default: '{}'", defaultSchemaName );
- } else {
- LOGGER.debug( "Will use configured database schema name: '{}'", result );
- }
- return result;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceSpi.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceSpi.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceSpi.java
deleted file mode 100644
index 9042182..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceSpi.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.sql.internal;
-
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import org.apache.polygene.api.injection.scope.This;
-import org.apache.polygene.library.sql.common.SQLUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public interface DatabaseSQLServiceSpi
-{
-
- boolean schemaExists( Connection connection )
- throws SQLException;
-
- String getCurrentSchemaName();
-
- boolean tableExists( Connection connection )
- throws SQLException;
-
- @SuppressWarnings( "PublicInnerClass" )
- public abstract class CommonMixin
- implements DatabaseSQLServiceSpi
- {
-
- private static final Logger LOGGER = LoggerFactory.getLogger( DatabaseSQLServiceSpi.class );
-
- @This
- private DatabaseSQLServiceState state;
-
- @Override
- public boolean schemaExists( Connection connection )
- throws SQLException
- {
- ResultSet rs = null;
- try {
- Boolean schemaFound = false;
- rs = connection.getMetaData().getSchemas();
- String schemaName = this.getCurrentSchemaName();
-
- while ( rs.next() && !schemaFound ) {
- String eachResult = rs.getString( 1 );
- LOGGER.trace( "Schema candidate: {}", eachResult );
- schemaFound = eachResult.equalsIgnoreCase( schemaName );
- }
- LOGGER.trace( "Schema {} found? {}", schemaName, schemaFound );
- return schemaFound;
- } finally {
- SQLUtil.closeQuietly( rs );
- }
- }
-
- @Override
- public String getCurrentSchemaName()
- {
- return this.state.schemaName().get();
- }
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceState.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceState.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceState.java
deleted file mode 100644
index 3e3926d..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceState.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.sql.internal;
-
-import org.apache.polygene.api.common.Optional;
-import org.apache.polygene.api.property.Property;
-import org.sql.generation.api.vendor.SQLVendor;
-
-public interface DatabaseSQLServiceState
-{
- @Optional
- Property<String> schemaName();
-
- @Optional
- Property<SQLVendor> vendor();
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceStatementsMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceStatementsMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceStatementsMixin.java
deleted file mode 100644
index cce4568..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceStatementsMixin.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.sql.internal;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
-import org.apache.polygene.api.entity.EntityReference;
-import org.apache.polygene.api.injection.scope.This;
-
-public abstract class DatabaseSQLServiceStatementsMixin
- implements DatabaseSQLService
-{
-
- @This
- private DatabaseSQLStringsBuilder sqlStrings;
-
- //
- // Used by the EntityStore, will probably remain the same even if we support several sql servers
- //
- @Override
- public PreparedStatement prepareGetAllEntitiesStatement( Connection connection )
- throws SQLException
- {
- return connection.prepareStatement( sqlStrings.buildSQLForSelectAllEntitiesStatement() );
- }
-
- @Override
- public PreparedStatement prepareGetEntityStatement( Connection connection )
- throws SQLException
- {
- return connection.prepareStatement( sqlStrings.buildSQLForSelectEntityStatement() );
- }
-
- @Override
- public PreparedStatement prepareInsertEntityStatement( Connection connection )
- throws SQLException
- {
- return connection.prepareStatement( sqlStrings.buildSQLForInsertEntityStatement() );
- }
-
- @Override
- public PreparedStatement prepareRemoveEntityStatement( Connection connection )
- throws SQLException
- {
- return connection.prepareStatement( sqlStrings.buildSQLForRemoveEntityStatement() );
- }
-
- @Override
- public PreparedStatement prepareUpdateEntityStatement( Connection connection )
- throws SQLException
- {
- return connection.prepareStatement( sqlStrings.buildSQLForUpdateEntityStatement() );
- }
-
- //
- // Populate statement methods, to move in a separated fragment if needed for multi sql server support
- //
- @Override
- public void populateGetAllEntitiesStatement( PreparedStatement ps )
- throws SQLException
- {
- // Nothing to do.
- }
-
- @Override
- public void populateGetEntityStatement( PreparedStatement ps, EntityReference ref )
- throws SQLException
- {
- ps.setString( 1, ref.identity().toString() );
- }
-
- @Override
- public void populateInsertEntityStatement( PreparedStatement ps, EntityReference ref, String entity )
- throws SQLException
- {
- ps.setString( 1, ref.identity().toString() );
- ps.setString( 2, entity );
- }
-
- @Override
- public void populateRemoveEntityStatement( PreparedStatement ps, EntityReference ref )
- throws SQLException
- {
- ps.setString( 1, ref.identity().toString() );
- }
-
- @Override
- public void populateUpdateEntityStatement( PreparedStatement ps, EntityReference ref, String entity )
- throws SQLException
- {
- ps.setString( 1, ref.identity().toString() );
- ps.setString( 2, entity );
- }
-
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLStringsBuilder.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLStringsBuilder.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLStringsBuilder.java
deleted file mode 100644
index 6fb04cb..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLStringsBuilder.java
+++ /dev/null
@@ -1,325 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with work for additional information
- * regarding copyright ownership. The ASF licenses file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.sql.internal;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import org.apache.polygene.api.injection.scope.This;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.sql.generation.api.grammar.builders.modification.DeleteBySearchBuilder;
-import org.sql.generation.api.grammar.builders.modification.UpdateBySearchBuilder;
-import org.sql.generation.api.grammar.common.SQLStatement;
-import org.sql.generation.api.grammar.common.datatypes.SQLDataType;
-import org.sql.generation.api.grammar.definition.table.UniqueSpecification;
-import org.sql.generation.api.grammar.factories.BooleanFactory;
-import org.sql.generation.api.grammar.factories.ColumnsFactory;
-import org.sql.generation.api.grammar.factories.DefinitionFactory;
-import org.sql.generation.api.grammar.factories.LiteralFactory;
-import org.sql.generation.api.grammar.factories.ModificationFactory;
-import org.sql.generation.api.grammar.factories.QueryFactory;
-import org.sql.generation.api.grammar.factories.TableReferenceFactory;
-import org.sql.generation.api.vendor.SQLVendor;
-
-public interface DatabaseSQLStringsBuilder
-{
- void init();
-
- String[] buildSQLForSchemaCreation();
-
- String[] buildSQLForIndexCreation();
-
- String[] buildSQLForTableCreation();
-
- String buildSQLForSelectAllEntitiesStatement();
-
- String buildSQLForSelectEntityStatement();
-
- String buildSQLForInsertEntityStatement();
-
- String buildSQLForUpdateEntityStatement();
-
- String buildSQLForRemoveEntityStatement();
-
- abstract class CommonMixin
- implements DatabaseSQLStringsBuilder
- {
- private static final Logger LOGGER = LoggerFactory.getLogger( DatabaseSQLStringsBuilder.class );
-
- @This
- private DatabaseSQLServiceState dbState;
-
- private SQLVendor vendor;
- private String schemaName;
-
- private String[] schemaCreationSQLs;
- private String[] indexCreationSQLs;
- private String[] tableCreationSQLs;
-
- private String selectAllEntitiesSQL;
- private String selectEntitySQL;
- private String insertEntitySQL;
- private String updateEntitySQL;
- private String removeEntitySQL;
-
- @Override
- public void init()
- {
- vendor = dbState.vendor().get();
- schemaName = dbState.schemaName().get();
- schemaCreationSQLs = toString( createSchemaStatements( vendor ) );
- indexCreationSQLs = toString( createIndicesStatements( vendor ) );
- tableCreationSQLs = toString( createTableStatements( vendor ) );
- selectAllEntitiesSQL = vendor.toString( createSelectAllEntitiesStatement( vendor ) );
- selectEntitySQL = vendor.toString( createSelectEntityStatement( vendor ) );
- insertEntitySQL = vendor.toString( createInsertEntityStatement( vendor ) );
- updateEntitySQL = vendor.toString( createUpdateEntityStatement( vendor ) );
- removeEntitySQL = vendor.toString( createRemoveEntityStatement( vendor ) );
-
- if( LOGGER.isTraceEnabled() )
- {
- LOGGER.trace( "SQL for schema creation: {}", Arrays.asList( schemaCreationSQLs ) );
- LOGGER.trace( "SQL for index creation: {}", Arrays.asList( indexCreationSQLs ) );
- LOGGER.trace( "SQL for table creation: {}", Arrays.asList( tableCreationSQLs ) );
- LOGGER.trace( "SQL for select all entities: {}", selectAllEntitiesSQL );
- LOGGER.trace( "SQL for select entity: {}", selectEntitySQL );
- LOGGER.trace( "SQL for insert entity: {}", insertEntitySQL );
- LOGGER.trace( "SQL for update entity: {}", updateEntitySQL );
- LOGGER.trace( "SQL for remove entity: {}", removeEntitySQL );
- }
- }
-
- protected String[] toString( SQLStatement[] stmts )
- {
- List<String> result = new ArrayList<>();
- if( stmts != null )
- {
- for( Integer idx = 0; idx < stmts.length; ++idx )
- {
- SQLStatement statement = stmts[ idx ];
- if( statement != null )
- {
- String stringStatement = vendor.toString( statement );
- if( stringStatement != null && stringStatement.length() > 0 )
- {
- result.add( vendor.toString( statement ) );
- }
- }
- }
- }
- return result.toArray( new String[ result.size() ] );
- }
-
- protected SQLVendor getVendor()
- {
- return vendor;
- }
-
- protected String getSchemaName()
- {
- return schemaName;
- }
-
- protected SQLStatement[] createSchemaStatements( SQLVendor vendor )
- {
- return new SQLStatement[] {
- vendor.getDefinitionFactory().createSchemaDefinitionBuilder()
- .setSchemaName( schemaName ).createExpression()
- };
- }
-
- protected SQLStatement[] createIndicesStatements( SQLVendor vendor )
- {
- return new SQLStatement[] {};
- }
-
- protected SQLStatement[] createTableStatements( SQLVendor vendor )
- {
- DefinitionFactory d = vendor.getDefinitionFactory();
- TableReferenceFactory t = vendor.getTableReferenceFactory();
-
- return new SQLStatement[] {
- d.createTableDefinitionBuilder()
- .setTableName( t.tableName( getSchemaName(), SQLs.TABLE_NAME ) )
- .setTableContentsSource(
- d.createTableElementListBuilder()
- .addTableElement( d.createColumnDefinition( SQLs.ENTITY_IDENTITY_COLUMN_NAME,
- getIDType(), false ) )
- .addTableElement( d.createColumnDefinition( SQLs.ENTITY_VERSION_COLUMN_NAME,
- getVersionType(), false ) )
- .addTableElement( d.createColumnDefinition( SQLs.ENTITY_STATE_COLUMN_NAME,
- getStateType(), false ) )
- .addTableElement( d.createTableConstraintDefinition(
- d.createUniqueConstraintBuilder()
- .setUniqueness( UniqueSpecification.PRIMARY_KEY )
- .addColumns( SQLs.ENTITY_IDENTITY_COLUMN_NAME )
- .createExpression() )
- ).createExpression()
- ).createExpression()
- };
- }
-
- protected SQLStatement createSelectAllEntitiesStatement( SQLVendor vendor )
- {
- QueryFactory q = vendor.getQueryFactory();
- TableReferenceFactory t = vendor.getTableReferenceFactory();
-
- return q.simpleQueryBuilder()
- .select( SQLs.ENTITY_STATE_COLUMN_NAME )
- .from( t.tableName( schemaName, SQLs.TABLE_NAME ) )
- .createExpression();
- }
-
- protected SQLStatement createSelectEntityStatement( SQLVendor vendor )
- {
- QueryFactory q = vendor.getQueryFactory();
- TableReferenceFactory t = vendor.getTableReferenceFactory();
- BooleanFactory b = vendor.getBooleanFactory();
- ColumnsFactory c = vendor.getColumnsFactory();
- LiteralFactory l = vendor.getLiteralFactory();
-
- return q.simpleQueryBuilder()
- .select( SQLs.ENTITY_STATE_COLUMN_NAME )
- .from( t.tableName( schemaName, SQLs.TABLE_NAME ) )
- .where( b.eq( c.colName( SQLs.ENTITY_IDENTITY_COLUMN_NAME ), l.param() ) )
- .createExpression();
- }
-
- protected SQLStatement createInsertEntityStatement( SQLVendor vendor )
- {
- ModificationFactory m = vendor.getModificationFactory();
- TableReferenceFactory t = vendor.getTableReferenceFactory();
- LiteralFactory l = vendor.getLiteralFactory();
-
- return m.insert()
- .setTableName( t.tableName( schemaName, SQLs.TABLE_NAME ) )
- .setColumnSource( m.columnSourceByValues()
- .addColumnNames( SQLs.ENTITY_IDENTITY_COLUMN_NAME,
- SQLs.ENTITY_STATE_COLUMN_NAME )
- .addValues( l.param(),
- l.param() )
- .createExpression()
- ).createExpression();
- }
-
- protected SQLStatement createUpdateEntityStatement( SQLVendor vendor )
- {
- ModificationFactory m = vendor.getModificationFactory();
- TableReferenceFactory t = vendor.getTableReferenceFactory();
- LiteralFactory l = vendor.getLiteralFactory();
- BooleanFactory b = vendor.getBooleanFactory();
- ColumnsFactory c = vendor.getColumnsFactory();
-
- UpdateBySearchBuilder builder = m.updateBySearch().setTargetTable(
- m.createTargetTable( t.tableName( schemaName, SQLs.TABLE_NAME ) )
- ).addSetClauses(
- m.setClause( SQLs.ENTITY_VERSION_COLUMN_NAME, m.updateSourceByExp( l.param() ) ),
- m.setClause( SQLs.ENTITY_STATE_COLUMN_NAME, m.updateSourceByExp( l.param() ) )
- );
- builder.getWhereBuilder().reset(
- b.eq( c.colName( SQLs.ENTITY_IDENTITY_COLUMN_NAME ), l.param() )
- ).and(
- b.eq( c.colName( SQLs.ENTITY_VERSION_COLUMN_NAME ), l.param() )
- );
- return builder.createExpression();
- }
-
- protected SQLStatement createRemoveEntityStatement( SQLVendor vendor )
- {
- ModificationFactory m = vendor.getModificationFactory();
- TableReferenceFactory t = vendor.getTableReferenceFactory();
- LiteralFactory l = vendor.getLiteralFactory();
- BooleanFactory b = vendor.getBooleanFactory();
- ColumnsFactory c = vendor.getColumnsFactory();
-
- DeleteBySearchBuilder builder = m.deleteBySearch().setTargetTable(
- m.createTargetTable( t.tableName( schemaName, SQLs.TABLE_NAME ) )
- );
- builder.getWhere().reset(
- b.eq( c.colName( SQLs.ENTITY_IDENTITY_COLUMN_NAME ), l.param() )
- );
- return builder.createExpression();
- }
-
- protected SQLDataType getIDType()
- {
- return vendor.getDataTypeFactory().sqlVarChar( 64 );
- }
-
- protected SQLDataType getVersionType()
- {
- return vendor.getDataTypeFactory().sqlVarChar( 64 );
- }
-
- protected SQLDataType getStateType()
- {
- return vendor.getDataTypeFactory().sqlVarChar( 10000 );
- }
-
- @Override
- public String[] buildSQLForSchemaCreation()
- {
- return schemaCreationSQLs;
- }
-
- @Override
- public String[] buildSQLForIndexCreation()
- {
- return indexCreationSQLs;
- }
-
- @Override
- public String buildSQLForSelectAllEntitiesStatement()
- {
- return selectAllEntitiesSQL;
- }
-
- @Override
- public String buildSQLForSelectEntityStatement()
- {
- return selectEntitySQL;
- }
-
- @Override
- public String buildSQLForInsertEntityStatement()
- {
- return insertEntitySQL;
- }
-
- @Override
- public String buildSQLForUpdateEntityStatement()
- {
- return updateEntitySQL;
- }
-
- @Override
- public String buildSQLForRemoveEntityStatement()
- {
- return removeEntitySQL;
- }
-
- @Override
- public String[] buildSQLForTableCreation()
- {
- return tableCreationSQLs;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DerbySQLDatabaseSQLServiceMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DerbySQLDatabaseSQLServiceMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DerbySQLDatabaseSQLServiceMixin.java
deleted file mode 100644
index 083d79e..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DerbySQLDatabaseSQLServiceMixin.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.sql.internal;
-
-import java.io.Reader;
-import java.io.StringReader;
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import org.apache.polygene.api.injection.scope.This;
-import org.apache.polygene.library.sql.common.SQLUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@SuppressWarnings( "ProtectedField" )
-public abstract class DerbySQLDatabaseSQLServiceMixin
- implements DatabaseSQLService, DatabaseSQLStringsBuilder, DatabaseSQLServiceSpi
-{
- private static final Logger LOGGER = LoggerFactory.getLogger( DerbySQLDatabaseSQLServiceMixin.class );
-
- @This
- protected DatabaseSQLServiceSpi spi;
-
- @Override
- public boolean tableExists( Connection connection )
- throws SQLException
- {
- ResultSet rs = null;
- try
- {
- String tableNameForQuery = SQLs.TABLE_NAME.toUpperCase();
- rs = connection.getMetaData().getTables( null, null, tableNameForQuery,
- new String[] { "TABLE" } );
- boolean tableExists = rs.next();
- LOGGER.trace( "Found table {}? {}", tableNameForQuery, tableExists );
- return tableExists;
- }
- finally
- {
- SQLUtil.closeQuietly( rs );
- }
- }
-
- @Override
- public Reader getEntityStateReader( ResultSet rs )
- throws SQLException
- {
- return new StringReader( rs.getString( SQLs.ENTITY_STATE_COLUMN_NAME ) );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/H2SQLDatabaseSQLServiceMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/H2SQLDatabaseSQLServiceMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/H2SQLDatabaseSQLServiceMixin.java
deleted file mode 100644
index 3b870c6..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/H2SQLDatabaseSQLServiceMixin.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.sql.internal;
-
-import java.io.Reader;
-import java.io.StringReader;
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import org.apache.polygene.api.injection.scope.This;
-import org.apache.polygene.library.sql.common.SQLUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public abstract class H2SQLDatabaseSQLServiceMixin
- implements DatabaseSQLService, DatabaseSQLStringsBuilder, DatabaseSQLServiceSpi
-{
- private static final Logger LOGGER = LoggerFactory.getLogger( H2SQLDatabaseSQLServiceMixin.class );
-
- @This
- protected DatabaseSQLServiceSpi spi;
-
- public boolean tableExists( Connection connection )
- throws SQLException
- {
- ResultSet rs = null;
- try
- {
- String tableNameForQuery = SQLs.TABLE_NAME.toUpperCase();
- rs = connection.getMetaData().getTables( null, null, tableNameForQuery,
- new String[] { "TABLE" } );
- boolean tableExists = rs.next();
- LOGGER.trace( "Found table {}? {}", tableNameForQuery, tableExists );
- return tableExists;
- }
- finally
- {
- SQLUtil.closeQuietly( rs );
- }
- }
-
- public Reader getEntityStateReader( ResultSet rs )
- throws SQLException
- {
- return new StringReader( rs.getString( SQLs.ENTITY_STATE_COLUMN_NAME ) );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/MySQLDatabaseSQLServiceMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/MySQLDatabaseSQLServiceMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/MySQLDatabaseSQLServiceMixin.java
deleted file mode 100644
index 1c6c534..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/MySQLDatabaseSQLServiceMixin.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.sql.internal;
-
-import java.io.Reader;
-import java.io.StringReader;
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import org.apache.polygene.api.injection.scope.This;
-import org.apache.polygene.library.sql.common.SQLUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@SuppressWarnings( "ProtectedField" )
-public abstract class MySQLDatabaseSQLServiceMixin
- implements DatabaseSQLService, DatabaseSQLStringsBuilder, DatabaseSQLServiceSpi
-{
-
- private static final Logger LOGGER = LoggerFactory.getLogger( MySQLDatabaseSQLServiceMixin.class );
-
- @This
- protected DatabaseSQLServiceSpi spi;
-
- @Override
- public boolean tableExists( Connection connection )
- throws SQLException
- {
- ResultSet rs = null;
- try
- {
- String tableNameForQuery = SQLs.TABLE_NAME.toUpperCase();
- rs = connection.getMetaData().getTables( null, null, tableNameForQuery,
- new String[] { "TABLE" } );
- boolean tableExists = rs.next();
- LOGGER.trace( "Found table {}? {}", tableNameForQuery, tableExists );
- return tableExists;
- }
- finally
- {
- SQLUtil.closeQuietly( rs );
- }
- }
-
- @Override
- public Reader getEntityStateReader( ResultSet rs )
- throws SQLException
- {
- return new StringReader( rs.getString( SQLs.ENTITY_STATE_COLUMN_NAME ) );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/PostgreSQLDatabaseSQLServiceMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/PostgreSQLDatabaseSQLServiceMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/PostgreSQLDatabaseSQLServiceMixin.java
deleted file mode 100644
index a4cf014..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/PostgreSQLDatabaseSQLServiceMixin.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.sql.internal;
-
-import java.io.Reader;
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import org.apache.polygene.api.injection.scope.This;
-import org.apache.polygene.library.sql.common.SQLUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public abstract class PostgreSQLDatabaseSQLServiceMixin
- implements DatabaseSQLServiceSpi, DatabaseSQLStringsBuilder, DatabaseSQLService
-{
- private static final Logger LOGGER = LoggerFactory.getLogger( PostgreSQLDatabaseSQLServiceMixin.class );
-
- @This
- protected DatabaseSQLServiceSpi spi;
-
- @Override
- public boolean tableExists( Connection connection )
- throws SQLException
- {
- ResultSet rs = null;
- try
- {
- rs = connection.getMetaData().getTables( null, spi.getCurrentSchemaName(), SQLs.TABLE_NAME,
- new String[] { "TABLE" } );
- boolean tableExists = rs.next();
- LOGGER.trace( "Found table {}? {}", SQLs.TABLE_NAME, tableExists );
- return tableExists;
- }
- finally
- {
- SQLUtil.closeQuietly( rs );
- }
- }
-
- @Override
- public Reader getEntityStateReader( ResultSet rs )
- throws SQLException
- {
- return rs.getCharacterStream( SQLs.ENTITY_STATE_COLUMN_NAME );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/PostgreSQLStringBuilderMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/PostgreSQLStringBuilderMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/PostgreSQLStringBuilderMixin.java
deleted file mode 100644
index b43d1c7..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/PostgreSQLStringBuilderMixin.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-
-package org.apache.polygene.entitystore.sql.internal;
-
-import org.apache.polygene.entitystore.sql.internal.DatabaseSQLStringsBuilder.CommonMixin;
-import org.sql.generation.api.grammar.common.datatypes.SQLDataType;
-import org.sql.generation.api.vendor.PostgreSQLVendor;
-
-/**
- *
- * @author Stanislav Muhametsin
- */
-public class PostgreSQLStringBuilderMixin extends CommonMixin
-{
-
- @Override
- protected SQLDataType getIDType()
- {
- return ((PostgreSQLVendor) this.getVendor()).getDataTypeFactory().text();
- }
-
- @Override
- protected SQLDataType getStateType()
- {
- return ((PostgreSQLVendor) this.getVendor()).getDataTypeFactory().text();
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLEntityState.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLEntityState.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLEntityState.java
deleted file mode 100644
index 2db6f7c..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLEntityState.java
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.sql.internal;
-
-import java.time.Instant;
-import java.util.Objects;
-import org.apache.polygene.api.common.QualifiedName;
-import org.apache.polygene.api.entity.EntityDescriptor;
-import org.apache.polygene.api.entity.EntityReference;
-import org.apache.polygene.spi.entity.EntityState;
-import org.apache.polygene.spi.entity.EntityStatus;
-import org.apache.polygene.spi.entity.ManyAssociationState;
-import org.apache.polygene.spi.entity.NamedAssociationState;
-import org.apache.polygene.spi.entitystore.helpers.DefaultEntityState;
-
-public interface SQLEntityState
- extends EntityState
-{
-
- Long getEntityPK();
-
- Long getEntityOptimisticLock();
-
- DefaultEntityState getDefaultEntityState();
-
- @SuppressWarnings( "PublicInnerClass" )
- public final class DefaultSQLEntityState
- implements SQLEntityState
- {
-
- private final DefaultEntityState state;
-
- private final Long entityPK;
-
- private final Long entityOptimisticLock;
-
- public DefaultSQLEntityState( DefaultEntityState state )
- {
- Objects.requireNonNull( state, "Entity state" );
- this.state = state;
- this.entityPK = null;
- this.entityOptimisticLock = null;
- }
-
- public DefaultSQLEntityState( DefaultEntityState state, Long entityPK, Long entityOptimisticLock )
- {
- Objects.requireNonNull( state, "Entity state" );
- Objects.requireNonNull( entityPK, "Entity PK" );
- Objects.requireNonNull( entityOptimisticLock, "Entity OptimisticLock" );
- this.state = state;
- this.entityPK = entityPK;
- this.entityOptimisticLock = entityOptimisticLock;
- }
-
- @Override
- public Long getEntityPK()
- {
- return entityPK;
- }
-
- @Override
- public Long getEntityOptimisticLock()
- {
- return entityOptimisticLock;
- }
-
- @Override
- public DefaultEntityState getDefaultEntityState()
- {
- return state;
- }
-
- @Override
- public EntityDescriptor entityDescriptor()
- {
- return state.entityDescriptor();
- }
-
- @Override
- public EntityReference associationValueOf( QualifiedName stateName )
- {
- return state.associationValueOf( stateName );
- }
-
- @Override
- public ManyAssociationState manyAssociationValueOf( QualifiedName stateName )
- {
- return state.manyAssociationValueOf( stateName );
- }
-
- @Override
- public NamedAssociationState namedAssociationValueOf( QualifiedName stateName )
- {
- return state.namedAssociationValueOf( stateName );
- }
-
- @Override
- public Object propertyValueOf( QualifiedName stateName )
- {
- return state.propertyValueOf( stateName );
- }
-
- @Override
- public EntityReference entityReference()
- {
- return state.entityReference();
- }
-
- @Override
- public boolean isAssignableTo( Class<?> type )
- {
- return state.isAssignableTo( type );
- }
-
- @Override
- public Instant lastModified()
- {
- return state.lastModified();
- }
-
- @Override
- public void remove()
- {
- state.remove();
- }
-
- @Override
- public void setAssociationValue( QualifiedName stateName, EntityReference newEntity )
- {
- state.setAssociationValue( stateName, newEntity );
- }
-
- @Override
- public void setPropertyValue( QualifiedName stateName, Object json )
- {
- state.setPropertyValue( stateName, json );
- }
-
- @Override
- public EntityStatus status()
- {
- return state.status();
- }
-
- @Override
- public String version()
- {
- return state.version();
- }
-
- @Override
- @SuppressWarnings( "EqualsWhichDoesntCheckParameterClass" )
- public boolean equals( Object obj )
- {
- return state.equals( obj );
- }
-
- @Override
- public int hashCode()
- {
- return state.hashCode();
- }
-
- @Override
- public String toString()
- {
- return state.toString();
- }
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLiteDatabaseSQLServiceMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLiteDatabaseSQLServiceMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLiteDatabaseSQLServiceMixin.java
deleted file mode 100644
index d762f8b..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLiteDatabaseSQLServiceMixin.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.sql.internal;
-
-import java.io.Reader;
-import java.io.StringReader;
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import org.apache.polygene.api.injection.scope.This;
-import org.apache.polygene.library.sql.common.SQLUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public abstract class SQLiteDatabaseSQLServiceMixin
- implements DatabaseSQLService, DatabaseSQLStringsBuilder, DatabaseSQLServiceSpi
-{
- private static final Logger LOGGER = LoggerFactory.getLogger( SQLiteDatabaseSQLServiceMixin.class );
-
- @This
- protected DatabaseSQLServiceSpi spi;
-
- @Override
- public boolean tableExists( Connection connection )
- throws SQLException
- {
- ResultSet rs = null;
- try
- {
- String tableNameForQuery = SQLs.TABLE_NAME.toUpperCase();
- rs = connection.getMetaData().getTables( null, null, tableNameForQuery,
- new String[] { "TABLE" } );
- boolean tableExists = rs.next();
- LOGGER.trace( "Found table {}? {}", tableNameForQuery, tableExists );
- return tableExists;
- }
- finally
- {
- SQLUtil.closeQuietly( rs );
- }
- }
-
- @Override
- public Reader getEntityStateReader( ResultSet rs )
- throws SQLException
- {
- return new StringReader( rs.getString( SQLs.ENTITY_STATE_COLUMN_NAME ) );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLs.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLs.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLs.java
deleted file mode 100644
index 8555a5d..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLs.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.sql.internal;
-
-public interface SQLs
-{
- String DEFAULT_SCHEMA_NAME = "POLYGENE_ES";
- String TABLE_NAME = "POLYGENE_ENTITIES";
- String ENTITY_IDENTITY_COLUMN_NAME = "ENTITY_IDENTITY";
- String ENTITY_VERSION_COLUMN_NAME = "ENTITY_VERSION";
- String ENTITY_STATE_COLUMN_NAME = "ENTITY_STATE";
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/package.html
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/package.html b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/package.html
deleted file mode 100644
index 508f1fc..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/package.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one
- ~ or more contributor license agreements. See the NOTICE file
- ~ distributed with this work for additional information
- ~ regarding copyright ownership. The ASF licenses this file
- ~ to you under the Apache License, Version 2.0 (the
- ~ "License"); you may not use this file except in compliance
- ~ with the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- ~
- ~
- -->
-<html>
- <body>
- <h2>SQL EntityStore Internal Package.</h2>
- </body>
-</html>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/main/resources/org/apache/polygene/entitystore/sql/changelog.xml
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/resources/org/apache/polygene/entitystore/sql/changelog.xml b/extensions/entitystore-sql/src/main/resources/org/apache/polygene/entitystore/sql/changelog.xml
new file mode 100644
index 0000000..47ef554
--- /dev/null
+++ b/extensions/entitystore-sql/src/main/resources/org/apache/polygene/entitystore/sql/changelog.xml
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+<databaseChangeLog
+ xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.0.xsd"
+ objectQuotingStrategy="QUOTE_ALL_OBJECTS">
+ <changeSet id="0" author="paul">
+ <createTable tableName="${es-sql.table}">
+ <column name="ENTITY_IDENTITY" type="varchar(64)">
+ <constraints primaryKey="true" nullable="false"/>
+ </column>
+ <column name="ENTITY_VERSION" type="varchar(64)">
+ <constraints nullable="false"/>
+ </column>
+ <column name="ENTITY_STATE" type="varchar(10240)">
+ <constraints nullable="false"/>
+ </column>
+ </createTable>
+ </changeSet>
+</databaseChangeLog>
[47/50] [abbrv] polygene-java git commit: Trigger UoW completion in
AbstractValueCompositeSerializationTest
Posted by pa...@apache.org.
Trigger UoW completion in AbstractValueCompositeSerializationTest
Add complex value composite in entity under test.
Exercise entity state serialization in test.
POLYGENE-231
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/0a23e9f7
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/0a23e9f7
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/0a23e9f7
Branch: refs/heads/serialization-3.0
Commit: 0a23e9f750691e3170ed3070b3fae1b98ed1c41b
Parents: a94e465
Author: Paul Merlin <pa...@apache.org>
Authored: Mon Mar 13 09:10:29 2017 +0100
Committer: Paul Merlin <pa...@apache.org>
Committed: Mon Mar 13 11:24:42 2017 +0100
----------------------------------------------------------------------
...AbstractValueCompositeSerializationTest.java | 50 ++++++++++++--------
1 file changed, 30 insertions(+), 20 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/0a23e9f7/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
index a0975ee..2642198 100644
--- a/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
+++ b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
@@ -50,7 +50,6 @@ import org.apache.polygene.api.structure.Module;
import org.apache.polygene.api.unitofwork.UnitOfWork;
import org.apache.polygene.api.value.ValueBuilder;
import org.apache.polygene.api.value.ValueComposite;
-import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.test.AbstractPolygeneTest;
import org.apache.polygene.test.EntityTestAssembler;
@@ -89,12 +88,8 @@ public abstract class AbstractValueCompositeSerializationTest
System.out.println( "# END " + testName.getMethodName() );
}
- @Structure
- protected Module moduleInstance;
-
@Override
public void assemble( ModuleAssembly module )
- throws AssemblyException
{
module.values( Some.class, SomeExtended.class, SomeShuffled.class,
AnotherValue.class, FooValue.class, CustomFooValue.class,
@@ -104,6 +99,9 @@ public abstract class AbstractValueCompositeSerializationTest
module.entities( Some.class, BarEntity.class );
}
+ @Structure
+ protected Module moduleInstance;
+
@Service
protected Serialization serialization;
@@ -141,6 +139,8 @@ public abstract class AbstractValueCompositeSerializationTest
is( true ) );
assertThat( "Value equality", some, equalTo( some2 ) );
+
+ uow.complete();
}
}
@@ -156,6 +156,8 @@ public abstract class AbstractValueCompositeSerializationTest
Some deserialized = serialization.deserialize( module, Some.class, serialized );
System.out.println( deserialized );
+
+ uow.complete();
}
}
@@ -171,6 +173,8 @@ public abstract class AbstractValueCompositeSerializationTest
SomeExtended deserialized = serialization.deserialize( module, SomeExtended.class, serialized );
System.out.println( deserialized );
+
+ uow.complete();
}
}
@@ -196,6 +200,8 @@ public abstract class AbstractValueCompositeSerializationTest
serialization.deserialize( module, SomeExtended.class, serialized );
System.out.println( deserialized );
+
+ uow.complete();
}
}
@@ -268,9 +274,9 @@ public abstract class AbstractValueCompositeSerializationTest
proto.identity().set( StringIdentity.fromString( identity ) );
setSomeValueState( module, uow, proto );
proto.extraProperty().set( "extra property" );
- proto.extraAssociation().set( buildBarEntity( uow, "extra association" ) );
- proto.extraManyAssociation().add( buildBarEntity( uow, "extra many association" ) );
- proto.extraNamedAssociation().put( "extra", buildBarEntity( uow, "extra named association" ) );
+ proto.extraAssociation().set( buildBarEntity( module, uow, "extra association" ) );
+ proto.extraManyAssociation().add( buildBarEntity( module, uow, "extra many association" ) );
+ proto.extraNamedAssociation().put( "extra", buildBarEntity( module, uow, "extra named association" ) );
return builder.newInstance();
}
@@ -314,7 +320,7 @@ public abstract class AbstractValueCompositeSerializationTest
// maintain a certain order but it's not the case on some JVMs. On OpenJDK 8 they are reversed for example.
// This should not be enforced tough as both the Map API and the JSON specification state that name-value pairs
// are unordered.
- // As a consequence this test should be enhanced to be Map order independant.
+ // As a consequence this test should be enhanced to be Map order independent.
//
// proto.stringIntMap().get().put( "bar", 67 );
@@ -330,18 +336,19 @@ public abstract class AbstractValueCompositeSerializationTest
some.customFooValue().set( module.newValue( CustomFooValue.class ) );
// NestedEntities
- some.barAssociation().set( buildBarEntity( uow, "bazar in barAssociation" ) );
- some.barEntityAssociation().set( buildBarEntity( uow, "bazar in barEntityAssociation" ) );
- some.barManyAssociation().add( buildBarEntity( uow, "bazar ONE in barManyAssociation" ) );
- some.barManyAssociation().add( buildBarEntity( uow, "bazar TWO in barManyAssociation" ) );
- some.barEntityManyAssociation().add( buildBarEntity( uow, "bazar ONE in barEntityManyAssociation" ) );
- some.barEntityManyAssociation().add( buildBarEntity( uow, "bazar TWO in barEntityManyAssociation" ) );
- some.barNamedAssociation().put( "bazar", buildBarEntity( uow, "bazar in barNamedAssociation" ) );
- some.barNamedAssociation().put( "cathedral", buildBarEntity( uow, "cathedral in barNamedAssociation" ) );
+ some.barAssociation().set( buildBarEntity( module, uow, "bazar in barAssociation" ) );
+ some.barEntityAssociation().set( buildBarEntity( module, uow, "bazar in barEntityAssociation" ) );
+ some.barManyAssociation().add( buildBarEntity( module, uow, "bazar ONE in barManyAssociation" ) );
+ some.barManyAssociation().add( buildBarEntity( module, uow, "bazar TWO in barManyAssociation" ) );
+ some.barEntityManyAssociation().add( buildBarEntity( module, uow, "bazar ONE in barEntityManyAssociation" ) );
+ some.barEntityManyAssociation().add( buildBarEntity( module, uow, "bazar TWO in barEntityManyAssociation" ) );
+ some.barNamedAssociation().put( "bazar", buildBarEntity( module, uow, "bazar in barNamedAssociation" ) );
+ some.barNamedAssociation().put( "cathedral",
+ buildBarEntity( module, uow, "cathedral in barNamedAssociation" ) );
some.barEntityNamedAssociation().put( "bazar",
- buildBarEntity( uow, "bazar in barEntityNamedAssociation" ) );
+ buildBarEntity( module, uow, "bazar in barEntityNamedAssociation" ) );
some.barEntityNamedAssociation().put( "cathedral",
- buildBarEntity( uow, "cathedral in barEntityNamedAssociation" ) );
+ buildBarEntity( module, uow, "cathedral in barEntityNamedAssociation" ) );
}
private static AnotherValue createAnotherValue( Module module, String val1, String val2 )
@@ -352,10 +359,11 @@ public abstract class AbstractValueCompositeSerializationTest
return valueBuilder.newInstance();
}
- private static BarEntity buildBarEntity( UnitOfWork uow, String cathedral )
+ private static BarEntity buildBarEntity( Module module, UnitOfWork uow, String cathedral )
{
EntityBuilder<BarEntity> barBuilder = uow.newEntityBuilder( BarEntity.class );
barBuilder.instance().cathedral().set( cathedral );
+ barBuilder.instance().another().set( createAnotherValue( module, "nested", "value" ) );
return barBuilder.newInstance();
}
@@ -574,6 +582,8 @@ public abstract class AbstractValueCompositeSerializationTest
{
@UseDefaults
Property<String> cathedral();
+
+ Property<AnotherValue> another();
}
public interface BarEntity
[33/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/test/java/org/apache/polygene/api/value/DocumentationSupport.java
----------------------------------------------------------------------
diff --git a/core/api/src/test/java/org/apache/polygene/api/value/DocumentationSupport.java b/core/api/src/test/java/org/apache/polygene/api/value/DocumentationSupport.java
index c822f68..4de963b 100644
--- a/core/api/src/test/java/org/apache/polygene/api/value/DocumentationSupport.java
+++ b/core/api/src/test/java/org/apache/polygene/api/value/DocumentationSupport.java
@@ -19,11 +19,7 @@
*/
package org.apache.polygene.api.value;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
@@ -32,16 +28,16 @@ import java.util.function.Function;
import java.util.stream.Stream;
import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.property.Property;
+import org.apache.polygene.api.serialization.Deserializer;
+import org.apache.polygene.api.serialization.Serialization;
+import org.apache.polygene.api.serialization.Serializer;
import org.apache.polygene.api.structure.Application;
import org.apache.polygene.api.structure.Module;
-import org.apache.polygene.api.type.CollectionType;
import org.apache.polygene.bootstrap.Assembler;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.Energy4Java;
import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
import org.apache.polygene.test.AbstractPolygeneTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.junit.Test;
import static java.util.stream.Collectors.toList;
@@ -52,17 +48,14 @@ import static org.junit.Assert.assertThat;
* Snippets:
* - default : default ValueSerialization
* - service : assembled service ValueSerialization
- * - lookup : ValueSerialization values module finder
+ * - io : i/o usage
*/
-public class DocumentationSupport
- extends AbstractPolygeneTest
+public class DocumentationSupport extends AbstractPolygeneTest
{
-
// START SNIPPET: default
// START SNIPPET: service
public interface SomeValue // (1)
{
-
Property<String> foo();
}
@@ -71,10 +64,6 @@ public class DocumentationSupport
throws AssemblyException
{
module.values( SomeValue.class ); // (2)
- // END SNIPPET: default
- new OrgJsonValueSerializationAssembler().assemble( module ); // (3)
- new DefaultUnitOfWorkAssembler().assemble( module );
- // START SNIPPET: default
}
// END SNIPPET: default
// END SNIPPET: service
@@ -97,9 +86,9 @@ public class DocumentationSupport
// END SNIPPET: default
// START SNIPPET: service
@Service
- private ValueSerializer valueSerializer; // (4)
+ private Serializer serializer; // (4)
@Service
- private ValueDeserializer valueDeserializer; // (4)
+ private Deserializer deserializer; // (4)
// END SNIPPET: service
@Test
@@ -107,8 +96,8 @@ public class DocumentationSupport
public void assembledDefaultServiceSerialization()
{
SomeValue someValue = someNewValueInstance(); // (5)
- String json = valueSerializer.serialize( someValue ); // (6)
- SomeValue someNewValue = valueDeserializer.deserialize( module, SomeValue.class, json ); // (7)
+ String json = serializer.serialize( someValue ); // (6)
+ SomeValue someNewValue = deserializer.deserialize( module, SomeValue.class, json ); // (7)
// END SNIPPET: service
assertThat( json, equalTo( "{\"foo\":\"bar\"}" ) );
@@ -120,46 +109,11 @@ public class DocumentationSupport
static enum AcmeValue
{
-
- foo, bar
+ foo,
+ bar
}
@Test
- // START SNIPPET: stream
- public void assembledServiceStreamingSerialization()
- {
- // END SNIPPET: stream
-
- List<AcmeValue> dataSource = Arrays.asList( AcmeValue.values() );
- ByteArrayOutputStream targetStream = new ByteArrayOutputStream();
-
- // START SNIPPET: stream
- // (1)
- Iterable<AcmeValue> data = dataSource; // Eg. Entities converted to Values
- OutputStream output = targetStream; // Eg. streaming JSON over HTTP
-
- // (2)
- valueSerializer.serialize( data, output );
- // END SNIPPET: stream
-
- byte[] serialized = targetStream.toByteArray();
- ByteArrayInputStream sourceStream = new ByteArrayInputStream( serialized );
-
- // START SNIPPET: stream
- // (3)
- InputStream input = sourceStream; // Eg. reading incoming JSON
-
- // (4)
- List<AcmeValue> values = valueDeserializer.deserialize( module, CollectionType.listOf( AcmeValue.class ), input );
- // END SNIPPET: stream
-
- assertThat( values, equalTo( dataSource ) );
-
- // START SNIPPET: stream
- }
- // END SNIPPET: stream
-
- @Test
// START SNIPPET: io
public void assembledServiceIOSerialization()
throws IOException
@@ -177,7 +131,7 @@ public class DocumentationSupport
Stream<AcmeValue> queryResult = dataSource.stream();
// (2)
- Function<AcmeValue, String> serialize = valueSerializer.serialize();
+ Function<AcmeValue, String> serialize = serializer.serializeFunction();
// (3)
// Eg. pipe data to another process or to a file
@@ -193,7 +147,7 @@ public class DocumentationSupport
Stream<String> lines = input.stream();
// (5)
- Function<String, AcmeValue> deserialize = valueDeserializer.deserialize( module, AcmeValue.class );
+ Function<String, AcmeValue> deserialize = deserializer.deserializeFunction( module, AcmeValue.class );
// Deserialization of a collection of AcmeValue from a String.
// One serialized AcmeValue per line.
@@ -209,47 +163,44 @@ public class DocumentationSupport
@Test
// TODO Move to SPI !
- // TODO Include in each ValueSerialization extensions documentation
+ // TODO Include in each Serialization extensions documentation
public void assembledWithValuesModuleSerialization()
throws Exception
{
- Application app = new Energy4Java().newApplication( applicationFactory -> {
- Assembler[][][] pancakes = new Assembler[][][]
- {
+ Application app = new Energy4Java().newApplication(
+ applicationFactory ->
+ {
+ Assembler[][][] pancakes = new Assembler[][][]
{
{
- valuesModule -> {
- valuesModule.layer().setName( "SINGLE-Layer" );
- valuesModule.setName( "VALUES-Module" );
-
- valuesModule.values( SomeValue.class );
- new DefaultUnitOfWorkAssembler().assemble( valuesModule );
- }
- },
- {
- servicesModule -> {
- servicesModule.setName( "SERVICES-Module" );
- new OrgJsonValueSerializationAssembler().
- assemble( servicesModule );
+ {
+ valuesModule ->
+ {
+ valuesModule.layer().setName( "SINGLE-Layer" );
+ valuesModule.setName( "VALUES-Module" );
+
+ valuesModule.values( SomeValue.class );
+ }
+ },
+ {
+ servicesModule -> servicesModule.setName( "SERVICES-Module" )
}
}
- }
- };
- return applicationFactory.newApplicationAssembly( pancakes );
- } );
+ };
+ return applicationFactory.newApplicationAssembly( pancakes );
+ } );
app.activate();
try
{
- Module valuesModule = app.findModule( "SINGLE-Layer", "VALUES-Module" );
SomeValue someValue = someNewValueInstance();
Module servicesModule = app.findModule( "SINGLE-Layer", "SERVICES-Module" );
- ValueSerialization valueSerialization = servicesModule.findService( ValueSerialization.class ).get();
+ Serialization stateSerialization = servicesModule.findService( Serialization.class ).get();
- String json = valueSerialization.serialize( someValue );
+ String json = stateSerialization.serialize( someValue );
assertThat( json, equalTo( "{\"foo\":\"bar\"}" ) );
- SomeValue someNewValue = valueSerialization.deserialize( module, SomeValue.class, json );
+ SomeValue someNewValue = stateSerialization.deserialize( module, SomeValue.class, json );
assertThat( someNewValue, equalTo( someValue ) );
}
finally
@@ -258,7 +209,7 @@ public class DocumentationSupport
}
}
- private SomeValue someNewValueInstance( )
+ private SomeValue someNewValueInstance()
{
ValueBuilder<SomeValue> builder = valueBuilderFactory.newValueBuilder( SomeValue.class );
builder.prototype().foo().set( "bar" );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/test/resources/org/apache/polygene/api/configuration/MyService.properties
----------------------------------------------------------------------
diff --git a/core/api/src/test/resources/org/apache/polygene/api/configuration/MyService.properties b/core/api/src/test/resources/org/apache/polygene/api/configuration/MyService.properties
index 600ed6f..c0639c1 100644
--- a/core/api/src/test/resources/org/apache/polygene/api/configuration/MyService.properties
+++ b/core/api/src/test/resources/org/apache/polygene/api/configuration/MyService.properties
@@ -18,4 +18,4 @@
#
#
-me = { name : Niclas, address={ street1 : "Henan Lu 555", street2 : "Block 15", city : { cityName : "Shanghai", country : { countryName : "China" } } } }
\ No newline at end of file
+me = { "name" : "Niclas", "address" : { "street1" : "Henan Lu 555", "street2" : "Block 15", "city" : { "cityName" : "Shanghai", "country" : { "countryName" : "China" } } } }
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/bootstrap/src/main/java/org/apache/polygene/bootstrap/builder/ApplicationBuilder.java
----------------------------------------------------------------------
diff --git a/core/bootstrap/src/main/java/org/apache/polygene/bootstrap/builder/ApplicationBuilder.java b/core/bootstrap/src/main/java/org/apache/polygene/bootstrap/builder/ApplicationBuilder.java
index 3a064e5..6159686 100644
--- a/core/bootstrap/src/main/java/org/apache/polygene/bootstrap/builder/ApplicationBuilder.java
+++ b/core/bootstrap/src/main/java/org/apache/polygene/bootstrap/builder/ApplicationBuilder.java
@@ -20,14 +20,16 @@
package org.apache.polygene.bootstrap.builder;
import java.io.InputStream;
+import java.io.StringReader;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.Scanner;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.Json;
+import javax.json.JsonArray;
+import javax.json.JsonObject;
+import javax.json.JsonValue;
import org.apache.polygene.api.activation.ActivationEventListener;
import org.apache.polygene.api.activation.ActivationEventListenerRegistration;
import org.apache.polygene.api.activation.ActivationException;
@@ -74,10 +76,7 @@ public class ApplicationBuilder
public ApplicationBuilder metaInfo( Object... metaInfos )
{
- for( Object metaInfo : metaInfos )
- {
- this.metaInfos.add( metaInfo );
- }
+ Collections.addAll( this.metaInfos, metaInfos );
return this;
}
@@ -199,13 +198,11 @@ public class ApplicationBuilder
* Load an ApplicationBuilder from a JSON String.
* @param json JSON String
* @return Application Builder loaded from JSON
- * @throws JSONException if unable to read JSON
* @throws AssemblyException if unable to declare the assembly
*/
public static ApplicationBuilder fromJson( String json )
- throws JSONException, AssemblyException
{
- JSONObject root = new JSONObject( json );
+ JsonObject root = Json.createReader( new StringReader( json ) ).readObject();
return fromJson( root );
}
@@ -213,25 +210,23 @@ public class ApplicationBuilder
* Load an ApplicationBuilder from a JSON InputStream.
* @param json JSON input
* @return Application Builder loaded from JSON
- * @throws JSONException if unable to read JSON
* @throws AssemblyException if unable to declare the assembly
*/
public static ApplicationBuilder fromJson( InputStream json )
- throws JSONException, AssemblyException
+ throws AssemblyException
{
- String jsonString = new Scanner( json, "UTF-8" ).useDelimiter( "\\A" ).next();
- return fromJson( jsonString );
+ JsonObject root = Json.createReader( json ).readObject();
+ return fromJson( root );
}
/**
* Load an ApplicationBuilder from a JSONObject.
* @param root JSON object
* @return Application Builder loaded from JSON
- * @throws JSONException if unable to read JSON
* @throws AssemblyException if unable to declare the assembly
*/
- public static ApplicationBuilder fromJson( JSONObject root )
- throws JSONException, AssemblyException
+ public static ApplicationBuilder fromJson( JsonObject root )
+ throws AssemblyException
{
String applicationName = root.getString( "name" );
ApplicationBuilder builder = new ApplicationBuilder( applicationName );
@@ -242,40 +237,43 @@ public class ApplicationBuilder
/** Configures the application struucture from a JSON document.
*
* @param root The JSON document root.
- * @throws JSONException if the JSON document isn't valid.
* @throws AssemblyException if probelms in the Assemblers provided in the JSON document.
*/
- protected void configureWithJson( JSONObject root )
- throws JSONException, AssemblyException
+ protected void configureWithJson( JsonObject root )
+ throws AssemblyException
{
- JSONArray layers = root.optJSONArray( "layers" );
- if( layers != null )
+ JsonValue optLayers = root.get( "layers" );
+ if( optLayers != null && optLayers.getValueType() == JsonValue.ValueType.ARRAY )
{
- for( int i = 0; i < layers.length(); i++ )
+ JsonArray layers = (JsonArray) optLayers;
+ for( int i = 0; i < layers.size(); i++ )
{
- JSONObject layerObject = layers.getJSONObject( i );
+ JsonObject layerObject = layers.getJsonObject( i );
String layerName = layerObject.getString( "name" );
LayerDeclaration layerDeclaration = withLayer( layerName );
- JSONArray using = layerObject.optJSONArray( "uses" );
- if( using != null )
+ JsonValue optUsing = layerObject.get( "uses" );
+ if( optUsing != null && optUsing.getValueType() == JsonValue.ValueType.ARRAY )
{
- for( int j = 0; j < using.length(); j++ )
+ JsonArray using = (JsonArray) optUsing;
+ for( int j = 0; j < using.size(); j++ )
{
layerDeclaration.using( using.getString( j ) );
}
}
- JSONArray modules = layerObject.optJSONArray( "modules" );
- if( modules != null )
+ JsonValue optModules = layerObject.get( "modules" );
+ if( optModules != null && optModules.getValueType() == JsonValue.ValueType.ARRAY )
{
- for( int k = 0; k < modules.length(); k++ )
+ JsonArray modules = (JsonArray) optModules;
+ for( int k = 0; k < modules.size(); k++ )
{
- JSONObject moduleObject = modules.getJSONObject( k );
+ JsonObject moduleObject = modules.getJsonObject( k );
String moduleName = moduleObject.getString( "name" );
ModuleDeclaration moduleDeclaration = layerDeclaration.withModule( moduleName );
- JSONArray assemblers = moduleObject.optJSONArray( "assemblers" );
- if( assemblers != null )
+ JsonValue optAssemblers = moduleObject.get( "assemblers" );
+ if( optAssemblers != null && optAssemblers.getValueType() == JsonValue.ValueType.ARRAY )
{
- for( int m = 0; m < assemblers.length(); m++ )
+ JsonArray assemblers = (JsonArray) optAssemblers;
+ for( int m = 0; m < assemblers.size(); m++ )
{
String string = assemblers.getString( m );
moduleDeclaration.withAssembler( string );
@@ -291,12 +289,11 @@ public class ApplicationBuilder
* {@literal main} method that read JSON from STDIN.
* <p>Passivation exceptions are written to STDERR if any.</p>
* @param args Unused
- * @throws JSONException if unable to read JSON
* @throws AssemblyException if the assembly failed
* @throws ActivationException if the activation failed
*/
public static void main( String[] args )
- throws JSONException, ActivationException, AssemblyException
+ throws ActivationException, AssemblyException
{
fromJson( System.in ).withPassivationShutdownHook().newApplication();
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/bootstrap/src/main/java/org/apache/polygene/bootstrap/serialization/DefaultSerializationAssembler.java
----------------------------------------------------------------------
diff --git a/core/bootstrap/src/main/java/org/apache/polygene/bootstrap/serialization/DefaultSerializationAssembler.java b/core/bootstrap/src/main/java/org/apache/polygene/bootstrap/serialization/DefaultSerializationAssembler.java
new file mode 100644
index 0000000..9b877cc
--- /dev/null
+++ b/core/bootstrap/src/main/java/org/apache/polygene/bootstrap/serialization/DefaultSerializationAssembler.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.bootstrap.serialization;
+
+import org.apache.polygene.api.serialization.Deserializer;
+import org.apache.polygene.api.serialization.Serialization;
+import org.apache.polygene.api.serialization.Serializer;
+import org.apache.polygene.bootstrap.Assembler;
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.serialization.javaxjson.JavaxJsonSerializationService;
+import org.apache.polygene.spi.serialization.JsonDeserializer;
+import org.apache.polygene.spi.serialization.JsonSerialization;
+import org.apache.polygene.spi.serialization.JsonSerializer;
+
+public class DefaultSerializationAssembler
+ implements Assembler
+{
+ @Override
+ public void assemble( ModuleAssembly module ) throws AssemblyException
+ {
+ module.services( JavaxJsonSerializationService.class )
+ .withTypes( Serialization.class, Serializer.class, Deserializer.class,
+ JsonSerialization.class, JsonSerializer.class, JsonDeserializer.class )
+ .taggedWith( Serialization.Formats.JSON );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/bootstrap/src/test/java/org/apache/polygene/bootstrap/builder/ApplicationBuilderTest.java
----------------------------------------------------------------------
diff --git a/core/bootstrap/src/test/java/org/apache/polygene/bootstrap/builder/ApplicationBuilderTest.java b/core/bootstrap/src/test/java/org/apache/polygene/bootstrap/builder/ApplicationBuilderTest.java
index d0ca6e5..c7c1e6c 100644
--- a/core/bootstrap/src/test/java/org/apache/polygene/bootstrap/builder/ApplicationBuilderTest.java
+++ b/core/bootstrap/src/test/java/org/apache/polygene/bootstrap/builder/ApplicationBuilderTest.java
@@ -29,7 +29,6 @@ import org.apache.polygene.api.structure.Module;
import org.apache.polygene.bootstrap.Assembler;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.json.JSONException;
import org.junit.Test;
import static java.util.stream.Collectors.toList;
@@ -59,7 +58,7 @@ public class ApplicationBuilderTest
@Test
public void givenJsonWhenBuildingApplicationExpectSuccess()
- throws JSONException, ActivationException, AssemblyException
+ throws ActivationException, AssemblyException
{
ApplicationBuilder builder = ApplicationBuilder.fromJson( APPLICATION );
Application application = builder.newApplication();
@@ -70,7 +69,7 @@ public class ApplicationBuilderTest
@Test
public void givenJsonInputStreamWhenBuildingApplicationExpectSuccess()
- throws IOException, JSONException, ActivationException, AssemblyException
+ throws IOException, ActivationException, AssemblyException
{
InputStream input = new ByteArrayInputStream( APPLICATION.getBytes( "UTF-8" ) );
ApplicationBuilder builder = ApplicationBuilder.fromJson( input );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/main/java/org/apache/polygene/runtime/bootstrap/ModuleAssemblyImpl.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/polygene/runtime/bootstrap/ModuleAssemblyImpl.java b/core/runtime/src/main/java/org/apache/polygene/runtime/bootstrap/ModuleAssemblyImpl.java
index 62220a6..43478bf 100644
--- a/core/runtime/src/main/java/org/apache/polygene/runtime/bootstrap/ModuleAssemblyImpl.java
+++ b/core/runtime/src/main/java/org/apache/polygene/runtime/bootstrap/ModuleAssemblyImpl.java
@@ -40,10 +40,11 @@ import org.apache.polygene.api.identity.HasIdentity;
import org.apache.polygene.api.identity.Identity;
import org.apache.polygene.api.identity.IdentityGenerator;
import org.apache.polygene.api.identity.StringIdentity;
+import org.apache.polygene.api.serialization.Serialization;
import org.apache.polygene.api.service.DuplicateServiceIdentityException;
import org.apache.polygene.api.structure.Module;
+import org.apache.polygene.api.type.HasEqualOrAssignableFromType;
import org.apache.polygene.api.type.HasTypes;
-import org.apache.polygene.api.type.MatchTypeSpecification;
import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
import org.apache.polygene.api.value.ValueComposite;
import org.apache.polygene.bootstrap.Assembler;
@@ -68,6 +69,7 @@ import org.apache.polygene.bootstrap.TransientDeclaration;
import org.apache.polygene.bootstrap.ValueAssembly;
import org.apache.polygene.bootstrap.ValueDeclaration;
import org.apache.polygene.bootstrap.identity.DefaultIdentityGeneratorAssembler;
+import org.apache.polygene.bootstrap.serialization.DefaultSerializationAssembler;
import org.apache.polygene.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
import org.apache.polygene.runtime.activation.ActivatorsModel;
import org.apache.polygene.runtime.composite.TransientModel;
@@ -119,8 +121,9 @@ final class ModuleAssemblyImpl
static
{
defaultAssemblers = new HashMap<>();
- defaultAssemblers.put(UnitOfWorkFactory.class, new DefaultUnitOfWorkAssembler());
- defaultAssemblers.put(IdentityGenerator.class, new DefaultIdentityGeneratorAssembler());
+ defaultAssemblers.put( UnitOfWorkFactory.class, new DefaultUnitOfWorkAssembler() );
+ defaultAssemblers.put( IdentityGenerator.class, new DefaultIdentityGeneratorAssembler() );
+ defaultAssemblers.put( Serialization.class, new DefaultSerializationAssembler() );
}
ModuleAssemblyImpl(LayerAssembly layerAssembly, String name)
@@ -307,27 +310,27 @@ final class ModuleAssemblyImpl
}
@Override
- public ConfigurationDeclaration configurations(Predicate<HasTypes> specification)
+ public ConfigurationDeclaration configurations( Predicate<HasTypes> specification )
{
- Predicate<HasTypes> isConfigurationComposite = new MatchTypeSpecification(HasIdentity.class);
- specification = specification.and(isConfigurationComposite);
- List<EntityAssemblyImpl> entityAssmblyList = new ArrayList<>();
- for (EntityAssemblyImpl entityAssembly : entityAssemblies.values())
+ Predicate<HasTypes> isConfigurationComposite = new HasEqualOrAssignableFromType<>( HasIdentity.class );
+ specification = specification.and( isConfigurationComposite );
+ List<EntityAssemblyImpl> entityAssemblyList = new ArrayList<>();
+ for( EntityAssemblyImpl entityAssembly : entityAssemblies.values() )
{
- if (specification.test(entityAssembly))
+ if( specification.test( entityAssembly ) )
{
- entityAssmblyList.add(entityAssembly);
+ entityAssemblyList.add( entityAssembly );
}
}
List<ValueAssemblyImpl> valueAssemblyList = new ArrayList<>();
- for (ValueAssemblyImpl transientAssembly : valueAssemblies.values())
+ for( ValueAssemblyImpl transientAssembly : valueAssemblies.values() )
{
- if (specification.test(transientAssembly))
+ if( specification.test( transientAssembly ) )
{
- valueAssemblyList.add(transientAssembly);
+ valueAssemblyList.add( transientAssembly );
}
}
- return new ConfigurationDeclarationImpl(entityAssmblyList, valueAssemblyList);
+ return new ConfigurationDeclarationImpl( entityAssemblyList, valueAssemblyList );
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/main/java/org/apache/polygene/runtime/property/PropertyModel.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/polygene/runtime/property/PropertyModel.java b/core/runtime/src/main/java/org/apache/polygene/runtime/property/PropertyModel.java
index 565b218..64a7b77 100644
--- a/core/runtime/src/main/java/org/apache/polygene/runtime/property/PropertyModel.java
+++ b/core/runtime/src/main/java/org/apache/polygene/runtime/property/PropertyModel.java
@@ -39,22 +39,20 @@ import org.apache.polygene.api.property.InitialValueProvider;
import org.apache.polygene.api.property.InvalidPropertyTypeException;
import org.apache.polygene.api.property.Property;
import org.apache.polygene.api.property.PropertyDescriptor;
-import org.apache.polygene.api.service.NoSuchServiceException;
import org.apache.polygene.api.structure.Module;
+import org.apache.polygene.api.serialization.Deserializer;
+import org.apache.polygene.api.service.ServiceFinder;
import org.apache.polygene.api.structure.ModuleDescriptor;
-import org.apache.polygene.api.type.Serialization;
import org.apache.polygene.api.type.ValueCompositeType;
import org.apache.polygene.api.type.ValueType;
import org.apache.polygene.api.util.Classes;
-import org.apache.polygene.api.value.MissingValueSerializationException;
-import org.apache.polygene.api.value.ValueDeserializer;
import org.apache.polygene.api.util.Visitable;
import org.apache.polygene.api.util.Visitor;
import org.apache.polygene.bootstrap.BindingException;
import org.apache.polygene.runtime.composite.ValueConstraintsInstance;
import org.apache.polygene.runtime.model.Binder;
import org.apache.polygene.runtime.model.Resolution;
-import org.apache.polygene.runtime.types.ValueTypeFactory;
+import org.apache.polygene.runtime.type.ValueTypeFactoryInstance;
/**
* Model for a Property.
@@ -187,11 +185,10 @@ public class PropertyModel
public void bind( Resolution resolution )
throws BindingException
{
- ValueTypeFactory factory = ValueTypeFactory.instance();
+ ValueTypeFactoryInstance factory = ValueTypeFactoryInstance.instance();
Class<?> declaringClass = ( (Member) accessor() ).getDeclaringClass();
Class<?> mainType = resolution.model().types().findFirst().orElse( null );
- Serialization.Variant variant = findVariant();
- valueType = factory.newValueType( type(), declaringClass, mainType, resolution.layer(), resolution.module(), variant );
+ valueType = factory.newValueType( type(), declaringClass, mainType, resolution.module() );
builderInfo = new BuilderPropertyInfo();
if( type instanceof TypeVariable )
{
@@ -199,21 +196,6 @@ public class PropertyModel
}
}
- private Serialization.Variant findVariant()
- {
- Serialization serialization = metaInfo.get( Serialization.class );
- Serialization.Variant variant = null;
- if( serialization != null )
- {
- variant = serialization.value();
- }
- if( variant == null )
- {
- variant = Serialization.Variant.entry;
- }
- return variant;
- }
-
@Override
public <ThrowableType extends Throwable> boolean accept( Visitor<? super PropertyModel, ThrowableType> visitor )
throws ThrowableType
@@ -356,21 +338,11 @@ public class PropertyModel
Class<?> propertyType = valueType().types().findFirst().orElse( null );
if( value instanceof String && !propertyType.equals( String.class ) )
{
- try
- {
- // here we could possibly deserialize json to other types...
- ValueDeserializer deserializer = module.instance()
- .serviceFinder()
- .findService( ValueDeserializer.class )
- .get();
- if( deserializer != null )
- {
- value = deserializer.deserialize( module, propertyType ).apply( (String) value );
- }
- }
- catch( NoSuchServiceException e )
+ ServiceFinder serviceFinder = module.instance().serviceFinder();
+ Deserializer deserializer = serviceFinder.findService( Deserializer.class ).get();
+ if( deserializer != null )
{
- throw new MissingValueSerializationException( "@UseDefaults with initialization value requires that there is a visible ValueDeserializer service available.", e);
+ value = deserializer.deserialize( module, valueType, (String) value );
}
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/main/java/org/apache/polygene/runtime/structure/ModuleInstance.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/polygene/runtime/structure/ModuleInstance.java b/core/runtime/src/main/java/org/apache/polygene/runtime/structure/ModuleInstance.java
index 246f0ab..64b5f72 100644
--- a/core/runtime/src/main/java/org/apache/polygene/runtime/structure/ModuleInstance.java
+++ b/core/runtime/src/main/java/org/apache/polygene/runtime/structure/ModuleInstance.java
@@ -51,6 +51,8 @@ import org.apache.polygene.api.property.Property;
import org.apache.polygene.api.property.PropertyDescriptor;
import org.apache.polygene.api.query.QueryBuilder;
import org.apache.polygene.api.query.QueryBuilderFactory;
+import org.apache.polygene.api.serialization.Serialization;
+import org.apache.polygene.api.serialization.SerializationException;
import org.apache.polygene.api.service.NoSuchServiceException;
import org.apache.polygene.api.service.ServiceFinder;
import org.apache.polygene.api.service.ServiceReference;
@@ -66,8 +68,6 @@ import org.apache.polygene.api.value.ValueBuilder;
import org.apache.polygene.api.value.ValueBuilderFactory;
import org.apache.polygene.api.value.ValueComposite;
import org.apache.polygene.api.value.ValueDescriptor;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.api.value.ValueSerializationException;
import org.apache.polygene.runtime.activation.ActivationDelegate;
import org.apache.polygene.runtime.composite.FunctionStateResolver;
import org.apache.polygene.runtime.composite.StateResolver;
@@ -83,6 +83,7 @@ import org.apache.polygene.runtime.service.ImportedServicesInstance;
import org.apache.polygene.runtime.service.ImportedServicesModel;
import org.apache.polygene.runtime.service.ServicesInstance;
import org.apache.polygene.runtime.service.ServicesModel;
+import org.apache.polygene.runtime.type.ValueTypeFactoryInstance;
import org.apache.polygene.runtime.value.ValueBuilderInstance;
import org.apache.polygene.runtime.value.ValueBuilderWithPrototype;
import org.apache.polygene.runtime.value.ValueBuilderWithState;
@@ -112,7 +113,7 @@ public class ModuleInstance
// Lazy assigned on accessors
private EntityStore store;
private IdentityGenerator generator;
- private ValueSerialization valueSerialization;
+ private Serialization serialization;
private MetricsProvider metrics;
private UnitOfWorkFactory uowf;
@@ -296,7 +297,7 @@ public class ModuleInstance
@Override
public Object getPropertyState( PropertyDescriptor propertyDescriptor )
{
- return propertyDescriptor.resolveInitialValue(module);
+ return propertyDescriptor.resolveInitialValue( module );
}
@Override
@@ -312,7 +313,8 @@ public class ModuleInstance
}
@Override
- public Stream<Map.Entry<String, EntityReference>> getNamedAssociationState( AssociationDescriptor associationDescriptor )
+ public Stream<Map.Entry<String, EntityReference>>
+ getNamedAssociationState( AssociationDescriptor associationDescriptor )
{
return new HashMap<String, EntityReference>().entrySet().stream();
}
@@ -351,9 +353,9 @@ public class ModuleInstance
try
{
- return valueSerialization().deserialize( model.module(), model.valueType(), serializedState );
+ return serialization().deserialize( model.module(), model.valueType(), serializedState );
}
- catch( ValueSerializationException ex )
+ catch( SerializationException ex )
{
throw new ConstructionException( "Could not create value from serialized state", ex );
}
@@ -379,7 +381,7 @@ public class ModuleInstance
ModelDescriptor serviceModel = typeLookup.lookupServiceModel( serviceType );
if( serviceModel == null )
{
- throw new NoSuchServiceException( serviceType.getTypeName(), name(),typeLookup );
+ throw new NoSuchServiceException( serviceType.getTypeName(), name(), typeLookup );
}
return findServiceReferenceInstance( serviceModel );
}
@@ -423,7 +425,6 @@ public class ModuleInstance
// Implementation of Activation
@Override
- @SuppressWarnings( "unchecked" )
public void activate()
throws ActivationException
{
@@ -455,6 +456,7 @@ public class ModuleInstance
return model;
}
+ @Override
public LayerDescriptor layer()
{
return layer;
@@ -466,6 +468,7 @@ public class ModuleInstance
return typeLookup;
}
+ @Override
public EntityStore entityStore()
{
if( store == null )
@@ -489,6 +492,7 @@ public class ModuleInstance
return store;
}
+ @Override
public UnitOfWorkFactory unitOfWorkFactory()
{
if( uowf == null )
@@ -536,6 +540,7 @@ public class ModuleInstance
return this;
}
+ @Override
public IdentityGenerator identityGenerator()
{
if( generator == null )
@@ -552,29 +557,24 @@ public class ModuleInstance
return generator;
}
- public ValueSerialization valueSerialization()
+ @Override
+ public Serialization serialization()
{
- if( valueSerialization == null )
+ if( serialization == null )
{
synchronized( this )
{
- if( valueSerialization == null )
+ if( serialization == null )
{
- try
- {
- ServiceReference<ValueSerialization> service = findService( ValueSerialization.class );
- valueSerialization = service.get();
- }
- catch( NoSuchServiceException e )
- {
- throw new ValueSerializationException( "No ValueSeriaservice available in module " + name() );
- }
+ ServiceReference<Serialization> service = findService( Serialization.class );
+ serialization = service.get();
}
}
}
- return valueSerialization;
+ return serialization;
}
+ @Override
public MetricsProvider metricsProvider()
{
if( metrics == null )
@@ -597,4 +597,10 @@ public class ModuleInstance
}
return metrics;
}
+
+ @Override
+ public ValueTypeFactoryInstance valueTypeFactory()
+ {
+ return ValueTypeFactoryInstance.instance();
+ }
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/main/java/org/apache/polygene/runtime/structure/TypeLookupImpl.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/polygene/runtime/structure/TypeLookupImpl.java b/core/runtime/src/main/java/org/apache/polygene/runtime/structure/TypeLookupImpl.java
index 9df92c9..6f55c88 100644
--- a/core/runtime/src/main/java/org/apache/polygene/runtime/structure/TypeLookupImpl.java
+++ b/core/runtime/src/main/java/org/apache/polygene/runtime/structure/TypeLookupImpl.java
@@ -19,10 +19,7 @@
*/
package org.apache.polygene.runtime.structure;
-import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
-import java.lang.reflect.WildcardType;
-import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
@@ -36,14 +33,15 @@ import org.apache.polygene.api.entity.EntityDescriptor;
import org.apache.polygene.api.object.ObjectDescriptor;
import org.apache.polygene.api.structure.ModuleDescriptor;
import org.apache.polygene.api.structure.TypeLookup;
-import org.apache.polygene.api.type.HasTypes;
+import org.apache.polygene.api.type.HasAssignableFromType;
+import org.apache.polygene.api.type.HasEqualType;
+import org.apache.polygene.api.type.HasTypesCollectors;
import org.apache.polygene.api.value.ValueDescriptor;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Stream.concat;
import static org.apache.polygene.api.common.Visibility.application;
import static org.apache.polygene.api.common.Visibility.layer;
-import static org.apache.polygene.api.util.Classes.interfacesOf;
/**
* Central place for Composite Type lookups.
@@ -64,16 +62,16 @@ class TypeLookupImpl
private final ConcurrentHashMap<Type, ModelDescriptor> serviceModels;
private final ConcurrentHashMap<Type, List<? extends ModelDescriptor>> servicesReferences;
- private final ModuleDescriptor moduleModel;
+ private final ModuleDescriptor module;
/**
- * Create a new TypeLookup bound to the given ModuleModel.
+ * Create a new TypeLookup bound to the given Module.
*
- * @param module ModuleModel bound to this TypeLookup
+ * @param module Module bound to this TypeLookup
*/
- TypeLookupImpl( ModuleModel module )
+ TypeLookupImpl( ModuleDescriptor module )
{
- moduleModel = module;
+ this.module = module;
// Instance caches
allObjects = new LazyValue<>();
@@ -96,10 +94,10 @@ class TypeLookupImpl
return objectModels.computeIfAbsent( type, key ->
{
List<? extends ObjectDescriptor> allModels = getAllObjects();
- ObjectDescriptor model = ambiguityMatching( key, allModels, new ExactTypeMatching<>( key ) );
+ ObjectDescriptor model = ambiguityMatching( key, allModels, new HasEqualType<>( key ) );
if( model == null )
{
- model = ambiguityMatching( key, allModels, new AssignableFromTypeMatching<>( key ) );
+ model = ambiguityMatching( key, allModels, new HasAssignableFromType<>( key ) );
}
return model;
} );
@@ -111,10 +109,10 @@ class TypeLookupImpl
return transientModels.computeIfAbsent( type, key ->
{
List<? extends TransientDescriptor> allModels = getAllTransients();
- TransientDescriptor model = ambiguityMatching( key, allModels, new ExactTypeMatching<>( key ) );
+ TransientDescriptor model = ambiguityMatching( key, allModels, new HasEqualType<>( key ) );
if( model == null )
{
- model = ambiguityMatching( key, allModels, new AssignableFromTypeMatching<>( key ) );
+ model = ambiguityMatching( key, allModels, new HasAssignableFromType<>( key ) );
}
return model;
} );
@@ -126,10 +124,10 @@ class TypeLookupImpl
return valueModels.computeIfAbsent( type, key ->
{
List<? extends ValueDescriptor> allModels = getAllValues();
- ValueDescriptor model = ambiguityMatching( key, allModels, new ExactTypeMatching<>( key ) );
+ ValueDescriptor model = ambiguityMatching( key, allModels, new HasEqualType<>( key ) );
if( model == null )
{
- model = ambiguityMatching( key, allModels, new AssignableFromTypeMatching<>( key ) );
+ model = ambiguityMatching( key, allModels, new HasAssignableFromType<>( key ) );
}
return model;
} );
@@ -141,10 +139,10 @@ class TypeLookupImpl
return unambiguousEntityModels.computeIfAbsent( type, key ->
{
List<? extends EntityDescriptor> allModels = getAllEntities();
- EntityDescriptor model = ambiguityMatching( key, allModels, new ExactTypeMatching<>( key ) );
+ EntityDescriptor model = ambiguityMatching( key, allModels, new HasEqualType<>( key ) );
if( model == null )
{
- model = ambiguityMatching( key, allModels, new AssignableFromTypeMatching<>( key ) );
+ model = ambiguityMatching( key, allModels, new HasAssignableFromType<>( key ) );
}
return model;
} );
@@ -155,7 +153,7 @@ class TypeLookupImpl
{
return entityModels.computeIfAbsent(
type,
- key -> new TypeMatchesSelector<EntityDescriptor>( key ).selectFrom( allEntities() ) );
+ key -> allEntities().collect( HasTypesCollectors.matchingTypes( key ) ) );
}
@Override
@@ -163,8 +161,7 @@ class TypeLookupImpl
{
return serviceModels.computeIfAbsent(
serviceType,
- key -> new BestTypeMatchSelector<ModelDescriptor>( key ).selectFrom( allServices() )
- .bestMatchOrElse( null ) );
+ key -> allServices().collect( HasTypesCollectors.matchingType( key ) ).orElse( null ) );
}
@Override
@@ -172,7 +169,7 @@ class TypeLookupImpl
{
return servicesReferences.computeIfAbsent(
type,
- key -> new TypeMatchesSelector<ModelDescriptor>( key ).selectFrom( allServices() ) );
+ key -> allServices().collect( HasTypesCollectors.matchingTypes( key ) ) );
}
@Override
@@ -184,17 +181,14 @@ class TypeLookupImpl
private List<ObjectDescriptor> getAllObjects()
{
return allObjects.computeIfAbsent(
- () -> concat( moduleModel.objects(),
+ () -> concat( module.objects(),
concat(
concat(
- moduleModel.layer().visibleObjects( layer ),
- moduleModel.layer()
- .visibleObjects( application )
+ module.layer().visibleObjects( layer ),
+ module.layer().visibleObjects( application )
),
- moduleModel.layer()
- .usedLayers()
- .layers()
- .flatMap( layer -> layer.visibleObjects( application ) )
+ module.layer().usedLayers().layers()
+ .flatMap( layer -> layer.visibleObjects( application ) )
)
).collect( toList() )
);
@@ -209,16 +203,14 @@ class TypeLookupImpl
private List<TransientDescriptor> getAllTransients()
{
return allTransients.computeIfAbsent(
- () -> concat( moduleModel.transientComposites(),
+ () -> concat( module.transientComposites(),
concat(
concat(
- moduleModel.layer().visibleTransients( layer ),
- moduleModel.layer().visibleTransients( application )
+ module.layer().visibleTransients( layer ),
+ module.layer().visibleTransients( application )
),
- moduleModel.layer()
- .usedLayers()
- .layers()
- .flatMap( layer -> layer.visibleTransients( application ) )
+ module.layer().usedLayers().layers()
+ .flatMap( layer -> layer.visibleTransients( application ) )
)
).collect( toList() )
);
@@ -233,15 +225,13 @@ class TypeLookupImpl
private List<ValueDescriptor> getAllValues()
{
return allValues.computeIfAbsent(
- () -> concat( moduleModel.valueComposites(),
+ () -> concat( module.valueComposites(),
concat(
- concat( moduleModel.layer().visibleValues( layer ),
- moduleModel.layer().visibleValues( application )
+ concat( module.layer().visibleValues( layer ),
+ module.layer().visibleValues( application )
),
- moduleModel.layer()
- .usedLayers()
- .layers()
- .flatMap( layer1 -> layer1.visibleValues( application ) )
+ module.layer().usedLayers().layers()
+ .flatMap( layer1 -> layer1.visibleValues( application ) )
)
).collect( toList() )
);
@@ -256,16 +246,14 @@ class TypeLookupImpl
private List<EntityDescriptor> getAllEntities()
{
return allEntities.computeIfAbsent(
- () -> concat( moduleModel.entityComposites(),
+ () -> concat( module.entityComposites(),
concat(
concat(
- moduleModel.layer().visibleEntities( layer ),
- moduleModel.layer().visibleEntities( application )
+ module.layer().visibleEntities( layer ),
+ module.layer().visibleEntities( application )
),
- moduleModel.layer()
- .usedLayers()
- .layers()
- .flatMap( layer -> layer.visibleEntities( application ) )
+ module.layer().usedLayers().layers()
+ .flatMap( layer -> layer.visibleEntities( application ) )
)
).collect( toList() )
);
@@ -281,28 +269,24 @@ class TypeLookupImpl
{
return allServices.computeIfAbsent(
() -> concat(
- concat( moduleModel.serviceComposites(),
+ concat( module.serviceComposites(),
concat(
concat(
- moduleModel.layer().visibleServices( layer ),
- moduleModel.layer().visibleServices( application )
+ module.layer().visibleServices( layer ),
+ module.layer().visibleServices( application )
),
- moduleModel.layer()
- .usedLayers()
- .layers()
- .flatMap( layer -> layer.visibleServices( application ) )
+ module.layer().usedLayers().layers()
+ .flatMap( layer -> layer.visibleServices( application ) )
)
),
- concat( moduleModel.importedServices(),
+ concat( module.importedServices(),
concat(
concat(
- moduleModel.layer().visibleServices( layer ),
- moduleModel.layer().visibleServices( application )
+ module.layer().visibleServices( layer ),
+ module.layer().visibleServices( application )
),
- moduleModel.layer()
- .usedLayers()
- .layers()
- .flatMap( layer -> layer.visibleServices( application ) )
+ module.layer().usedLayers().layers()
+ .flatMap( layer -> layer.visibleServices( application ) )
)
)
).collect( toList() )
@@ -312,7 +296,7 @@ class TypeLookupImpl
private static <T extends ModelDescriptor> T ambiguityMatching(
Class type,
List<T> modelModules,
- TypeMatching<T> matching
+ Predicate<T> matching
)
{
List<T> models = modelModules.stream()
@@ -330,177 +314,6 @@ class TypeLookupImpl
return models.get( 0 );
}
- private static abstract class TypeMatching<T extends HasTypes>
- implements Predicate<T>
- {
- protected final Type lookedUpType;
-
- protected TypeMatching( Type lookedUpType )
- {
- this.lookedUpType = lookedUpType;
- }
-
- @Override
- public final boolean test( T model )
- {
- if( lookedUpType instanceof Class )
- {
- return model.types().anyMatch( checkMatch( lookedUpType ) );
- }
- else
- {
- if( lookedUpType instanceof ParameterizedType )
- {
- // Foo<Bar> check
- // First check Foo
- ParameterizedType parameterizedType = (ParameterizedType) lookedUpType;
- Type rawType = parameterizedType.getRawType();
- if( model.types().noneMatch( checkMatch( rawType ) ) )
- {
- return false;
- }
- // Then check Bar
- return interfacesOf( model.types() ).anyMatch( intf -> intf.equals( lookedUpType ) );
- }
- else if( lookedUpType instanceof WildcardType )
- {
- return true;
- }
- return false;
- }
- }
-
- protected abstract Predicate<Type> checkMatch( Type matchTo );
- }
-
- private static class ExactTypeMatching<T extends HasTypes> extends TypeMatching<T>
- {
- private ExactTypeMatching( Type lookedUpType )
- {
- super( lookedUpType );
- }
-
- protected Predicate<Type> checkMatch( Type matchTo )
- {
- return matchTo::equals;
- }
- }
-
- private static class AssignableFromTypeMatching<T extends HasTypes> extends TypeMatching<T>
- {
- private AssignableFromTypeMatching( Type lookedUpType )
- {
- super( lookedUpType );
- }
-
- protected Predicate<Type> checkMatch( Type matchTo )
- {
- // TODO; what to do if there is ParameterizedType here?? Now set to ClassCastException and see if anything surfaces
-// if( matchTo instanceof Class )
- {
- Class<?> clazz = (Class<?>) matchTo;
- return candidate -> !candidate.equals( matchTo ) && clazz.isAssignableFrom( (Class<?>) candidate );
- }
-// return candidate -> candidate.equals( matchTo );
- }
- }
-
- /**
- * Selects descriptors by combining {@link ExactTypeMatching} and {@link AssignableFromTypeMatching}.
- *
- * Selected descriptors are sorted, exact matches first, assignable ones second.
- * Other than that, original order is preserved.
- *
- * <code>
- * [ assignable1, matching1, assignable2, assignable3, matching2, non-matching-nor-assignable ]
- * </code>
- * results in
- * <code>
- * [ matching1, matching2, assignable1, assignable2, assignable3 ]
- * </code>
- *
- * @param <T> Descriptor type
- */
- private static class TypeMatchesSelector<T extends HasTypes> extends ArrayList<T>
- {
- private final ExactTypeMatching<T> exactMatchPredicate;
- private final AssignableFromTypeMatching<T> assignablePredicate;
- private Integer lastMatchIndex;
-
- private TypeMatchesSelector( Type type )
- {
- this.exactMatchPredicate = new ExactTypeMatching<>( type );
- this.assignablePredicate = new AssignableFromTypeMatching<>( type );
- }
-
- List<T> selectFrom( Stream<? extends T> candidates )
- {
- candidates.forEach( this::addDescriptor );
- return this;
- }
-
- private void addDescriptor( T descriptor )
- {
- if( contains( descriptor ) )
- {
- return;
- }
- if( exactMatchPredicate.test( descriptor ) )
- {
- Integer nextMatchIndex = lastMatchIndex == null ? 0 : lastMatchIndex + 1;
- add( nextMatchIndex, descriptor );
- lastMatchIndex = nextMatchIndex;
- }
- else if( assignablePredicate.test( descriptor ) )
- {
- add( descriptor );
- }
- }
-
- boolean containsExactMatches()
- {
- return lastMatchIndex != null;
- }
- }
-
- /**
- * Selects the best matching descriptor by combining {@link ExactTypeMatching} and {@link AssignableFromTypeMatching}.
- *
- * Selected descriptor is the first exact match if it exists, the first assignable otherwise.
- *
- * @param <T> Descriptor type
- */
- private static class BestTypeMatchSelector<T extends HasTypes>
- {
- private TypeMatchesSelector<T> descriptors;
-
- BestTypeMatchSelector( Type type )
- {
- this.descriptors = new TypeMatchesSelector<>( type );
- }
-
- BestTypeMatchSelector<T> selectFrom( Stream<? extends T> candidates )
- {
- candidates.forEach( this::addDescriptor );
- return this;
- }
-
- T bestMatchOrElse( T or )
- {
- return !descriptors.isEmpty() ? descriptors.get( 0 ) : or;
- }
-
- private void addDescriptor( T descriptor )
- {
- // Until an exact match is found, even if we already found assignable ones,
- // keep selecting in case the last element is an exact match.
- if( !descriptors.containsExactMatches() )
- {
- descriptors.addDescriptor( descriptor );
- }
- }
- }
-
/**
* This Predicate will filter out all Models that doesn't have the same visibility as the first one.
*/
@@ -525,7 +338,7 @@ class TypeLookupImpl
{
private volatile T value;
- public T computeIfAbsent( Supplier<T> supplier )
+ private T computeIfAbsent( Supplier<T> supplier )
{
if( value == null )
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/main/java/org/apache/polygene/runtime/type/ValueTypeFactoryInstance.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/polygene/runtime/type/ValueTypeFactoryInstance.java b/core/runtime/src/main/java/org/apache/polygene/runtime/type/ValueTypeFactoryInstance.java
new file mode 100644
index 0000000..37a1b91
--- /dev/null
+++ b/core/runtime/src/main/java/org/apache/polygene/runtime/type/ValueTypeFactoryInstance.java
@@ -0,0 +1,147 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+
+package org.apache.polygene.runtime.type;
+
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+import org.apache.polygene.api.common.InvalidApplicationException;
+import org.apache.polygene.api.structure.ModuleDescriptor;
+import org.apache.polygene.api.type.CollectionType;
+import org.apache.polygene.api.type.EnumType;
+import org.apache.polygene.api.type.MapType;
+import org.apache.polygene.api.type.ValueCompositeType;
+import org.apache.polygene.api.type.ValueType;
+import org.apache.polygene.api.util.Classes;
+import org.apache.polygene.api.value.ValueComposite;
+import org.apache.polygene.api.value.ValueDescriptor;
+import org.apache.polygene.runtime.value.ValueInstance;
+import org.apache.polygene.spi.type.ValueTypeFactory;
+
+public class ValueTypeFactoryInstance implements ValueTypeFactory
+{
+ private static final ValueTypeFactoryInstance INSTANCE = new ValueTypeFactoryInstance();
+
+ public static ValueTypeFactoryInstance instance()
+ {
+ return INSTANCE;
+ }
+
+ @Override
+ public ValueType valueTypeOf( ModuleDescriptor module, Object object )
+ {
+ if( object instanceof ValueComposite )
+ {
+ return ValueInstance.valueInstanceOf( (ValueComposite) object ).descriptor().valueType();
+ }
+ if( object instanceof Enum )
+ {
+ return EnumType.of( ( (Enum) object ).getDeclaringClass() );
+ }
+ return valueTypeOf( module, object.getClass() );
+ }
+
+ @Override
+ public ValueType valueTypeOf( ModuleDescriptor module, Class<?> type )
+ {
+ ValueDescriptor valueDescriptor = module.typeLookup().lookupValueModel( type );
+ if( valueDescriptor != null )
+ {
+ return valueDescriptor.valueType();
+ }
+ return newValueType( type, type, type, module );
+ }
+
+ public ValueType newValueType( Type type, Class declaringClass, Class compositeType, ModuleDescriptor module )
+ {
+ ValueType valueType;
+ if( EnumType.isEnum( type ) )
+ {
+ valueType = EnumType.of( Classes.RAW_CLASS.apply( type ) );
+ }
+ else if( CollectionType.isCollection( type ) )
+ {
+ if( type instanceof ParameterizedType )
+ {
+ ParameterizedType pt = (ParameterizedType) type;
+ Type collectionType = pt.getActualTypeArguments()[ 0 ];
+ if( collectionType instanceof TypeVariable && declaringClass != null )
+ {
+ TypeVariable collectionTypeVariable = (TypeVariable) collectionType;
+ collectionType = Classes.resolveTypeVariable( collectionTypeVariable, declaringClass,
+ compositeType );
+ }
+ ValueType collectedType = newValueType( collectionType, declaringClass, compositeType, module );
+ valueType = CollectionType.of( Classes.RAW_CLASS.apply( type ), collectedType );
+ }
+ else
+ {
+ ValueType collectedType = newValueType( Object.class, declaringClass, compositeType, module );
+ valueType = CollectionType.of( Classes.RAW_CLASS.apply( type ), collectedType );
+ }
+ }
+ else if( MapType.isMap( type ) )
+ {
+ if( type instanceof ParameterizedType )
+ {
+ ParameterizedType pt = (ParameterizedType) type;
+ Type keyType = pt.getActualTypeArguments()[ 0 ];
+ if( keyType instanceof TypeVariable && declaringClass != null )
+ {
+ TypeVariable keyTypeVariable = (TypeVariable) keyType;
+ keyType = Classes.resolveTypeVariable( keyTypeVariable, declaringClass, compositeType );
+ }
+ ValueType keyedType = newValueType( keyType, declaringClass, compositeType, module );
+ Type valType = pt.getActualTypeArguments()[ 1 ];
+ if( valType instanceof TypeVariable && declaringClass != null )
+ {
+ TypeVariable valueTypeVariable = (TypeVariable) valType;
+ valType = Classes.resolveTypeVariable( valueTypeVariable, declaringClass, compositeType );
+ }
+ ValueType valuedType = newValueType( valType, declaringClass, compositeType, module );
+ valueType = MapType.of( Classes.RAW_CLASS.apply( type ), keyedType, valuedType );
+ }
+ else
+ {
+ ValueType keyType = newValueType( Object.class, declaringClass, compositeType, module );
+ ValueType valuesType = newValueType( Object.class, declaringClass, compositeType, module );
+ valueType = MapType.of( Classes.RAW_CLASS.apply( type ), keyType, valuesType );
+ }
+ }
+ else if( ValueCompositeType.isValueComposite( type ) )
+ {
+ ValueDescriptor model = module.typeLookup().lookupValueModel( Classes.RAW_CLASS.apply( type ) );
+ if( model == null )
+ {
+ throw new InvalidApplicationException(
+ "[" + module.name() + "] Could not find ValueComposite of type " + type );
+ }
+
+ valueType = model.valueType();
+ }
+ else
+ {
+ valueType = ValueType.of( Classes.RAW_CLASS.apply( type ) );
+ }
+
+ return valueType;
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/main/java/org/apache/polygene/runtime/types/ValueTypeFactory.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/polygene/runtime/types/ValueTypeFactory.java b/core/runtime/src/main/java/org/apache/polygene/runtime/types/ValueTypeFactory.java
deleted file mode 100644
index a3538c0..0000000
--- a/core/runtime/src/main/java/org/apache/polygene/runtime/types/ValueTypeFactory.java
+++ /dev/null
@@ -1,233 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-
-package org.apache.polygene.runtime.types;
-
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-import java.util.ArrayList;
-import java.util.List;
-import org.apache.polygene.api.common.InvalidApplicationException;
-import org.apache.polygene.api.common.MetaInfo;
-import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.api.type.CollectionType;
-import org.apache.polygene.api.type.EnumType;
-import org.apache.polygene.api.type.MapType;
-import org.apache.polygene.api.type.Serialization;
-import org.apache.polygene.api.type.ValueCompositeType;
-import org.apache.polygene.api.type.ValueType;
-import org.apache.polygene.api.util.Classes;
-import org.apache.polygene.api.util.HierarchicalVisitorAdapter;
-import org.apache.polygene.api.value.ValueComposite;
-import org.apache.polygene.runtime.association.AssociationsModel;
-import org.apache.polygene.runtime.association.ManyAssociationsModel;
-import org.apache.polygene.runtime.association.NamedAssociationsModel;
-import org.apache.polygene.runtime.composite.CompositeMethodsModel;
-import org.apache.polygene.runtime.composite.MixinsModel;
-import org.apache.polygene.runtime.property.PropertiesModel;
-import org.apache.polygene.runtime.structure.LayerModel;
-import org.apache.polygene.runtime.structure.ModuleModel;
-import org.apache.polygene.runtime.structure.UsedLayersModel;
-import org.apache.polygene.runtime.value.ValueModel;
-import org.apache.polygene.runtime.value.ValueStateModel;
-import org.apache.polygene.runtime.value.ValuesModel;
-
-public class ValueTypeFactory
-{
- private static final ValueTypeFactory instance = new ValueTypeFactory();
-
- public static ValueTypeFactory instance()
- {
- return instance;
- }
-
- @SuppressWarnings( { "raw", "unchecked" } )
- public ValueType newValueType( Type type,
- Class declaringClass,
- Class compositeType,
- LayerModel layer,
- ModuleModel module,
- Serialization.Variant variant
- )
- {
- ValueType valueType;
- if( CollectionType.isCollection( type ) )
- {
- if( type instanceof ParameterizedType )
- {
- ParameterizedType pt = (ParameterizedType) type;
- Type collectionType = pt.getActualTypeArguments()[ 0 ];
- if( collectionType instanceof TypeVariable )
- {
- TypeVariable collectionTypeVariable = (TypeVariable) collectionType;
- collectionType = Classes.resolveTypeVariable( collectionTypeVariable, declaringClass, compositeType );
- }
- ValueType collectedType = newValueType( collectionType, declaringClass, compositeType, layer, module, variant );
- valueType = new CollectionType( Classes.RAW_CLASS.apply( type ), collectedType );
- }
- else
- {
- ValueType collectedType = newValueType( Object.class, declaringClass, compositeType, layer, module, variant );
- valueType = new CollectionType( Classes.RAW_CLASS.apply( type ), collectedType );
- }
- }
- else if( MapType.isMap( type ) )
- {
- if( type instanceof ParameterizedType )
- {
- ParameterizedType pt = (ParameterizedType) type;
- Type keyType = pt.getActualTypeArguments()[ 0 ];
- if( keyType instanceof TypeVariable )
- {
- TypeVariable keyTypeVariable = (TypeVariable) keyType;
- keyType = Classes.resolveTypeVariable( keyTypeVariable, declaringClass, compositeType );
- }
- ValueType keyedType = newValueType( keyType, declaringClass, compositeType, layer, module, variant );
- Type valType = pt.getActualTypeArguments()[ 1 ];
- if( valType instanceof TypeVariable )
- {
- TypeVariable valueTypeVariable = (TypeVariable) valType;
- valType = Classes.resolveTypeVariable( valueTypeVariable, declaringClass, compositeType );
- }
- ValueType valuedType = newValueType( valType, declaringClass, compositeType, layer, module, variant );
- valueType = new MapType( Classes.RAW_CLASS.apply( type ), keyedType, valuedType, variant );
- }
- else
- {
- ValueType keyType = newValueType( Object.class, declaringClass, compositeType, layer, module, variant );
- ValueType valuesType = newValueType( Object.class, declaringClass, compositeType, layer, module, variant );
- valueType = new MapType( Classes.RAW_CLASS.apply( type ), keyType, valuesType, variant );
- }
- }
- else if( ValueCompositeType.isValueComposite( type ) )
- {
- // Find ValueModel in module/layer/used layers
- ValueModel model = new ValueFinder( layer, module, Classes.RAW_CLASS.apply( type ) ).getFoundModel();
-
- if( model == null )
- {
- if( type.equals( ValueComposite.class ) )
- {
- // Create default model
- MixinsModel mixinsModel = new MixinsModel();
- List<Class<?>> valueComposite = new ArrayList<>();
- valueComposite.add( ValueComposite.class );
- ValueStateModel valueStateModel = new ValueStateModel( new PropertiesModel(),
- new AssociationsModel(),
- new ManyAssociationsModel(),
- new NamedAssociationsModel() );
- model = new ValueModel( module, valueComposite, Visibility.application, new MetaInfo(),
- mixinsModel, valueStateModel, new CompositeMethodsModel( mixinsModel ) );
- }
- else
- {
- throw new InvalidApplicationException( "[" + module.name() + "] Could not find ValueComposite of type " + type );
- }
- }
-
- return model.valueType();
- }
- else if( EnumType.isEnum( type ) )
- {
- valueType = new EnumType( Classes.RAW_CLASS.apply( type ) );
- }
- else
- {
- valueType = new ValueType( Classes.RAW_CLASS.apply( type ) );
- }
-
- return valueType;
- }
-
- @SuppressWarnings( "raw" )
- private static class ValueFinder
- extends HierarchicalVisitorAdapter<Object, Object, RuntimeException>
- {
- private Class<?> type;
- private ValueModel foundModel;
- private Visibility visibility;
-
- private ValueFinder( LayerModel layer, ModuleModel module, Class type )
- {
- this.type = type;
-
- visibility = Visibility.module;
- module.accept( this );
-
- if( foundModel == null )
- {
- visibility = Visibility.layer;
- layer.accept( this );
-
- if( foundModel == null )
- {
- visibility = Visibility.application;
- layer.usedLayers().accept( this );
- }
- }
- }
-
- public ValueModel getFoundModel()
- {
- return foundModel;
- }
-
- @Override
- public boolean visitEnter( Object visited )
- throws RuntimeException
- {
- if( visited instanceof ValuesModel )
- {
- return true;
- }
- else if( visited instanceof ModuleModel )
- {
- return true;
- }
- else if( visited instanceof LayerModel )
- {
- return true;
- }
- else if( visited instanceof UsedLayersModel )
- {
- return true;
- }
- else if( visited instanceof ValueModel )
- {
- ValueModel valueModel = (ValueModel) visited;
- boolean typeEquality = valueModel.types().anyMatch( t -> t.equals( type ) );
- if( typeEquality && valueModel.visibility().ordinal() >= visibility.ordinal() )
- {
- foundModel = valueModel;
- }
- }
-
- return false;
- }
-
- @Override
- public boolean visitLeave( Object visited )
- throws RuntimeException
- {
- return foundModel == null;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/main/java/org/apache/polygene/runtime/value/ValueInstance.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/polygene/runtime/value/ValueInstance.java b/core/runtime/src/main/java/org/apache/polygene/runtime/value/ValueInstance.java
index 573d659..04846e9 100644
--- a/core/runtime/src/main/java/org/apache/polygene/runtime/value/ValueInstance.java
+++ b/core/runtime/src/main/java/org/apache/polygene/runtime/value/ValueInstance.java
@@ -164,6 +164,6 @@ public final class ValueInstance
@Override
public String toString()
{
- return ( (ModuleSpi) module().instance() ).valueSerialization().serialize( this.<ValueComposite>proxy() );
+ return ( (ModuleSpi) module().instance() ).serialization().serialize( proxy() );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/main/java/org/apache/polygene/runtime/value/ValueModel.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/main/java/org/apache/polygene/runtime/value/ValueModel.java b/core/runtime/src/main/java/org/apache/polygene/runtime/value/ValueModel.java
index 2148095..4fee793 100644
--- a/core/runtime/src/main/java/org/apache/polygene/runtime/value/ValueModel.java
+++ b/core/runtime/src/main/java/org/apache/polygene/runtime/value/ValueModel.java
@@ -58,7 +58,7 @@ public final class ValueModel extends CompositeModel
{
super( module, types, visibility, metaInfo, mixinsModel, stateModel, compositeMethodsModel );
- valueType = new ValueCompositeType( this );
+ valueType = ValueCompositeType.of( this );
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/test/java/org/apache/polygene/bootstrap/ApplicationAssemblerTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/polygene/bootstrap/ApplicationAssemblerTest.java b/core/runtime/src/test/java/org/apache/polygene/bootstrap/ApplicationAssemblerTest.java
index 6729cf9..f924408 100644
--- a/core/runtime/src/test/java/org/apache/polygene/bootstrap/ApplicationAssemblerTest.java
+++ b/core/runtime/src/test/java/org/apache/polygene/bootstrap/ApplicationAssemblerTest.java
@@ -20,6 +20,7 @@
package org.apache.polygene.bootstrap;
import org.apache.polygene.api.identity.IdentityGenerator;
+import org.apache.polygene.api.serialization.Serialization;
import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
import org.junit.Assert;
import org.junit.Test;
@@ -77,7 +78,9 @@ public class ApplicationAssemblerTest
if( visited instanceof ServiceDescriptor )
{
ServiceDescriptor serviceDescriptor = (ServiceDescriptor) visited;
- if( serviceDescriptor.hasType( UnitOfWorkFactory.class ) || serviceDescriptor.hasType( IdentityGenerator.class ) )
+ if( serviceDescriptor.hasType( UnitOfWorkFactory.class )
+ || serviceDescriptor.hasType( IdentityGenerator.class )
+ || serviceDescriptor.hasType( Serialization.class ) )
{
return false;
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/test/java/org/apache/polygene/regression/qi382/Qi382Test.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/polygene/regression/qi382/Qi382Test.java b/core/runtime/src/test/java/org/apache/polygene/regression/qi382/Qi382Test.java
index 4a846dc..f09aa1c 100644
--- a/core/runtime/src/test/java/org/apache/polygene/regression/qi382/Qi382Test.java
+++ b/core/runtime/src/test/java/org/apache/polygene/regression/qi382/Qi382Test.java
@@ -31,12 +31,10 @@ import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.unitofwork.UnitOfWork;
import org.apache.polygene.api.unitofwork.UnitOfWorkCompletionException;
import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
import org.apache.polygene.test.AbstractPolygeneTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
import org.junit.Test;
import static org.hamcrest.core.IsEqual.equalTo;
@@ -53,7 +51,6 @@ public class Qi382Test extends AbstractPolygeneTest
public void assemble( ModuleAssembly module )
throws AssemblyException
{
- module.addServices( OrgJsonValueSerializationService.class ).taggedWith( ValueSerialization.Formats.JSON );
module.addServices( MemoryEntityStoreService.class );
module.entities( Car.class, Person.class );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/test/java/org/apache/polygene/regression/qi383/Qi383Test.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/polygene/regression/qi383/Qi383Test.java b/core/runtime/src/test/java/org/apache/polygene/regression/qi383/Qi383Test.java
index a44f20a..8ed138c 100644
--- a/core/runtime/src/test/java/org/apache/polygene/regression/qi383/Qi383Test.java
+++ b/core/runtime/src/test/java/org/apache/polygene/regression/qi383/Qi383Test.java
@@ -19,18 +19,16 @@
*/
package org.apache.polygene.regression.qi383;
-import org.apache.polygene.api.identity.StringIdentity;
-import org.apache.polygene.test.AbstractPolygeneTest;
-import org.junit.Test;
import org.apache.polygene.api.entity.EntityComposite;
+import org.apache.polygene.api.identity.StringIdentity;
import org.apache.polygene.api.unitofwork.EntityCompositeAlreadyExistsException;
import org.apache.polygene.api.unitofwork.UnitOfWork;
import org.apache.polygene.api.unitofwork.UnitOfWorkCompletionException;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
+import org.apache.polygene.test.AbstractPolygeneTest;
+import org.junit.Test;
public class Qi383Test extends AbstractPolygeneTest
{
@@ -38,7 +36,6 @@ public class Qi383Test extends AbstractPolygeneTest
public void assemble( ModuleAssembly module )
throws AssemblyException
{
- module.addServices( OrgJsonValueSerializationService.class ).taggedWith( ValueSerialization.Formats.JSON );
module.addServices( MemoryEntityStoreService.class );
module.entities( Car.class );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/test/java/org/apache/polygene/runtime/association/AssociationAssignmentTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/polygene/runtime/association/AssociationAssignmentTest.java b/core/runtime/src/test/java/org/apache/polygene/runtime/association/AssociationAssignmentTest.java
index 051b3bc..c3131eb 100644
--- a/core/runtime/src/test/java/org/apache/polygene/runtime/association/AssociationAssignmentTest.java
+++ b/core/runtime/src/test/java/org/apache/polygene/runtime/association/AssociationAssignmentTest.java
@@ -25,12 +25,10 @@ import org.apache.polygene.api.entity.EntityBuilder;
import org.apache.polygene.api.entity.EntityComposite;
import org.apache.polygene.api.identity.Identity;
import org.apache.polygene.api.unitofwork.UnitOfWork;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
import org.apache.polygene.test.AbstractPolygeneTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
import org.junit.Test;
import static org.hamcrest.core.IsEqual.equalTo;
@@ -45,8 +43,6 @@ public class AssociationAssignmentTest extends AbstractPolygeneTest
throws AssemblyException
{
module.services( MemoryEntityStoreService.class );
- module.services( OrgJsonValueSerializationService.class )
- .taggedWith( ValueSerialization.Formats.JSON );
module.entities( TheAssociatedType.class );
module.entities( TheMainType.class );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/test/java/org/apache/polygene/runtime/defaults/UseDefaultsTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/polygene/runtime/defaults/UseDefaultsTest.java b/core/runtime/src/test/java/org/apache/polygene/runtime/defaults/UseDefaultsTest.java
index d0b0863..ab1feb9 100644
--- a/core/runtime/src/test/java/org/apache/polygene/runtime/defaults/UseDefaultsTest.java
+++ b/core/runtime/src/test/java/org/apache/polygene/runtime/defaults/UseDefaultsTest.java
@@ -28,11 +28,9 @@ import org.apache.polygene.api.common.UseDefaults;
import org.apache.polygene.api.composite.TransientBuilder;
import org.apache.polygene.api.composite.TransientComposite;
import org.apache.polygene.api.property.Property;
-import org.apache.polygene.api.value.ValueDeserializer;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.test.AbstractPolygeneTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueDeserializer;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
@@ -42,14 +40,12 @@ import static org.junit.Assert.assertThat;
/**
* JAVADOC
*/
-public class UseDefaultsTest
- extends AbstractPolygeneTest
+public class UseDefaultsTest extends AbstractPolygeneTest
{
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.transients( TestComposite.class );
- module.services( ValueDeserializer.class ).withMixins( OrgJsonValueDeserializer.class );
module.forMixin( TestComposite.class ).declareDefaults().assemblyString().set( "habba" );
}
@@ -76,9 +72,9 @@ public class UseDefaultsTest
assertThat( testComposite.initializedIntegerDefaultValue().get(), equalTo( 123 ) );
assertThat( testComposite.initializedFloatDefaultValue().get(), equalTo( 123.45f ) );
List<String> expectedList = Collections.singletonList( "abcde" );
-// assertThat( testComposite.initializedStringListDefultString().get(), equalTo( expectedList) );
+ assertThat( testComposite.initializedStringListDefultString().get(), equalTo( expectedList ) );
Map<String, Integer> expectedMap = Collections.singletonMap( "abcd", 345 );
-// assertThat( testComposite.initializedMapDefaultValue().get(), equalTo( expectedMap) );
+ assertThat( testComposite.initializedMapDefaultValue().get(), equalTo( expectedMap ) );
}
interface TestComposite
@@ -109,12 +105,10 @@ public class UseDefaultsTest
@UseDefaults( "123.45" )
Property<Float> initializedFloatDefaultValue();
-// TODO: Seems that OrgJsonValueDeserializer has problem with arrays.
-// @UseDefaults( "[\"abcde\"]" )
-// Property<List<String>> initializedStringListDefultString();
+ @UseDefaults( "[\"abcde\"]" )
+ Property<List<String>> initializedStringListDefultString();
-// TODO: Seems that OrgJsonValueDeserializer has problem with arrays.
-// @UseDefaults( "{\"abcd\" : 345 }" )
-// Property<Map<String, Integer>> initializedMapDefaultValue();
+ @UseDefaults( "{\"abcd\": 345}" )
+ Property<Map<String, Integer>> initializedMapDefaultValue();
}
}
[12/50] [abbrv] polygene-java git commit: Fixed Serialization missing
in RdfIndexingAssembler,
causing failed tests. Fixed additional issues in Yeoman generator.
Posted by pa...@apache.org.
Fixed Serialization missing in RdfIndexingAssembler, causing failed tests. Fixed additional issues in Yeoman generator.
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/b8aea70a
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/b8aea70a
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/b8aea70a
Branch: refs/heads/serialization-3.0
Commit: b8aea70ac345bd99e8848a8ffd880f0e57dc3440
Parents: 41c759b
Author: niclas <ni...@spicter.com>
Authored: Sat Mar 11 23:17:25 2017 +0800
Committer: niclas <ni...@spicter.com>
Committed: Sat Mar 11 23:17:25 2017 +0800
----------------------------------------------------------------------
.../cache/memcache/MemcacheAssembler.java | 47 --
.../memcache/assembly/MemcacheAssembler.java | 49 ++
.../cache/memcache/MemcacheCachePoolTest.java | 1 +
.../cassandra/CassandraMapEntityStoreTest.java | 2 +-
.../preferences/ListPreferencesNodes.java | 68 ++
.../preferences/PreferencesEntityStoreInfo.java | 45 ++
.../PreferencesEntityStoreMixin.java | 658 +++++++++++++++++++
.../PreferencesEntityStoreService.java | 60 ++
.../PreferencesEntityStoreAssembler.java | 51 ++
.../preferences/assembly/package.html | 24 +
.../entitystore/preferences/package.html | 24 +
.../entitystore/prefs/ListPreferencesNodes.java | 68 --
.../prefs/PreferencesEntityStoreInfo.java | 45 --
.../prefs/PreferencesEntityStoreMixin.java | 658 -------------------
.../prefs/PreferencesEntityStoreService.java | 60 --
.../PreferenceEntityStoreAssembler.java | 51 --
.../entitystore/prefs/assembly/package.html | 24 -
.../polygene/entitystore/prefs/package.html | 24 -
.../entitystore/DocumentationSupport.java | 4 +-
.../entitystore/PreferencesEntityStoreTest.java | 4 +-
.../sql/assembly/SQLEntityStoreAssembler.java | 28 +
extensions/indexing-elasticsearch/build.gradle | 1 +
.../elasticsearch/ElasticSearchQueryTest.java | 4 +
extensions/indexing-rdf/build.gradle | 2 +-
.../index/rdf/query/RdfQueryParserFactory.java | 1 +
.../index/rdf/RdfNamedQueryMultimoduleTest.java | 2 +
.../polygene/index/rdf/RdfNamedQueryTest.java | 2 +
.../index/rdf/RdfQueryMultimoduleTest.java | 2 +
.../polygene/index/rdf/qi95/Qi95IssueTest.java | 6 +-
extensions/indexing-solr/build.gradle | 1 +
.../index/solr/assembly/SolrAssembler.java | 48 --
.../solr/assembly/SolrIndexingAssembler.java | 47 ++
.../index/solr/SolrEntityFinderTest.java | 4 +-
.../polygene/index/solr/SolrNamedQueryTest.java | 4 +-
.../index/solr/SolrQueryServiceTest.java | 4 +-
.../polygene/index/solr/SolrQueryTest.java | 4 +-
extensions/indexing-sql/build.gradle | 1 +
.../sql/assembly/SQLIndexingAssembler.java | 24 +
.../assembly/CodahaleMetricsAssembler.java | 2 +-
.../JacksonValueSerializationAssembler.java | 41 --
.../JacksonValueSerializationAssembler.java | 42 ++
.../JacksonCollectionSerializationTest.java | 1 +
...JacksonConfigurationDeserializationTest.java | 1 +
.../jackson/JacksonJsonDateFormatTest.java | 1 +
.../JacksonPlainValueSerializationTest.java | 1 +
.../JacksonValueCompositeSerializationTest.java | 1 +
.../stax/StaxValueSerializationAssembler.java | 41 --
.../StaxValueSerializationAssembler.java | 42 ++
.../stax/StaxCollectionSerializationTest.java | 1 +
.../StaxConfigurationDeserializationTest.java | 1 +
.../stax/StaxPlainValueSerializationTest.java | 1 +
.../StaxValueCompositeSerializationTest.java | 1 +
.../RestletCrudConnectivityAssembler.java | 2 +-
.../configuration/ConfigurationModule.java | 2 +-
.../infrastructue/SerializationModule.java | 2 +-
settings.gradle | 1 +
.../ConfigModule/bootstrap.tmpl | 2 +-
.../MetricsModule/bootstrap.tmpl | 2 +-
.../SerializationModule/bootstrap.tmpl | 2 +-
tools/generator-polygene/build.gradle | 68 ++
tools/generator-polygene/test/generator_test.js | 134 +++-
61 files changed, 1402 insertions(+), 1142 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/cache-memcache/src/main/java/org/apache/polygene/cache/memcache/MemcacheAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/cache-memcache/src/main/java/org/apache/polygene/cache/memcache/MemcacheAssembler.java b/extensions/cache-memcache/src/main/java/org/apache/polygene/cache/memcache/MemcacheAssembler.java
deleted file mode 100644
index bbc58cb..0000000
--- a/extensions/cache-memcache/src/main/java/org/apache/polygene/cache/memcache/MemcacheAssembler.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.cache.memcache;
-
-import org.apache.polygene.bootstrap.Assemblers;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.bootstrap.ServiceDeclaration;
-
-/**
- * Memcache CachePool Assembler.
- */
-public class MemcacheAssembler
- extends Assemblers.VisibilityIdentityConfig<MemcacheAssembler>
-{
- @Override
- public void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- ServiceDeclaration service = module.services( MemcachePoolService.class ).visibleIn( visibility() );
- if( hasIdentity() )
- {
- service.identifiedBy( identity() );
- }
- if( hasConfig() )
- {
- configModule().entities( MemcacheConfiguration.class ).visibleIn( configVisibility() );
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/cache-memcache/src/main/java/org/apache/polygene/cache/memcache/assembly/MemcacheAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/cache-memcache/src/main/java/org/apache/polygene/cache/memcache/assembly/MemcacheAssembler.java b/extensions/cache-memcache/src/main/java/org/apache/polygene/cache/memcache/assembly/MemcacheAssembler.java
new file mode 100644
index 0000000..e2cbc11
--- /dev/null
+++ b/extensions/cache-memcache/src/main/java/org/apache/polygene/cache/memcache/assembly/MemcacheAssembler.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.cache.memcache.assembly;
+
+import org.apache.polygene.bootstrap.Assemblers;
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.bootstrap.ServiceDeclaration;
+import org.apache.polygene.cache.memcache.MemcacheConfiguration;
+import org.apache.polygene.cache.memcache.MemcachePoolService;
+
+/**
+ * Memcache CachePool Assembler.
+ */
+public class MemcacheAssembler
+ extends Assemblers.VisibilityIdentityConfig<MemcacheAssembler>
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ throws AssemblyException
+ {
+ ServiceDeclaration service = module.services( MemcachePoolService.class ).visibleIn( visibility() );
+ if( hasIdentity() )
+ {
+ service.identifiedBy( identity() );
+ }
+ if( hasConfig() )
+ {
+ configModule().entities( MemcacheConfiguration.class ).visibleIn( configVisibility() );
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/cache-memcache/src/test/java/org/apache/polygene/cache/memcache/MemcacheCachePoolTest.java
----------------------------------------------------------------------
diff --git a/extensions/cache-memcache/src/test/java/org/apache/polygene/cache/memcache/MemcacheCachePoolTest.java b/extensions/cache-memcache/src/test/java/org/apache/polygene/cache/memcache/MemcacheCachePoolTest.java
index 7d5d98b..7843eb3 100644
--- a/extensions/cache-memcache/src/test/java/org/apache/polygene/cache/memcache/MemcacheCachePoolTest.java
+++ b/extensions/cache-memcache/src/test/java/org/apache/polygene/cache/memcache/MemcacheCachePoolTest.java
@@ -22,6 +22,7 @@ package org.apache.polygene.cache.memcache;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.cache.memcache.assembly.MemcacheAssembler;
import org.apache.polygene.test.internal.DockerRule;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.cache.AbstractCachePoolTest;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/entitystore-cassandra/src/test/java/org/apache/polygene/entitystore/cassandra/CassandraMapEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-cassandra/src/test/java/org/apache/polygene/entitystore/cassandra/CassandraMapEntityStoreTest.java b/extensions/entitystore-cassandra/src/test/java/org/apache/polygene/entitystore/cassandra/CassandraMapEntityStoreTest.java
index 45e35e1..af97dc9 100644
--- a/extensions/entitystore-cassandra/src/test/java/org/apache/polygene/entitystore/cassandra/CassandraMapEntityStoreTest.java
+++ b/extensions/entitystore-cassandra/src/test/java/org/apache/polygene/entitystore/cassandra/CassandraMapEntityStoreTest.java
@@ -27,7 +27,7 @@ import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
import org.apache.polygene.test.entity.CanRemoveAll;
import org.apache.polygene.test.internal.DockerRule;
-import org.apache.polygene.valueserialization.jackson.JacksonValueSerializationAssembler;
+import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
import org.junit.ClassRule;
/**
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/ListPreferencesNodes.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/ListPreferencesNodes.java b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/ListPreferencesNodes.java
new file mode 100644
index 0000000..ad30f02
--- /dev/null
+++ b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/ListPreferencesNodes.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.entitystore.preferences;
+
+import java.util.prefs.BackingStoreException;
+import java.util.prefs.Preferences;
+
+public class ListPreferencesNodes
+{
+ public static void main( String[] args )
+ throws Exception
+ {
+ Preferences preferences = Preferences.userRoot();
+ printNode( preferences, "" );
+ }
+
+ private static void printNode( Preferences node, String indent )
+ throws BackingStoreException
+ {
+ System.out.print( indent );
+ String name = node.name();
+ if( "".equals( name ) )
+ {
+ name = "/";
+ }
+
+ System.out.print( name );
+ String[] nodes = node.keys();
+ if( nodes.length > 0 )
+ {
+ System.out.print( " { " );
+ boolean first = true;
+ for( String key : nodes )
+ {
+ if( !first )
+ {
+ System.out.print( ", " );
+ }
+ first = false;
+ System.out.print( key );
+ }
+ System.out.print( " }" );
+ }
+ System.out.println();
+ for( String childName : node.childrenNames() )
+ {
+ Preferences child = node.node( childName );
+ printNode( child, indent + " " );
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/PreferencesEntityStoreInfo.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/PreferencesEntityStoreInfo.java b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/PreferencesEntityStoreInfo.java
new file mode 100644
index 0000000..fc59c15
--- /dev/null
+++ b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/PreferencesEntityStoreInfo.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.entitystore.preferences;
+
+import java.io.Serializable;
+import java.util.prefs.Preferences;
+
+/**
+ * @author edward.yakop@gmail.com
+ */
+public final class PreferencesEntityStoreInfo
+ implements Serializable
+{
+ private Preferences rootNode;
+
+ public PreferencesEntityStoreInfo( Preferences aRootNode )
+ {
+ rootNode = aRootNode;
+ }
+
+ /**
+ * @return root preference node to use.
+ */
+ public Preferences rootNode()
+ {
+ return rootNode;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/PreferencesEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/PreferencesEntityStoreMixin.java b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/PreferencesEntityStoreMixin.java
new file mode 100644
index 0000000..fa32a71
--- /dev/null
+++ b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/PreferencesEntityStoreMixin.java
@@ -0,0 +1,658 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.entitystore.preferences;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.prefs.BackingStoreException;
+import java.util.prefs.Preferences;
+import java.util.stream.Stream;
+import org.apache.polygene.api.cache.CacheOptions;
+import org.apache.polygene.api.common.QualifiedName;
+import org.apache.polygene.api.entity.EntityDescriptor;
+import org.apache.polygene.api.entity.EntityReference;
+import org.apache.polygene.api.identity.Identity;
+import org.apache.polygene.api.identity.IdentityGenerator;
+import org.apache.polygene.api.injection.scope.Service;
+import org.apache.polygene.api.injection.scope.Structure;
+import org.apache.polygene.api.injection.scope.This;
+import org.apache.polygene.api.injection.scope.Uses;
+import org.apache.polygene.api.property.PropertyDescriptor;
+import org.apache.polygene.api.service.ServiceActivation;
+import org.apache.polygene.api.service.ServiceDescriptor;
+import org.apache.polygene.api.service.qualifier.Tagged;
+import org.apache.polygene.api.structure.Application;
+import org.apache.polygene.api.structure.ModuleDescriptor;
+import org.apache.polygene.api.time.SystemTime;
+import org.apache.polygene.api.type.CollectionType;
+import org.apache.polygene.api.type.EnumType;
+import org.apache.polygene.api.type.MapType;
+import org.apache.polygene.api.type.ValueCompositeType;
+import org.apache.polygene.api.type.ValueType;
+import org.apache.polygene.api.unitofwork.NoSuchEntityException;
+import org.apache.polygene.api.unitofwork.NoSuchEntityTypeException;
+import org.apache.polygene.api.usecase.Usecase;
+import org.apache.polygene.api.usecase.UsecaseBuilder;
+import org.apache.polygene.api.value.ValueSerialization;
+import org.apache.polygene.api.value.ValueSerializationException;
+import org.apache.polygene.spi.PolygeneSPI;
+import org.apache.polygene.spi.entity.EntityState;
+import org.apache.polygene.spi.entity.EntityStatus;
+import org.apache.polygene.spi.entitystore.DefaultEntityStoreUnitOfWork;
+import org.apache.polygene.spi.entitystore.EntityStore;
+import org.apache.polygene.spi.entitystore.EntityStoreException;
+import org.apache.polygene.spi.entitystore.EntityStoreSPI;
+import org.apache.polygene.spi.entitystore.EntityStoreUnitOfWork;
+import org.apache.polygene.spi.entitystore.StateCommitter;
+import org.apache.polygene.spi.entitystore.helpers.DefaultEntityState;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Implementation of EntityStore that is backed by the Preferences API.
+ *
+ * <p>@see Preferences</p>
+ * <p>
+ * Associations are stored as the reference of the referenced Entity, ManyAssociations are stored as multi-line strings
+ * (one reference per line), and NamedAssociations are stored as multi-line strings (one name on a line, reference on the
+ * next line).
+ * </p>
+ * <p>Nested ValuesComposites, Collections and Maps are stored using available ValueSerialization service.</p>
+ */
+public class PreferencesEntityStoreMixin
+ implements ServiceActivation, EntityStore, EntityStoreSPI
+{
+ @Structure
+ private PolygeneSPI spi;
+
+ @This
+ private EntityStoreSPI entityStoreSpi;
+
+ @Uses
+ private ServiceDescriptor descriptor;
+
+ @Structure
+ private Application application;
+
+ @Service
+ @Tagged( ValueSerialization.Formats.JSON )
+ private ValueSerialization valueSerialization;
+
+ private Preferences root;
+
+ public Logger logger;
+
+ public ScheduledThreadPoolExecutor reloadExecutor;
+
+ @Service
+ private IdentityGenerator identityGenerator;
+
+ @Override
+ public void activateService()
+ throws Exception
+ {
+ root = getApplicationRoot();
+ logger = LoggerFactory.getLogger( PreferencesEntityStoreService.class.getName() );
+ logger.info( "Preferences store:" + root.absolutePath() );
+
+ // Reload underlying store every 60 seconds
+ reloadExecutor = new ScheduledThreadPoolExecutor( 1 );
+ reloadExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy( false );
+ reloadExecutor.scheduleAtFixedRate( () -> {
+ try
+ {
+ //noinspection SynchronizeOnNonFinalField
+ synchronized( root )
+ {
+ root.sync();
+ }
+ }
+ catch( BackingStoreException e )
+ {
+ logger.warn( "Could not reload preferences", e );
+ }
+ }, 0, 60, TimeUnit.SECONDS );
+ }
+
+ private Preferences getApplicationRoot()
+ {
+ PreferencesEntityStoreInfo storeInfo = descriptor.metaInfo( PreferencesEntityStoreInfo.class );
+
+ Preferences preferences;
+ if( storeInfo == null )
+ {
+ // Default to use system root + application name
+ preferences = Preferences.systemRoot();
+ String name = application.name();
+ preferences = preferences.node( name );
+ }
+ else
+ {
+ preferences = storeInfo.rootNode();
+ }
+
+ return preferences;
+ }
+
+ @Override
+ public void passivateService()
+ throws Exception
+ {
+ reloadExecutor.shutdown();
+ reloadExecutor.awaitTermination( 10, TimeUnit.SECONDS );
+ }
+
+ @Override
+ public EntityStoreUnitOfWork newUnitOfWork( ModuleDescriptor module, Usecase usecase, Instant currentTime )
+ {
+ return new DefaultEntityStoreUnitOfWork( module, entityStoreSpi, newUnitOfWorkId(), usecase, currentTime );
+ }
+
+ @Override
+ public Stream<EntityState> entityStates( final ModuleDescriptor module )
+ {
+ UsecaseBuilder builder = UsecaseBuilder.buildUsecase( "polygene.entitystore.preferences.visit" );
+ Usecase visitUsecase = builder.withMetaInfo( CacheOptions.NEVER ).newUsecase();
+ EntityStoreUnitOfWork uow = newUnitOfWork( module, visitUsecase, SystemTime.now() );
+
+ try
+ {
+ return Stream.of( root.childrenNames() )
+ .map( EntityReference::parseEntityReference )
+ .map( ref -> uow.entityStateOf( module, ref ) )
+ .onClose( uow::discard );
+ }
+ catch( BackingStoreException e )
+ {
+ throw new EntityStoreException( e );
+ }
+ }
+
+ @Override
+ public EntityState newEntityState( EntityStoreUnitOfWork unitOfWork,
+ EntityReference reference,
+ EntityDescriptor entityDescriptor
+ )
+ {
+ return new DefaultEntityState( unitOfWork.currentTime(), reference, entityDescriptor );
+ }
+
+ @Override
+ public EntityState entityStateOf( EntityStoreUnitOfWork unitOfWork,
+ ModuleDescriptor module,
+ EntityReference reference
+ )
+ {
+ try
+ {
+ if( !root.nodeExists( reference.identity().toString() ) )
+ {
+ throw new NoSuchEntityException( reference, UnknownType.class, unitOfWork.usecase() );
+ }
+
+ Preferences entityPrefs = root.node( reference.identity().toString() );
+
+ String type = entityPrefs.get( "type", null );
+ EntityStatus status = EntityStatus.LOADED;
+
+ EntityDescriptor entityDescriptor = module.entityDescriptor( type );
+ if( entityDescriptor == null )
+ {
+ throw new NoSuchEntityTypeException( type, module.name(), module.typeLookup() );
+ }
+
+ Map<QualifiedName, Object> properties = new HashMap<>();
+ final Preferences propsPrefs = entityPrefs.node( "properties" );
+ entityDescriptor.state().properties().forEach(
+ persistentPropertyDescriptor ->
+ {
+ if( persistentPropertyDescriptor.qualifiedName().name().equals( "reference" ) )
+ {
+ // Fake reference property
+ properties.put( persistentPropertyDescriptor.qualifiedName(), reference.identity().toString() );
+ }
+ else
+ {
+ ValueType propertyType = persistentPropertyDescriptor.valueType();
+ Class<?> primaryType = propertyType.primaryType();
+ if( Number.class.isAssignableFrom( primaryType ) )
+ {
+ if( primaryType.equals( Long.class ) )
+ {
+ properties.put( persistentPropertyDescriptor.qualifiedName(),
+ this.getNumber( propsPrefs, module, persistentPropertyDescriptor, LONG_PARSER ) );
+ }
+ else if( primaryType.equals( Integer.class ) )
+ {
+ properties.put( persistentPropertyDescriptor.qualifiedName(),
+ this.getNumber( propsPrefs, module, persistentPropertyDescriptor, INT_PARSER ) );
+ }
+ else if( primaryType.equals( Double.class ) )
+ {
+ properties.put( persistentPropertyDescriptor.qualifiedName(),
+ this.getNumber( propsPrefs, module, persistentPropertyDescriptor, DOUBLE_PARSER ) );
+ }
+ else if( primaryType.equals( Float.class ) )
+ {
+ properties.put( persistentPropertyDescriptor.qualifiedName(),
+ this.getNumber( propsPrefs, module, persistentPropertyDescriptor, FLOAT_PARSER ) );
+ }
+ else
+ {
+ // Load as string even though it's a number
+ String json = propsPrefs.get( persistentPropertyDescriptor.qualifiedName()
+ .name(), null );
+ Object value;
+ if( json == null )
+ {
+ value = null;
+ }
+ else
+ {
+ value = valueSerialization.deserialize( module, persistentPropertyDescriptor.valueType(), json );
+ }
+ properties.put( persistentPropertyDescriptor.qualifiedName(), value );
+ }
+ }
+ else if( primaryType.equals( Boolean.class ) )
+ {
+ Boolean initialValue = (Boolean) persistentPropertyDescriptor.resolveInitialValue(module);
+ properties.put( persistentPropertyDescriptor.qualifiedName(),
+ propsPrefs.getBoolean( persistentPropertyDescriptor.qualifiedName().name(),
+ initialValue == null ? false : initialValue ) );
+ }
+ else if( propertyType instanceof ValueCompositeType
+ || propertyType instanceof MapType
+ || propertyType instanceof CollectionType
+ || propertyType instanceof EnumType )
+ {
+ String json = propsPrefs.get( persistentPropertyDescriptor.qualifiedName().name(), null );
+ Object value;
+ if( json == null )
+ {
+ value = null;
+ }
+ else
+ {
+ value = valueSerialization.deserialize( module, persistentPropertyDescriptor.valueType(), json );
+ }
+ properties.put( persistentPropertyDescriptor.qualifiedName(), value );
+ }
+ else
+ {
+ String json = propsPrefs.get( persistentPropertyDescriptor.qualifiedName().name(), null );
+ if( json == null )
+ {
+ if( persistentPropertyDescriptor.resolveInitialValue( module ) != null )
+ {
+ properties.put( persistentPropertyDescriptor.qualifiedName(),
+ persistentPropertyDescriptor.resolveInitialValue( module ) );
+ }
+ else
+ {
+ properties.put( persistentPropertyDescriptor.qualifiedName(), null );
+ }
+ }
+ else
+ {
+ Object value = valueSerialization.deserialize( module, propertyType, json );
+ properties.put( persistentPropertyDescriptor.qualifiedName(), value );
+ }
+ }
+ }
+ } );
+
+ // Associations
+ Map<QualifiedName, EntityReference> associations = new HashMap<>();
+ final Preferences assocs = entityPrefs.node( "associations" );
+ entityDescriptor.state().associations().forEach( associationType -> {
+ String associatedEntity = assocs.get( associationType.qualifiedName().name(), null );
+ EntityReference value = associatedEntity == null
+ ? null
+ : EntityReference.parseEntityReference( associatedEntity );
+ associations.put( associationType.qualifiedName(), value );
+ } );
+
+ // ManyAssociations
+ Map<QualifiedName, List<EntityReference>> manyAssociations = new HashMap<>();
+ Preferences manyAssocs = entityPrefs.node( "manyassociations" );
+ entityDescriptor.state().manyAssociations().forEach( manyAssociationType -> {
+ List<EntityReference> references = new ArrayList<>();
+ String entityReferences = manyAssocs.get( manyAssociationType
+ .qualifiedName()
+ .name(), null );
+ if( entityReferences == null )
+ {
+ // ManyAssociation not found, default to empty one
+ manyAssociations.put( manyAssociationType.qualifiedName(), references );
+ }
+ else
+ {
+ String[] refs = entityReferences.split( "\n" );
+ for( String ref : refs )
+ {
+ EntityReference value = ref == null
+ ? null
+ : EntityReference.parseEntityReference( ref );
+ references.add( value );
+ }
+ manyAssociations.put( manyAssociationType.qualifiedName(), references );
+ }
+ } );
+
+ // NamedAssociations
+ Map<QualifiedName, Map<String, EntityReference>> namedAssociations = new HashMap<>();
+ Preferences namedAssocs = entityPrefs.node( "namedassociations" );
+ entityDescriptor.state().namedAssociations().forEach( namedAssociationType -> {
+ Map<String, EntityReference> references = new LinkedHashMap<>();
+ String entityReferences = namedAssocs.get( namedAssociationType.qualifiedName().name(), null );
+ if( entityReferences == null )
+ {
+ // NamedAssociation not found, default to empty one
+ namedAssociations.put( namedAssociationType.qualifiedName(), references );
+ }
+ else
+ {
+ String[] namedRefs = entityReferences.split( "\n" );
+ if( namedRefs.length % 2 != 0 )
+ {
+ throw new EntityStoreException( "Invalid NamedAssociation storage format" );
+ }
+ for( int idx = 0; idx < namedRefs.length; idx += 2 )
+ {
+ String name = namedRefs[ idx ];
+ String ref = namedRefs[ idx + 1 ];
+ references.put( name, EntityReference.parseEntityReference( ref ) );
+ }
+ namedAssociations.put( namedAssociationType.qualifiedName(), references );
+ }
+ } );
+
+ return new DefaultEntityState( entityPrefs.get( "version", "" ),
+ Instant.ofEpochMilli(entityPrefs.getLong( "modified", unitOfWork.currentTime().toEpochMilli() )),
+ reference,
+ status,
+ entityDescriptor,
+ properties,
+ associations,
+ manyAssociations,
+ namedAssociations
+ );
+ }
+ catch( ValueSerializationException | BackingStoreException e )
+ {
+ throw new EntityStoreException( e );
+ }
+ }
+
+ @Override
+ public String versionOf( EntityStoreUnitOfWork unitOfWork, EntityReference reference )
+ {
+ try
+ {
+ if( !root.nodeExists( reference.identity().toString() ) )
+ {
+ throw new NoSuchEntityException( reference, UnknownType.class, unitOfWork.usecase() );
+ }
+
+ Preferences entityPrefs = root.node( reference.identity().toString() );
+ return entityPrefs.get( "version", "" );
+ }
+ catch( BackingStoreException e )
+ {
+ throw new EntityStoreException( e );
+ }
+ }
+
+ @Override
+ public StateCommitter applyChanges( final EntityStoreUnitOfWork unitofwork, final Iterable<EntityState> state )
+ {
+ return new StateCommitter()
+ {
+ @SuppressWarnings( "SynchronizeOnNonFinalField" )
+ @Override
+ public void commit()
+ {
+ try
+ {
+ synchronized( root )
+ {
+ for( EntityState entityState : state )
+ {
+ DefaultEntityState state = (DefaultEntityState) entityState;
+ if( state.status().equals( EntityStatus.NEW ) )
+ {
+ Preferences entityPrefs = root.node( state.entityReference().identity().toString() );
+ writeEntityState( state, entityPrefs, unitofwork.identity(), unitofwork.currentTime() );
+ }
+ else if( state.status().equals( EntityStatus.UPDATED ) )
+ {
+ Preferences entityPrefs = root.node( state.entityReference().identity().toString() );
+ writeEntityState( state, entityPrefs, unitofwork.identity(), unitofwork.currentTime() );
+ }
+ else if( state.status().equals( EntityStatus.REMOVED ) )
+ {
+ root.node( state.entityReference().identity().toString() ).removeNode();
+ }
+ }
+ root.flush();
+ }
+ }
+ catch( BackingStoreException e )
+ {
+ throw new EntityStoreException( e );
+ }
+ }
+
+ @Override
+ public void cancel()
+ {
+ }
+ };
+ }
+
+ protected void writeEntityState( DefaultEntityState state,
+ Preferences entityPrefs,
+ Identity identity,
+ Instant lastModified
+ )
+ throws EntityStoreException
+ {
+ try
+ {
+ // Store into Preferences API
+ entityPrefs.put( "type", state.entityDescriptor().types().findFirst().get().getName() );
+ entityPrefs.put( "version", identity.toString() );
+ entityPrefs.putLong( "modified", lastModified.toEpochMilli() );
+
+ // Properties
+ Preferences propsPrefs = entityPrefs.node( "properties" );
+ state.entityDescriptor().state().properties()
+ .filter( property -> !property.qualifiedName().name().equals( "reference" ) )
+ .forEach( persistentProperty ->
+ {
+ Object value = state.properties().get( persistentProperty.qualifiedName() );
+
+ if( value == null )
+ {
+ propsPrefs.remove( persistentProperty.qualifiedName().name() );
+ }
+ else
+ {
+ ValueType valueType = persistentProperty.valueType();
+ Class<?> primaryType = valueType.primaryType();
+ if( Number.class.isAssignableFrom( primaryType ) )
+ {
+ if( primaryType.equals( Long.class ) )
+ {
+ propsPrefs.putLong( persistentProperty.qualifiedName().name(), (Long) value );
+ }
+ else if( primaryType.equals( Integer.class ) )
+ {
+ propsPrefs.putInt( persistentProperty.qualifiedName()
+ .name(), (Integer) value );
+ }
+ else if( primaryType.equals( Double.class ) )
+ {
+ propsPrefs.putDouble( persistentProperty.qualifiedName()
+ .name(), (Double) value );
+ }
+ else if( primaryType.equals( Float.class ) )
+ {
+ propsPrefs.putFloat( persistentProperty.qualifiedName()
+ .name(), (Float) value );
+ }
+ else
+ {
+ // Store as string even though it's a number
+ String jsonString = valueSerialization.serialize( value );
+ propsPrefs.put( persistentProperty.qualifiedName().name(), jsonString );
+ }
+ }
+ else if( primaryType.equals( Boolean.class ) )
+ {
+ propsPrefs.putBoolean( persistentProperty.qualifiedName()
+ .name(), (Boolean) value );
+ }
+ else if( valueType instanceof ValueCompositeType
+ || valueType instanceof MapType
+ || valueType instanceof CollectionType
+ || valueType instanceof EnumType )
+ {
+ String jsonString = valueSerialization.serialize( value );
+ propsPrefs.put( persistentProperty.qualifiedName().name(), jsonString );
+ }
+ else
+ {
+ String jsonString = valueSerialization.serialize( value );
+ propsPrefs.put( persistentProperty.qualifiedName().name(), jsonString );
+ }
+ }
+ } );
+
+ // Associations
+ if( !state.associations().isEmpty() )
+ {
+ Preferences assocsPrefs = entityPrefs.node( "associations" );
+ for( Map.Entry<QualifiedName, EntityReference> association : state.associations().entrySet() )
+ {
+ if( association.getValue() == null )
+ {
+ assocsPrefs.remove( association.getKey().name() );
+ }
+ else
+ {
+ assocsPrefs.put( association.getKey().name(), association.getValue().identity().toString() );
+ }
+ }
+ }
+
+ // ManyAssociations
+ if( !state.manyAssociations().isEmpty() )
+ {
+ Preferences manyAssocsPrefs = entityPrefs.node( "manyassociations" );
+ for( Map.Entry<QualifiedName, List<EntityReference>> manyAssociation : state.manyAssociations()
+ .entrySet() )
+ {
+ StringBuilder manyAssocs = new StringBuilder();
+ for( EntityReference entityReference : manyAssociation.getValue() )
+ {
+ if( manyAssocs.length() > 0 )
+ {
+ manyAssocs.append( "\n" );
+ }
+ manyAssocs.append( entityReference.identity().toString() );
+ }
+ if( manyAssocs.length() > 0 )
+ {
+ manyAssocsPrefs.put( manyAssociation.getKey().name(), manyAssocs.toString() );
+ }
+ }
+ }
+
+ // NamedAssociations
+ if( !state.namedAssociations().isEmpty() )
+ {
+ Preferences namedAssocsPrefs = entityPrefs.node( "namedassociations" );
+ for( Map.Entry<QualifiedName, Map<String, EntityReference>> namedAssociation : state.namedAssociations()
+ .entrySet() )
+ {
+ StringBuilder namedAssocs = new StringBuilder();
+ for( Map.Entry<String, EntityReference> namedRef : namedAssociation.getValue().entrySet() )
+ {
+ if( namedAssocs.length() > 0 )
+ {
+ namedAssocs.append( "\n" );
+ }
+ namedAssocs.append( namedRef.getKey() ).append( "\n" ).append( namedRef.getValue().identity().toString() );
+ }
+ if( namedAssocs.length() > 0 )
+ {
+ namedAssocsPrefs.put( namedAssociation.getKey().name(), namedAssocs.toString() );
+ }
+ }
+ }
+ }
+ catch( ValueSerializationException e )
+ {
+ throw new EntityStoreException( "Could not store EntityState", e );
+ }
+ }
+
+ protected Identity newUnitOfWorkId()
+ {
+ return identityGenerator.generate(EntityStore.class);
+ }
+
+ private interface NumberParser<T>
+ {
+ T parse( String str );
+ }
+
+ private static final NumberParser<Long> LONG_PARSER = Long::parseLong;
+
+ private static final NumberParser<Integer> INT_PARSER = Integer::parseInt;
+
+ private static final NumberParser<Double> DOUBLE_PARSER = Double::parseDouble;
+
+ private static final NumberParser<Float> FLOAT_PARSER = Float::parseFloat;
+
+ private <T> T getNumber( Preferences prefs, ModuleDescriptor module, PropertyDescriptor pDesc, NumberParser<T> parser )
+ {
+ Object initialValue = pDesc.resolveInitialValue( module );
+ String str = prefs.get( pDesc.qualifiedName().name(), initialValue == null ? null : initialValue.toString() );
+ T result = null;
+ if( str != null )
+ {
+ result = parser.parse( str );
+ }
+ return result;
+ }
+
+ private static class UnknownType
+ {
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/PreferencesEntityStoreService.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/PreferencesEntityStoreService.java b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/PreferencesEntityStoreService.java
new file mode 100644
index 0000000..b66e2c7
--- /dev/null
+++ b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/PreferencesEntityStoreService.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+
+package org.apache.polygene.entitystore.preferences;
+
+import org.apache.polygene.api.concern.Concerns;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.service.ServiceActivation;
+import org.apache.polygene.api.service.ServiceComposite;
+import org.apache.polygene.spi.entitystore.ConcurrentModificationCheckConcern;
+import org.apache.polygene.spi.entitystore.EntityStateVersions;
+import org.apache.polygene.spi.entitystore.EntityStore;
+
+/**
+ * EntityStore backed by Preferences API.
+ * <p>
+ * A root node is created in the System preferences, whose name
+ * is the same as the Application name (default:"Application").
+ * </p>
+ * <p>
+ * Each entity is stored under its identity name.
+ * </p>
+ * <p>
+ * Property types are converted to native Preferences API types
+ * as much as possible. All others will be serialized to a string using JSON.
+ * </p>
+ * <p>
+ * Associations are stored as the identity of the referenced Entity, ManyAssociations are stored as multi-line strings
+ * (one reference per line), and NamedAssociations are stored as multi-line strings (one name on a line, reference on the
+ * next line).
+ * </p>
+ * <p>
+ * The main use of the EntityStore is for storage of ConfigurationComposites for ServiceComposites.
+ * </p>
+ * @see org.apache.polygene.api.service.ServiceComposite
+ * @see org.apache.polygene.api.configuration.Configuration
+ */
+@Concerns( ConcurrentModificationCheckConcern.class )
+@Mixins( PreferencesEntityStoreMixin.class )
+public interface PreferencesEntityStoreService
+ extends EntityStore, ServiceComposite, EntityStateVersions, ServiceActivation
+{
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/assembly/PreferencesEntityStoreAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/assembly/PreferencesEntityStoreAssembler.java b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/assembly/PreferencesEntityStoreAssembler.java
new file mode 100644
index 0000000..53ea9de
--- /dev/null
+++ b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/assembly/PreferencesEntityStoreAssembler.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.entitystore.preferences.assembly;
+
+import java.util.prefs.Preferences;
+import org.apache.polygene.bootstrap.Assemblers;
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.bootstrap.ServiceDeclaration;
+import org.apache.polygene.entitystore.preferences.PreferencesEntityStoreInfo;
+import org.apache.polygene.entitystore.preferences.PreferencesEntityStoreService;
+
+public class PreferencesEntityStoreAssembler
+ extends Assemblers.VisibilityIdentityConfig<PreferencesEntityStoreAssembler>
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ throws AssemblyException
+ {
+ String applicationName = module.layer().application().name();
+
+ Preferences root = Preferences.userRoot();
+ Preferences node = root.node( applicationName );
+ PreferencesEntityStoreInfo info = new PreferencesEntityStoreInfo( node );
+ ServiceDeclaration service = module.services( PreferencesEntityStoreService.class )
+ .setMetaInfo( info )
+ .visibleIn( visibility() )
+ .instantiateOnStartup();
+ if( hasIdentity() )
+ {
+ service.identifiedBy( identity() );
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/assembly/package.html
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/assembly/package.html b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/assembly/package.html
new file mode 100644
index 0000000..564de79
--- /dev/null
+++ b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/assembly/package.html
@@ -0,0 +1,24 @@
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ ~
+ ~
+ -->
+<html>
+ <body>
+ <h2>Preferences EntityStore Assembly.</h2>
+ </body>
+</html>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/package.html
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/package.html b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/package.html
new file mode 100644
index 0000000..8e39337
--- /dev/null
+++ b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/package.html
@@ -0,0 +1,24 @@
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ ~
+ ~
+ -->
+<html>
+ <body>
+ <h2>Preferences EntityStore.</h2>
+ </body>
+</html>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/ListPreferencesNodes.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/ListPreferencesNodes.java b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/ListPreferencesNodes.java
deleted file mode 100644
index 35c3418..0000000
--- a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/ListPreferencesNodes.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.prefs;
-
-import java.util.prefs.BackingStoreException;
-import java.util.prefs.Preferences;
-
-public class ListPreferencesNodes
-{
- public static void main( String[] args )
- throws Exception
- {
- Preferences preferences = Preferences.userRoot();
- printNode( preferences, "" );
- }
-
- private static void printNode( Preferences node, String indent )
- throws BackingStoreException
- {
- System.out.print( indent );
- String name = node.name();
- if( "".equals( name ) )
- {
- name = "/";
- }
-
- System.out.print( name );
- String[] nodes = node.keys();
- if( nodes.length > 0 )
- {
- System.out.print( " { " );
- boolean first = true;
- for( String key : nodes )
- {
- if( !first )
- {
- System.out.print( ", " );
- }
- first = false;
- System.out.print( key );
- }
- System.out.print( " }" );
- }
- System.out.println();
- for( String childName : node.childrenNames() )
- {
- Preferences child = node.node( childName );
- printNode( child, indent + " " );
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/PreferencesEntityStoreInfo.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/PreferencesEntityStoreInfo.java b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/PreferencesEntityStoreInfo.java
deleted file mode 100644
index 9574844..0000000
--- a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/PreferencesEntityStoreInfo.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.prefs;
-
-import java.io.Serializable;
-import java.util.prefs.Preferences;
-
-/**
- * @author edward.yakop@gmail.com
- */
-public final class PreferencesEntityStoreInfo
- implements Serializable
-{
- private Preferences rootNode;
-
- public PreferencesEntityStoreInfo( Preferences aRootNode )
- {
- rootNode = aRootNode;
- }
-
- /**
- * @return root preference node to use.
- */
- public Preferences rootNode()
- {
- return rootNode;
- }
-}
\ No newline at end of file
[06/50] [abbrv] polygene-java git commit: Added support for
properties/associations/manyassociations/namedassociations for incoming
domain model composites. name/type
Posted by pa...@apache.org.
Added support for properties/associations/manyassociations/namedassociations for incoming domain model composites. name/type
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/0c7ee190
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/0c7ee190
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/0c7ee190
Branch: refs/heads/serialization-3.0
Commit: 0c7ee1909ce7e317182f34f011199276b5eeb18c
Parents: 284fb8e
Author: niclas <ni...@spicter.com>
Authored: Sat Mar 11 17:55:36 2017 +0800
Committer: niclas <ni...@spicter.com>
Committed: Sat Mar 11 17:55:36 2017 +0800
----------------------------------------------------------------------
tools/generator-polygene/app/index.js | 73 +++++++++++
.../DomainLayer/DomainModule/Configuration.tmpl | 37 ++++++
.../DomainLayer/DomainModule/Crud.tmpl | 10 +-
.../DomainLayer/DomainModule/Entity.tmpl | 10 +-
.../DomainLayer/DomainModule/Service.tmpl | 16 +++
.../DomainLayer/DomainModule/Transient.tmpl | 10 +-
.../DomainLayer/DomainModule/Value.tmpl | 13 +-
.../DomainLayer/DomainModule/bootstrap.tmpl | 131 ++++++++++++-------
.../DomainLayer/DomainModule/module.js | 9 +-
.../app/templates/DomainLayer/bootstrap.tmpl | 17 ++-
10 files changed, 263 insertions(+), 63 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/0c7ee190/tools/generator-polygene/app/index.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/index.js b/tools/generator-polygene/app/index.js
index a13be9d..7f76c10 100644
--- a/tools/generator-polygene/app/index.js
+++ b/tools/generator-polygene/app/index.js
@@ -287,4 +287,77 @@ function assignFunctions(polygene) {
polygene.firstUpper = function (text) {
return text.charAt(0).toUpperCase() + text.substring(1);
};
+ polygene.typeNameOnly = function(text) {
+ var lastPos = text.lastIndexOf(".");
+ if( lastPos < 0 ) {
+ return text;
+ }
+ return text.substring(lastPos + 1);
+ };
+
+ polygene.configurationClassName = function( clazzName ) {
+ if( clazzName.endsWith( "Service" )) {
+ clazzName = clazzName.substring(0, clazzName.length - 7 );
+ }
+ return clazzName + "Configuration";
+ };
+
+ polygene.prepareClazz = function (current) {
+ var state = [];
+ var imported = {};
+ var props = current.clazz.properties;
+ if( props ) {
+ for( var idx in props ) {
+ var prop = props[idx];
+ state.push( 'Property' + '<' + polygene.typeNameOnly(prop.type) + "> " + prop.name + "();")
+ imported[prop.type] = imported[prop.type];
+ }
+ } else {
+ state.push( 'Property<String> name(); // TODO: remove sample property')
+ }
+ var assocs = current.clazz.associations;
+ if( assocs ) {
+ for( var idx in assocs ) {
+ var assoc = assocs[idx];
+ state.push("Association" + '<' + polygene.typeNameOnly(assoc.type) + '>' + assoc.name + "();")
+ imported[assoc.type] = imported[assoc.type] ;
+ }
+ }
+ assocs = current.clazz.manyassociations;
+ if( assocs ) {
+ for( var idx in assocs ) {
+ var assoc = assocs[idx];
+ state.push("ManyAssociation<" + polygene.typeNameOnly(assoc.type) + ">" + assoc.name + "();")
+ imported[assoc.type] = imported[assoc.type] ;
+ }
+ }
+ assocs = current.clazz.namedassociations;
+ if( assocs ) {
+ for( var idx in assocs ) {
+ var assoc = assocs[idx];
+ state.push("NamedAssociation<" + polygene.typeNameOnly(assoc.type) + ">" + assoc.name + "();")
+ imported[assoc.type] = imported[assoc.type];
+ }
+ }
+ current.state = state;
+ current.imported = imported;
+ };
+
+ polygene.prepareConfigClazz = function (current) {
+ var state = [];
+ var imported = {};
+ var props = current.clazz.configuration;
+ if( props ) {
+ for( var idx in props ) {
+ var prop = props[idx];
+ state.push( 'Property' + '<' + polygene.typeNameOnly(prop.type) + "> " + prop.name + "();")
+ imported[prop.type] = imported[prop.type];
+ }
+ } else {
+ state.push( 'Property<String> name(); // TODO: remove sample property')
+ }
+ current.state = state;
+ current.imported = imported;
+ };
+
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/0c7ee190/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Configuration.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Configuration.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Configuration.tmpl
new file mode 100644
index 0000000..14c9735
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Configuration.tmpl
@@ -0,0 +1,37 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.model.<%= polygene.current.name %>;
+
+import org.apache.polygene.api.injection.scope.This;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.property.Property;
+<%
+for( var prop in polygene.current.imported ) {
+ if( !prop.startsWith( "java.lang" )) {
+ %><%- "import " + prop + ";"; %><%
+ }
+} %>
+
+public interface <%= polygene.current.clazz.name %>
+{
+<% for( var idx in polygene.current.state ) { %>
+ <%- polygene.current.state[idx]; %>
+<% } %>
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/0c7ee190/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl
index 95eed76..ecec763 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl
@@ -22,13 +22,21 @@ package <%= packageName %>.model.<%= polygene.current.name %>;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.property.Property;
+<%
+for( var prop in polygene.current.imported ) {
+ if( !prop.startsWith( "java.lang" )) {
+ %><%- "import " + prop + ";"; %><%
+ }
+} %>
@Mixins( { <%= polygene.current.clazz.name %>.Mixin.class } )
public interface <%= polygene.current.clazz.name %>
{
interface State
{
- Property<String> name(); // Sample hidden property
+<% for( var idx in polygene.current.state ) { %>
+ <%- polygene.current.state[idx]; %>
+<% } %>
}
class Mixin
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/0c7ee190/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl
index 95eed76..ecec763 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl
@@ -22,13 +22,21 @@ package <%= packageName %>.model.<%= polygene.current.name %>;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.property.Property;
+<%
+for( var prop in polygene.current.imported ) {
+ if( !prop.startsWith( "java.lang" )) {
+ %><%- "import " + prop + ";"; %><%
+ }
+} %>
@Mixins( { <%= polygene.current.clazz.name %>.Mixin.class } )
public interface <%= polygene.current.clazz.name %>
{
interface State
{
- Property<String> name(); // Sample hidden property
+<% for( var idx in polygene.current.state ) { %>
+ <%- polygene.current.state[idx]; %>
+<% } %>
}
class Mixin
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/0c7ee190/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Service.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Service.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Service.tmpl
index 0edefdc..5710441 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Service.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Service.tmpl
@@ -19,18 +19,34 @@
-%>
package <%= packageName %>.model.<%= polygene.current.name %>;
+import org.apache.polygene.api.configuration.Configuration;
import org.apache.polygene.api.injection.scope.Structure;
+import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
import org.apache.polygene.api.value.ValueBuilderFactory;
+<%
+for( var prop in polygene.current.imported ) {
+ if( !prop.startsWith( "java.lang" )) {
+ %><%- "import " + prop + ";"; %><%
+ }
+} %>
@Mixins( { <%= polygene.current.clazz.name %>.Mixin.class } )
public interface <%= polygene.current.clazz.name %>
{
+
class Mixin
implements <%= polygene.current.clazz.name %>
{
+ @This
+ private Configuration<<%- polygene.configurationClassName( polygene.current.clazz.name ); %>> configuration;
+
@Structure
private ValueBuilderFactory vbf;
+
+ @Structure
+ private UnitOfWorkFactory uowf;
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/0c7ee190/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Transient.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Transient.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Transient.tmpl
index 29f32e2..1fae121 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Transient.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Transient.tmpl
@@ -22,11 +22,19 @@ package <%= packageName %>.model.<%= polygene.current.name %>;
import org.apache.polygene.api.injection.scope.Uses;
import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.property.Property;
+<%
+for( var prop in polygene.current.imported ) {
+ if( !prop.startsWith( "java.lang" )) {
+ %><%- "import " + prop + ";"; %><%
+ }
+} %>
@Mixins( { <%= polygene.current.clazz.name %>.Mixin.class } )
public interface <%= polygene.current.clazz.name %>
{
- Property<String> name(); // Sample hidden property
+<% for( var idx in polygene.current.state ) { %>
+ <%- polygene.current.state[idx]; %>
+<% } %>
// If Property declarations are public, the Mixin must be abstract, because PropertyMixin will implement those methods.
abstract class Mixin
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/0c7ee190/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
index 95eed76..c4194e7 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
@@ -22,20 +22,27 @@ package <%= packageName %>.model.<%= polygene.current.name %>;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.property.Property;
+<%
+for( var prop in polygene.current.imported ) {
+ if( !prop.startsWith( "java.lang" )) {
+ %><%- "import " + prop + ";"; %><%
+ }
+} %>
@Mixins( { <%= polygene.current.clazz.name %>.Mixin.class } )
public interface <%= polygene.current.clazz.name %>
{
interface State
{
- Property<String> name(); // Sample hidden property
+<% for( var idx in polygene.current.state ) { %>
+ <%- polygene.current.state[idx]; %>
+<% } %>
}
class Mixin
implements <%= polygene.current.clazz.name %>
{
@This
- private State state; // Sample reference to hidden property
-
+ private State state; // Reference to private State instance
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/0c7ee190/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl
index 3ee206c..17b391a 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl
@@ -23,14 +23,36 @@ import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.LayerAssembly;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.bootstrap.layered.ModuleAssembler;
-<% for( var idx in polygene.current.cruds) { %>
-<%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.cruds[idx].name + ";" %>
-<% } %>
-<% for( var idx in polygene.current.values) { %><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.values[idx].name + ";" %><% } %>
-<% for( var idx in polygene.current.entities) { %><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.entities[idx].name + ";" %><% } %>
-<% for( var idx in polygene.current.transients) { %><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.transients[idx].name + ";" %><% } %>
-<% for( var idx in polygene.current.objects) { %><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.objects[idx].name + ";" %><% } %>
-<% for( var idx in polygene.current.services) { %><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.services[idx].name + ";" %><% } %>
+
+<% for( var idx in polygene.current.cruds) {
+%><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.cruds[idx].name + ";" %>
+<%
+}
+
+for( var idx in polygene.current.values) {
+%><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.values[idx].name + ";" %>
+<%
+}
+for( var idx in polygene.current.entities) {
+%><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.entities[idx].name + ";" %>
+<%
+}
+
+for( var idx in polygene.current.transients) {
+%><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.transients[idx].name + ";" %>
+<%
+}
+
+for( var idx in polygene.current.objects) {
+%><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.objects[idx].name + ";" %>
+<%
+}
+
+for( var idx in polygene.current.services) {
+%><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.services[idx].name + ";" %>
+<%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.configurationClassName(polygene.current.services[idx].name) + ";" %>
+<%
+} %>
import static org.apache.polygene.api.common.Visibility.layer;
import static org.apache.polygene.api.common.Visibility.application;
@@ -42,46 +64,57 @@ public class <%- firstUpper(polygene.current.name) %>Module
public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
throws AssemblyException
{
-<% if( polygene.current.cruds ) { %>
- <% for( var value in polygene.current.cruds ) { %>
- <% var crud1 = polygene.current.cruds[value]; %>
- module.values(<%- crud1.name + ".class" %>)<% if( crud1.visibility ) {%><%-".visibleIn(" + crud1.visibility +")"%><% } %>;
- <% } %>
- <% for( var value in polygene.current.cruds ) { %>
- <% var crud2 = polygene.current.cruds[value]; %>
- module.entities(<%= crud2.name + ".class" %>)<% if( crud2.visibility ) {%><%-".visibleIn(" + crud2.visibility +")"%><% } %>;
- <% } %>
-<% } %>
-<% if( polygene.current.values ) { %>
- <% for( var value in polygene.current.values ) { %>
- <% var v = polygene.current.values[value]; %>
- module.values(<%= v.name + ".class" %>)<% if( v.visibility ) {%><%-".visibleIn(" + v.visibility +")"%><% } %>;
- <% } %>
-<% } %>
-<% if( polygene.current.entities ) { %>
- <% for( var value in polygene.current.entities ) { %>
- <% var entity = polygene.current.entities[value]; %>
- module.values(<%= entity.name + ".class" %>)<% if( entity.visibility ) {%><%-".visibleIn(" + entity.visibility +")"%><% } %>;
- <% } %>
-<% } %>
-<% if( polygene.current.transients ) { %>
- <% for( var value in polygene.current.transients ) { %>
- <% var trans = polygene.current.transients[value]; %>
- module.values(<%= trans.name + ".class" %>)<% if( trans.visibility ) {%><%-".visibleIn(" + trans.visibility +")"%><% } %>;
- <% } %>
-<% } %>
-<% if( polygene.current.objects ) { %>
- <% for( var value in polygene.current.objects ) { %>
- <% var obj = polygene.current.objects[value]; %>
- module.values(<%= obj.name + ".class" %>)<% if( obj.visibility ) {%><%-".visibleIn(" + obj.visibility +")"%><% } %>;
- <% } %>
-<% } %>
-<% if( polygene.current.services ) { %>
- <% for( var value in polygene.current.services ) { %>
- <% var service = polygene.current.services[value]; %>
- module.values(<%= service.name + ".class" %>)<% if( service.visibility ) {%><%-".visibleIn(" + service.visibility +")"%><% } %>;
- <% } %>
-<% } %>
+<%
+if( polygene.current.cruds ) {
+ for( var value in polygene.current.cruds ) {
+ var crud = polygene.current.cruds[value];
+%>
+ <%- "module.values( " + crud.name + ".class )" + (crud.visibility ? ".visibleIn(" + crud.visibility +")" : "" ) %>;
+ <%- "module.entities( " + crud.name + ".class )" + (crud.visibility ? ".visibleIn(" + crud.visibility +")" : "" ) %>;
+<%
+ }
+}
+if( polygene.current.values ) {
+ for( var value in polygene.current.values ) {
+ var v = polygene.current.values[value];
+%>
+ <%- "module.values( " + v.name + ".class )" + (v.visibility ? ".visibleIn(" + v.visibility +")" : "" ) %>;
+<%
+ }
+}
+if( polygene.current.entities ) {
+ for( var value in polygene.current.entities ) {
+ var entity = polygene.current.entities[value];
+%>
+ <%- "module.entities( " + entity.name + ".class )" + (entity.visibility ? ".visibleIn(" + entity.visibility +")" : "" ) %>;
+<%
+ }
+}
+if( polygene.current.transients ) {
+ for( var value in polygene.current.transients ) {
+ var trans = polygene.current.transients[value];
+%>
+ <%- "module.transients( " + trans.name + ".class )" + (trans.visibility ? ".visibleIn(" + trans.visibility +")" : "" ) %>;
+<%
+ }
+}
+if( polygene.current.objects ) {
+ for( var value in polygene.current.objects ) {
+ var obj = polygene.current.objects[value];
+%>
+ <%- "module.objects( " + obj.name + ".class )" + (obj.visibility ? ".visibleIn(" + obj.visibility +")" : "" ) %>;
+<%
+ }
+}
+if( polygene.current.services ) {
+ for( var value in polygene.current.services ) {
+ var service = polygene.current.services[value];
+%>
+ <%- "module.services( " + service.name + ".class )" + (service.visibility ? ".visibleIn(" + service.visibility + ")" : "" ) %>;
+ <%- "module.entities( " + polygene.configurationClassName(service.name) + ".class )" %>;
+<%
+ }
+} %>
return module;
}
-}
\ No newline at end of file
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/0c7ee190/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js
index 2ceeaa5..3aea91c 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js
@@ -28,12 +28,19 @@ function copyPolygeneDomainModule(p, moduleName, moduleDef) {
copyComposites(p, moduleDef.transients, "Transient");
copyComposites(p, moduleDef.objects, "Object");
copyComposites(p, moduleDef.services, "Service");
+ copyComposites(p, moduleDef.services, "Configuration");
}
function copyComposites(p, composites, type) {
for (var idx in composites) {
if (composites.hasOwnProperty(idx)) {
- p.current.clazz = composites[idx];
+ if( type === "Configuration"){
+ p.current.clazz.name = p.configurationClassName(composites[idx].name);
+ p.prepareConfigClazz(p.current);
+ } else {
+ p.current.clazz = composites[idx];
+ p.prepareClazz(p.current);
+ }
p.copyTemplate(p.ctx,
'DomainLayer/DomainModule/' + type + '.tmpl',
'model/src/main/java/' + p.javaPackageDir + '/model/' + p.current.name + '/' + p.current.clazz.name + '.java');
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/0c7ee190/tools/generator-polygene/app/templates/DomainLayer/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/bootstrap.tmpl b/tools/generator-polygene/app/templates/DomainLayer/bootstrap.tmpl
index 63401be..68be6f3 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/bootstrap.tmpl
@@ -28,15 +28,18 @@ public class DomainLayer extends LayeredLayerAssembler
implements LayerAssembler
{
@Override
- public LayerAssembly assemble(LayerAssembly layer)
+ public LayerAssembly assemble( LayerAssembly layer )
throws AssemblyException
{
-<% if( hasFeature( 'rest api' ) ) { %>
- createModule( layer, CrudModule.class );
-<% } %>
-<% if( hasFeature( 'security' ) ) { %>
- createModule( layer, SecurityModule.class );
-<% } %>
+<% if( hasFeature( 'rest api' ) ) {
+%> createModule( layer, CrudModule.class );<%
+}
+for( var mod in polygene.modules ) {%>
+<%- " createModule( layer, " + polygene.firstUpper(mod) + "Module.class );" %><%
+}
+if( hasFeature( 'security' ) ) {
+%> createModule( layer, SecurityModule.class );<%
+} %>
return layer;
}
}
\ No newline at end of file
[26/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-jdbm/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/entitystore-jdbm/build.gradle b/extensions/entitystore-jdbm/build.gradle
index 4cfbdea..c195e0c 100644
--- a/extensions/entitystore-jdbm/build.gradle
+++ b/extensions/entitystore-jdbm/build.gradle
@@ -34,7 +34,6 @@ dependencies {
runtimeOnly polygene.core.runtime
testImplementation polygene.core.testsupport
- testImplementation polygene.extension( 'valueserialization-orgjson' )
testRuntimeOnly libraries.logback
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-jdbm/src/main/java/org/apache/polygene/entitystore/jdbm/JdbmEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-jdbm/src/main/java/org/apache/polygene/entitystore/jdbm/JdbmEntityStoreMixin.java b/extensions/entitystore-jdbm/src/main/java/org/apache/polygene/entitystore/jdbm/JdbmEntityStoreMixin.java
index ec1f703..312c002 100644
--- a/extensions/entitystore-jdbm/src/main/java/org/apache/polygene/entitystore/jdbm/JdbmEntityStoreMixin.java
+++ b/extensions/entitystore-jdbm/src/main/java/org/apache/polygene/entitystore/jdbm/JdbmEntityStoreMixin.java
@@ -140,7 +140,7 @@ public class JdbmEntityStoreMixin
changes.visitMap( new MapChanger()
{
@Override
- public Writer newEntity( final EntityReference ref, EntityDescriptor descriptor )
+ public Writer newEntity( EntityReference ref, EntityDescriptor descriptor )
throws IOException
{
return new StringWriter( 1000 )
@@ -160,7 +160,7 @@ public class JdbmEntityStoreMixin
}
@Override
- public Writer updateEntity( final EntityReference ref, EntityDescriptor descriptor )
+ public Writer updateEntity( MapChange mapChange )
throws IOException
{
return new StringWriter( 1000 )
@@ -171,7 +171,7 @@ public class JdbmEntityStoreMixin
{
super.close();
- Long stateIndex = getStateIndex( ref.identity() );
+ Long stateIndex = getStateIndex( mapChange.reference().identity() );
byte[] stateArray = toString().getBytes( "UTF-8" );
recordManager.update( stateIndex, stateArray, serializer );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-jdbm/src/test/java/org/apache/polygene/entitystore/jdbm/JdbmEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-jdbm/src/test/java/org/apache/polygene/entitystore/jdbm/JdbmEntityStoreTest.java b/extensions/entitystore-jdbm/src/test/java/org/apache/polygene/entitystore/jdbm/JdbmEntityStoreTest.java
index 2d1351b..bd3cef4 100644
--- a/extensions/entitystore-jdbm/src/test/java/org/apache/polygene/entitystore/jdbm/JdbmEntityStoreTest.java
+++ b/extensions/entitystore-jdbm/src/test/java/org/apache/polygene/entitystore/jdbm/JdbmEntityStoreTest.java
@@ -27,7 +27,6 @@ import org.apache.polygene.library.fileconfig.FileConfigurationAssembler;
import org.apache.polygene.library.fileconfig.FileConfigurationOverride;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
@@ -49,7 +48,6 @@ public class JdbmEntityStoreTest
new FileConfigurationAssembler()
.withOverride( new FileConfigurationOverride().withConventionalRoot( tmpDir.getRoot() ) )
.assemble( module );
- new OrgJsonValueSerializationAssembler().assemble( module );
new JdbmEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-jdbm/src/test/java/org/apache/polygene/entitystore/jdbm/JdbmEntityStoreWithCacheTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-jdbm/src/test/java/org/apache/polygene/entitystore/jdbm/JdbmEntityStoreWithCacheTest.java b/extensions/entitystore-jdbm/src/test/java/org/apache/polygene/entitystore/jdbm/JdbmEntityStoreWithCacheTest.java
index 0b633ea..b6bed70 100644
--- a/extensions/entitystore-jdbm/src/test/java/org/apache/polygene/entitystore/jdbm/JdbmEntityStoreWithCacheTest.java
+++ b/extensions/entitystore-jdbm/src/test/java/org/apache/polygene/entitystore/jdbm/JdbmEntityStoreWithCacheTest.java
@@ -27,7 +27,6 @@ import org.apache.polygene.library.fileconfig.FileConfigurationAssembler;
import org.apache.polygene.library.fileconfig.FileConfigurationOverride;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.cache.AbstractEntityStoreWithCacheTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
@@ -49,7 +48,6 @@ public class JdbmEntityStoreWithCacheTest
new FileConfigurationAssembler()
.withOverride( new FileConfigurationOverride().withConventionalRoot( tmpDir.getRoot() ) )
.assemble( module );
- new OrgJsonValueSerializationAssembler().assemble( module );
new JdbmEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-leveldb/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/entitystore-leveldb/build.gradle b/extensions/entitystore-leveldb/build.gradle
index 4fa7608..98b8460 100644
--- a/extensions/entitystore-leveldb/build.gradle
+++ b/extensions/entitystore-leveldb/build.gradle
@@ -36,7 +36,6 @@ dependencies {
runtimeOnly libraries.leveldb_jni_all
testImplementation polygene.core.testsupport
- testImplementation polygene.extension( 'valueserialization-orgjson' )
testRuntimeOnly libraries.logback
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-leveldb/src/main/java/org/apache/polygene/entitystore/leveldb/LevelDBEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-leveldb/src/main/java/org/apache/polygene/entitystore/leveldb/LevelDBEntityStoreMixin.java b/extensions/entitystore-leveldb/src/main/java/org/apache/polygene/entitystore/leveldb/LevelDBEntityStoreMixin.java
index bcc9975..1db246e 100644
--- a/extensions/entitystore-leveldb/src/main/java/org/apache/polygene/entitystore/leveldb/LevelDBEntityStoreMixin.java
+++ b/extensions/entitystore-leveldb/src/main/java/org/apache/polygene/entitystore/leveldb/LevelDBEntityStoreMixin.java
@@ -234,7 +234,7 @@ public class LevelDBEntityStoreMixin
@Override
public void applyChanges( MapChanges changes )
- throws IOException
+ throws Exception
{
final WriteBatch writeBatch = db.createWriteBatch();
try
@@ -243,7 +243,7 @@ public class LevelDBEntityStoreMixin
{
@Override
- public Writer newEntity( final EntityReference ref, EntityDescriptor entityDescriptor )
+ public Writer newEntity( EntityReference ref, EntityDescriptor entityDescriptor )
throws IOException
{
return new StringWriter( 1000 )
@@ -262,7 +262,7 @@ public class LevelDBEntityStoreMixin
}
@Override
- public Writer updateEntity( final EntityReference ref, EntityDescriptor entityDescriptor )
+ public Writer updateEntity( MapChange mapChange )
throws IOException
{
return new StringWriter( 1000 )
@@ -274,7 +274,8 @@ public class LevelDBEntityStoreMixin
{
super.close();
String jsonState = toString();
- writeBatch.put( ref.identity().toString().getBytes( charset ), jsonState.getBytes( charset ) );
+ writeBatch.put( mapChange.reference().identity().toString().getBytes( charset ),
+ jsonState.getBytes( charset ) );
}
};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-leveldb/src/test/java/org/apache/polygene/entitystore/leveldb/JavaLevelDBEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-leveldb/src/test/java/org/apache/polygene/entitystore/leveldb/JavaLevelDBEntityStoreTest.java b/extensions/entitystore-leveldb/src/test/java/org/apache/polygene/entitystore/leveldb/JavaLevelDBEntityStoreTest.java
index 1b5ff6a..c5d4cdc 100644
--- a/extensions/entitystore-leveldb/src/test/java/org/apache/polygene/entitystore/leveldb/JavaLevelDBEntityStoreTest.java
+++ b/extensions/entitystore-leveldb/src/test/java/org/apache/polygene/entitystore/leveldb/JavaLevelDBEntityStoreTest.java
@@ -27,7 +27,6 @@ import org.apache.polygene.library.fileconfig.FileConfigurationAssembler;
import org.apache.polygene.library.fileconfig.FileConfigurationOverride;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
@@ -46,7 +45,6 @@ public class JavaLevelDBEntityStoreTest
super.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().visibleIn( Visibility.module ).assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
new FileConfigurationAssembler()
.withOverride( new FileConfigurationOverride().withConventionalRoot( tmpDir.getRoot() ) )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-leveldb/src/test/java/org/apache/polygene/entitystore/leveldb/JniLevelDBEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-leveldb/src/test/java/org/apache/polygene/entitystore/leveldb/JniLevelDBEntityStoreTest.java b/extensions/entitystore-leveldb/src/test/java/org/apache/polygene/entitystore/leveldb/JniLevelDBEntityStoreTest.java
index e0f14b2..819d930 100644
--- a/extensions/entitystore-leveldb/src/test/java/org/apache/polygene/entitystore/leveldb/JniLevelDBEntityStoreTest.java
+++ b/extensions/entitystore-leveldb/src/test/java/org/apache/polygene/entitystore/leveldb/JniLevelDBEntityStoreTest.java
@@ -27,7 +27,6 @@ import org.apache.polygene.library.fileconfig.FileConfigurationAssembler;
import org.apache.polygene.library.fileconfig.FileConfigurationOverride;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
@@ -45,7 +44,6 @@ public class JniLevelDBEntityStoreTest
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().visibleIn( Visibility.module ).assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
new FileConfigurationAssembler()
.withOverride( new FileConfigurationOverride().withConventionalRoot( tmpDir.getRoot() ) )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-leveldb/src/test/java/org/apache/polygene/entitystore/leveldb/LevelDBEntityStoreWithCacheTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-leveldb/src/test/java/org/apache/polygene/entitystore/leveldb/LevelDBEntityStoreWithCacheTest.java b/extensions/entitystore-leveldb/src/test/java/org/apache/polygene/entitystore/leveldb/LevelDBEntityStoreWithCacheTest.java
index f512a14..9840501 100644
--- a/extensions/entitystore-leveldb/src/test/java/org/apache/polygene/entitystore/leveldb/LevelDBEntityStoreWithCacheTest.java
+++ b/extensions/entitystore-leveldb/src/test/java/org/apache/polygene/entitystore/leveldb/LevelDBEntityStoreWithCacheTest.java
@@ -27,7 +27,6 @@ import org.apache.polygene.library.fileconfig.FileConfigurationAssembler;
import org.apache.polygene.library.fileconfig.FileConfigurationOverride;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.cache.AbstractEntityStoreWithCacheTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
@@ -44,7 +43,6 @@ public class LevelDBEntityStoreWithCacheTest
super.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().visibleIn( Visibility.module ).assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
new FileConfigurationAssembler()
.withOverride( new FileConfigurationOverride().withConventionalRoot( tmpDir.getRoot() ) )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-memory/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/entitystore-memory/build.gradle b/extensions/entitystore-memory/build.gradle
index 0f3e713..f46ae73 100644
--- a/extensions/entitystore-memory/build.gradle
+++ b/extensions/entitystore-memory/build.gradle
@@ -28,7 +28,6 @@ dependencies {
runtimeOnly polygene.core.runtime
testImplementation polygene.core.testsupport
- testImplementation polygene.extension( 'valueserialization-orgjson' )
testRuntimeOnly libraries.logback
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-memory/src/test/java/org/apache/polygene/entitystore/memory/MemoryEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-memory/src/test/java/org/apache/polygene/entitystore/memory/MemoryEntityStoreTest.java b/extensions/entitystore-memory/src/test/java/org/apache/polygene/entitystore/memory/MemoryEntityStoreTest.java
index ed74805..f36cca5 100644
--- a/extensions/entitystore-memory/src/test/java/org/apache/polygene/entitystore/memory/MemoryEntityStoreTest.java
+++ b/extensions/entitystore-memory/src/test/java/org/apache/polygene/entitystore/memory/MemoryEntityStoreTest.java
@@ -19,24 +19,19 @@
*/
package org.apache.polygene.entitystore.memory;
-import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.memory.assembly.MemoryEntityStoreAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
public class MemoryEntityStoreTest
extends AbstractEntityStoreTest
{
-
// START SNIPPET: assembly
@Override
public void assemble( ModuleAssembly module )
- throws AssemblyException
{
new MemoryEntityStoreAssembler().assemble( module );
// END SNIPPET: assembly
- new OrgJsonValueSerializationAssembler().assemble( module );
super.assemble( module );
// START SNIPPET: assembly
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-memory/src/test/java/org/apache/polygene/entitystore/memory/MemoryEntityStoreWithCacheTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-memory/src/test/java/org/apache/polygene/entitystore/memory/MemoryEntityStoreWithCacheTest.java b/extensions/entitystore-memory/src/test/java/org/apache/polygene/entitystore/memory/MemoryEntityStoreWithCacheTest.java
index c3ccaff..28dc102 100644
--- a/extensions/entitystore-memory/src/test/java/org/apache/polygene/entitystore/memory/MemoryEntityStoreWithCacheTest.java
+++ b/extensions/entitystore-memory/src/test/java/org/apache/polygene/entitystore/memory/MemoryEntityStoreWithCacheTest.java
@@ -23,7 +23,6 @@ import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.memory.assembly.MemoryEntityStoreAssembler;
import org.apache.polygene.test.cache.AbstractEntityStoreWithCacheTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
public class MemoryEntityStoreWithCacheTest
extends AbstractEntityStoreWithCacheTest
@@ -33,7 +32,6 @@ public class MemoryEntityStoreWithCacheTest
throws AssemblyException
{
super.assemble( module );
- new OrgJsonValueSerializationAssembler().assemble( module );
new MemoryEntityStoreAssembler().assemble( module );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-mongodb/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/entitystore-mongodb/build.gradle b/extensions/entitystore-mongodb/build.gradle
index 12d23c4..8ace38e 100644
--- a/extensions/entitystore-mongodb/build.gradle
+++ b/extensions/entitystore-mongodb/build.gradle
@@ -33,7 +33,6 @@ dependencies {
runtimeOnly polygene.core.runtime
testImplementation polygene.core.testsupport
- testImplementation polygene.extension( 'valueserialization-orgjson' )
testImplementation libraries.embed_mongo
testRuntimeOnly libraries.logback
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-mongodb/src/main/java/org/apache/polygene/entitystore/mongodb/MongoMapEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-mongodb/src/main/java/org/apache/polygene/entitystore/mongodb/MongoMapEntityStoreMixin.java b/extensions/entitystore-mongodb/src/main/java/org/apache/polygene/entitystore/mongodb/MongoMapEntityStoreMixin.java
index bda729c..106325d 100644
--- a/extensions/entitystore-mongodb/src/main/java/org/apache/polygene/entitystore/mongodb/MongoMapEntityStoreMixin.java
+++ b/extensions/entitystore-mongodb/src/main/java/org/apache/polygene/entitystore/mongodb/MongoMapEntityStoreMixin.java
@@ -222,14 +222,14 @@ public class MongoMapEntityStoreMixin
@Override
public void applyChanges( MapChanges changes )
- throws IOException
+ throws Exception
{
final MongoCollection<Document> entities = db.getCollection( collectionName );
changes.visitMap( new MapChanger()
{
@Override
- public Writer newEntity( final EntityReference ref, EntityDescriptor entityDescriptor )
+ public Writer newEntity( EntityReference ref, EntityDescriptor entityDescriptor )
throws IOException
{
return new StringWriter( 1000 )
@@ -249,7 +249,7 @@ public class MongoMapEntityStoreMixin
}
@Override
- public Writer updateEntity( final EntityReference ref, EntityDescriptor entityDescriptor )
+ public Writer updateEntity( MapChange mapChange )
throws IOException
{
return new StringWriter( 1000 )
@@ -261,9 +261,9 @@ public class MongoMapEntityStoreMixin
super.close();
Document bsonState = Document.parse( toString() );
Document entity = new Document();
- entity.put( IDENTITY_COLUMN, ref.identity().toString() );
+ entity.put( IDENTITY_COLUMN, mapChange.reference().identity().toString() );
entity.put( STATE_COLUMN, bsonState );
- entities.replaceOne( byIdentity( ref ), entity );
+ entities.replaceOne( byIdentity( mapChange.reference() ), entity );
}
};
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-mongodb/src/test/java/org/apache/polygene/entitystore/mongodb/EmbedMongoMapEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-mongodb/src/test/java/org/apache/polygene/entitystore/mongodb/EmbedMongoMapEntityStoreTest.java b/extensions/entitystore-mongodb/src/test/java/org/apache/polygene/entitystore/mongodb/EmbedMongoMapEntityStoreTest.java
index 68652a4..2341777 100644
--- a/extensions/entitystore-mongodb/src/test/java/org/apache/polygene/entitystore/mongodb/EmbedMongoMapEntityStoreTest.java
+++ b/extensions/entitystore-mongodb/src/test/java/org/apache/polygene/entitystore/mongodb/EmbedMongoMapEntityStoreTest.java
@@ -31,7 +31,6 @@ import org.apache.polygene.entitystore.mongodb.assembly.MongoDBEntityStoreAssemb
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
import org.apache.polygene.test.util.FreePortFinder;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
@@ -76,8 +75,6 @@ public class EmbedMongoMapEntityStoreTest extends AbstractEntityStoreTest
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
-
new MongoDBEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-mongodb/src/test/java/org/apache/polygene/entitystore/mongodb/MongoMapEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-mongodb/src/test/java/org/apache/polygene/entitystore/mongodb/MongoMapEntityStoreTest.java b/extensions/entitystore-mongodb/src/test/java/org/apache/polygene/entitystore/mongodb/MongoMapEntityStoreTest.java
index f893aff..aa9b9e3 100644
--- a/extensions/entitystore-mongodb/src/test/java/org/apache/polygene/entitystore/mongodb/MongoMapEntityStoreTest.java
+++ b/extensions/entitystore-mongodb/src/test/java/org/apache/polygene/entitystore/mongodb/MongoMapEntityStoreTest.java
@@ -20,14 +20,13 @@
package org.apache.polygene.entitystore.mongodb;
import com.mongodb.Mongo;
-import org.apache.polygene.entitystore.mongodb.assembly.MongoDBEntityStoreAssembler;
-import org.junit.BeforeClass;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.entitystore.mongodb.assembly.MongoDBEntityStoreAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
+import org.junit.BeforeClass;
import static org.apache.polygene.test.util.Assume.assumeConnectivity;
@@ -55,8 +54,6 @@ public class MongoMapEntityStoreTest
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
-
// START SNIPPET: assembly
new MongoDBEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
// END SNIPPET: assembly
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-mongodb/src/test/java/org/apache/polygene/entitystore/mongodb/MongoMapEntityStoreWithCacheTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-mongodb/src/test/java/org/apache/polygene/entitystore/mongodb/MongoMapEntityStoreWithCacheTest.java b/extensions/entitystore-mongodb/src/test/java/org/apache/polygene/entitystore/mongodb/MongoMapEntityStoreWithCacheTest.java
index de356f1..cad95ea 100644
--- a/extensions/entitystore-mongodb/src/test/java/org/apache/polygene/entitystore/mongodb/MongoMapEntityStoreWithCacheTest.java
+++ b/extensions/entitystore-mongodb/src/test/java/org/apache/polygene/entitystore/mongodb/MongoMapEntityStoreWithCacheTest.java
@@ -20,14 +20,13 @@
package org.apache.polygene.entitystore.mongodb;
import com.mongodb.Mongo;
-import org.apache.polygene.entitystore.mongodb.assembly.MongoDBEntityStoreAssembler;
-import org.junit.BeforeClass;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.entitystore.mongodb.assembly.MongoDBEntityStoreAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.cache.AbstractEntityStoreWithCacheTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
+import org.junit.BeforeClass;
import static org.apache.polygene.test.util.Assume.assumeConnectivity;
@@ -53,8 +52,6 @@ public class MongoMapEntityStoreWithCacheTest
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
-
new MongoDBEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
MongoEntityStoreConfiguration mongoConfig = config.forMixin( MongoEntityStoreConfiguration.class ).declareDefaults();
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-preferences/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/build.gradle b/extensions/entitystore-preferences/build.gradle
index 2c8bbff..b4681d6 100644
--- a/extensions/entitystore-preferences/build.gradle
+++ b/extensions/entitystore-preferences/build.gradle
@@ -32,7 +32,6 @@ dependencies {
runtimeOnly polygene.core.runtime
testImplementation polygene.core.testsupport
- testImplementation polygene.extension( 'valueserialization-orgjson' )
testRuntimeOnly libraries.logback
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/PreferencesEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/PreferencesEntityStoreMixin.java b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/PreferencesEntityStoreMixin.java
index fa32a71..4d6e65a 100644
--- a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/PreferencesEntityStoreMixin.java
+++ b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/preferences/PreferencesEntityStoreMixin.java
@@ -43,7 +43,8 @@ import org.apache.polygene.api.injection.scope.Uses;
import org.apache.polygene.api.property.PropertyDescriptor;
import org.apache.polygene.api.service.ServiceActivation;
import org.apache.polygene.api.service.ServiceDescriptor;
-import org.apache.polygene.api.service.qualifier.Tagged;
+import org.apache.polygene.api.serialization.Serialization;
+import org.apache.polygene.api.serialization.SerializationException;
import org.apache.polygene.api.structure.Application;
import org.apache.polygene.api.structure.ModuleDescriptor;
import org.apache.polygene.api.time.SystemTime;
@@ -56,8 +57,6 @@ import org.apache.polygene.api.unitofwork.NoSuchEntityException;
import org.apache.polygene.api.unitofwork.NoSuchEntityTypeException;
import org.apache.polygene.api.usecase.Usecase;
import org.apache.polygene.api.usecase.UsecaseBuilder;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.api.value.ValueSerializationException;
import org.apache.polygene.spi.PolygeneSPI;
import org.apache.polygene.spi.entity.EntityState;
import org.apache.polygene.spi.entity.EntityStatus;
@@ -80,7 +79,7 @@ import org.slf4j.LoggerFactory;
* (one reference per line), and NamedAssociations are stored as multi-line strings (one name on a line, reference on the
* next line).
* </p>
- * <p>Nested ValuesComposites, Collections and Maps are stored using available ValueSerialization service.</p>
+ * <p>Nested ValuesComposites, Collections and Maps are stored using available StateSerialization service.</p>
*/
public class PreferencesEntityStoreMixin
implements ServiceActivation, EntityStore, EntityStoreSPI
@@ -98,8 +97,7 @@ public class PreferencesEntityStoreMixin
private Application application;
@Service
- @Tagged( ValueSerialization.Formats.JSON )
- private ValueSerialization valueSerialization;
+ private Serialization serialization;
private Preferences root;
@@ -263,16 +261,16 @@ public class PreferencesEntityStoreMixin
else
{
// Load as string even though it's a number
- String json = propsPrefs.get( persistentPropertyDescriptor.qualifiedName()
- .name(), null );
+ String string = propsPrefs.get( persistentPropertyDescriptor.qualifiedName()
+ .name(), null );
Object value;
- if( json == null )
+ if( string == null )
{
value = null;
}
else
{
- value = valueSerialization.deserialize( module, persistentPropertyDescriptor.valueType(), json );
+ value = serialization.deserialize( module, propertyType, string );
}
properties.put( persistentPropertyDescriptor.qualifiedName(), value );
}
@@ -289,27 +287,27 @@ public class PreferencesEntityStoreMixin
|| propertyType instanceof CollectionType
|| propertyType instanceof EnumType )
{
- String json = propsPrefs.get( persistentPropertyDescriptor.qualifiedName().name(), null );
+ String string = propsPrefs.get( persistentPropertyDescriptor.qualifiedName().name(), null );
Object value;
- if( json == null )
+ if( string == null )
{
value = null;
}
else
{
- value = valueSerialization.deserialize( module, persistentPropertyDescriptor.valueType(), json );
+ value = serialization.deserialize( module, propertyType, string );
}
properties.put( persistentPropertyDescriptor.qualifiedName(), value );
}
else
{
- String json = propsPrefs.get( persistentPropertyDescriptor.qualifiedName().name(), null );
- if( json == null )
+ String string = propsPrefs.get( persistentPropertyDescriptor.qualifiedName().name(), null );
+ if( string == null )
{
if( persistentPropertyDescriptor.resolveInitialValue( module ) != null )
{
properties.put( persistentPropertyDescriptor.qualifiedName(),
- persistentPropertyDescriptor.resolveInitialValue( module ) );
+ persistentPropertyDescriptor.resolveInitialValue( module ) );
}
else
{
@@ -318,7 +316,7 @@ public class PreferencesEntityStoreMixin
}
else
{
- Object value = valueSerialization.deserialize( module, propertyType, json );
+ Object value = serialization.deserialize( module, propertyType, string );
properties.put( persistentPropertyDescriptor.qualifiedName(), value );
}
}
@@ -402,7 +400,7 @@ public class PreferencesEntityStoreMixin
namedAssociations
);
}
- catch( ValueSerializationException | BackingStoreException e )
+ catch( SerializationException | BackingStoreException e )
{
throw new EntityStoreException( e );
}
@@ -528,8 +526,8 @@ public class PreferencesEntityStoreMixin
else
{
// Store as string even though it's a number
- String jsonString = valueSerialization.serialize( value );
- propsPrefs.put( persistentProperty.qualifiedName().name(), jsonString );
+ String string = serialization.serialize( value );
+ propsPrefs.put( persistentProperty.qualifiedName().name(), string );
}
}
else if( primaryType.equals( Boolean.class ) )
@@ -542,13 +540,13 @@ public class PreferencesEntityStoreMixin
|| valueType instanceof CollectionType
|| valueType instanceof EnumType )
{
- String jsonString = valueSerialization.serialize( value );
- propsPrefs.put( persistentProperty.qualifiedName().name(), jsonString );
+ String string = serialization.serialize( value );
+ propsPrefs.put( persistentProperty.qualifiedName().name(), string );
}
else
{
- String jsonString = valueSerialization.serialize( value );
- propsPrefs.put( persistentProperty.qualifiedName().name(), jsonString );
+ String string = serialization.serialize( value );
+ propsPrefs.put( persistentProperty.qualifiedName().name(), string );
}
}
} );
@@ -616,7 +614,7 @@ public class PreferencesEntityStoreMixin
}
}
}
- catch( ValueSerializationException e )
+ catch( SerializationException e )
{
throw new EntityStoreException( "Could not store EntityState", e );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-preferences/src/test/java/org/apache/polygene/entitystore/PreferencesEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/test/java/org/apache/polygene/entitystore/PreferencesEntityStoreTest.java b/extensions/entitystore-preferences/src/test/java/org/apache/polygene/entitystore/PreferencesEntityStoreTest.java
index 10be81e..3a65af6 100644
--- a/extensions/entitystore-preferences/src/test/java/org/apache/polygene/entitystore/PreferencesEntityStoreTest.java
+++ b/extensions/entitystore-preferences/src/test/java/org/apache/polygene/entitystore/PreferencesEntityStoreTest.java
@@ -25,7 +25,6 @@ import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.preferences.PreferencesEntityStoreInfo;
import org.apache.polygene.entitystore.preferences.PreferencesEntityStoreService;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
@@ -51,6 +50,5 @@ public class PreferencesEntityStoreTest
PreferencesEntityStoreInfo metaInfo = new PreferencesEntityStoreInfo( node );
Thread.currentThread().setContextClassLoader( cl );
module.services( PreferencesEntityStoreService.class ).setMetaInfo( metaInfo ).instantiateOnStartup();
- new OrgJsonValueSerializationAssembler().assemble( module );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-redis/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/entitystore-redis/build.gradle b/extensions/entitystore-redis/build.gradle
index afe5978..da29e7d 100644
--- a/extensions/entitystore-redis/build.gradle
+++ b/extensions/entitystore-redis/build.gradle
@@ -33,7 +33,6 @@ dependencies {
runtimeOnly polygene.core.runtime
testImplementation polygene.internals.testsupport
- testImplementation polygene.extension( 'valueserialization-orgjson' )
testRuntimeOnly libraries.logback
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-redis/src/main/java/org/apache/polygene/entitystore/redis/RedisMapEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-redis/src/main/java/org/apache/polygene/entitystore/redis/RedisMapEntityStoreMixin.java b/extensions/entitystore-redis/src/main/java/org/apache/polygene/entitystore/redis/RedisMapEntityStoreMixin.java
index c080082..0fcb2c5 100644
--- a/extensions/entitystore-redis/src/main/java/org/apache/polygene/entitystore/redis/RedisMapEntityStoreMixin.java
+++ b/extensions/entitystore-redis/src/main/java/org/apache/polygene/entitystore/redis/RedisMapEntityStoreMixin.java
@@ -98,14 +98,14 @@ public class RedisMapEntityStoreMixin
@Override
public void applyChanges( MapChanges changes )
- throws IOException
+ throws Exception
{
try( Jedis jedis = pool.getResource() )
{
changes.visitMap( new MapChanger()
{
@Override
- public Writer newEntity( final EntityReference ref, EntityDescriptor entityDescriptor )
+ public Writer newEntity( EntityReference ref, EntityDescriptor entityDescriptor )
throws IOException
{
return new StringWriter( 1000 )
@@ -125,7 +125,7 @@ public class RedisMapEntityStoreMixin
}
@Override
- public Writer updateEntity( final EntityReference ref, EntityDescriptor entityDescriptor )
+ public Writer updateEntity( MapChange mapChange )
throws IOException
{
return new StringWriter( 1000 )
@@ -135,10 +135,12 @@ public class RedisMapEntityStoreMixin
throws IOException
{
super.close();
- String statusCode = jedis.set( ref.identity().toString(), toString(), "XX" );
+ String statusCode = jedis.set( mapChange.reference().identity().toString(),
+ toString(),
+ "XX" );
if( !"OK".equals( statusCode ) )
{
- throw new EntityNotFoundException( ref );
+ throw new EntityNotFoundException( mapChange.reference() );
}
}
};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-redis/src/test/java/org/apache/polygene/entitystore/redis/RedisMapEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-redis/src/test/java/org/apache/polygene/entitystore/redis/RedisMapEntityStoreTest.java b/extensions/entitystore-redis/src/test/java/org/apache/polygene/entitystore/redis/RedisMapEntityStoreTest.java
index e5ef9f8..e654afc 100644
--- a/extensions/entitystore-redis/src/test/java/org/apache/polygene/entitystore/redis/RedisMapEntityStoreTest.java
+++ b/extensions/entitystore-redis/src/test/java/org/apache/polygene/entitystore/redis/RedisMapEntityStoreTest.java
@@ -23,10 +23,9 @@ import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.redis.assembly.RedisEntityStoreAssembler;
-import org.apache.polygene.test.internal.DockerRule;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
+import org.apache.polygene.test.internal.DockerRule;
import org.junit.ClassRule;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
@@ -46,7 +45,6 @@ public class RedisMapEntityStoreTest
super.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
// START SNIPPET: assembly
new RedisEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
// END SNIPPET: assembly
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-redis/src/test/java/org/apache/polygene/entitystore/redis/RedisMapEntityStoreWithCacheTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-redis/src/test/java/org/apache/polygene/entitystore/redis/RedisMapEntityStoreWithCacheTest.java b/extensions/entitystore-redis/src/test/java/org/apache/polygene/entitystore/redis/RedisMapEntityStoreWithCacheTest.java
index f4499a1..1dba76a 100644
--- a/extensions/entitystore-redis/src/test/java/org/apache/polygene/entitystore/redis/RedisMapEntityStoreWithCacheTest.java
+++ b/extensions/entitystore-redis/src/test/java/org/apache/polygene/entitystore/redis/RedisMapEntityStoreWithCacheTest.java
@@ -23,10 +23,9 @@ import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.redis.assembly.RedisEntityStoreAssembler;
-import org.apache.polygene.test.internal.DockerRule;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.cache.AbstractEntityStoreWithCacheTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
+import org.apache.polygene.test.internal.DockerRule;
import org.junit.ClassRule;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
@@ -44,7 +43,6 @@ public class RedisMapEntityStoreWithCacheTest
super.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
new RedisEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
RedisEntityStoreConfiguration redisConfig = config.forMixin( RedisEntityStoreConfiguration.class )
.declareDefaults();
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-riak/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/entitystore-riak/build.gradle b/extensions/entitystore-riak/build.gradle
index a36ca6c..98200ac 100644
--- a/extensions/entitystore-riak/build.gradle
+++ b/extensions/entitystore-riak/build.gradle
@@ -34,7 +34,6 @@ dependencies {
runtimeOnly polygene.core.runtime
testImplementation polygene.internals.testsupport
- testImplementation polygene.extension( 'valueserialization-orgjson' )
testImplementation libraries.awaitility
testRuntimeOnly libraries.logback
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-riak/src/main/java/org/apache/polygene/entitystore/riak/RiakMapEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-riak/src/main/java/org/apache/polygene/entitystore/riak/RiakMapEntityStoreMixin.java b/extensions/entitystore-riak/src/main/java/org/apache/polygene/entitystore/riak/RiakMapEntityStoreMixin.java
index bb461cd..9417df5 100644
--- a/extensions/entitystore-riak/src/main/java/org/apache/polygene/entitystore/riak/RiakMapEntityStoreMixin.java
+++ b/extensions/entitystore-riak/src/main/java/org/apache/polygene/entitystore/riak/RiakMapEntityStoreMixin.java
@@ -199,8 +199,7 @@ public class RiakMapEntityStoreMixin implements ServiceActivation, MapEntityStor
}
@Override
- public void passivateService()
- throws Exception
+ public void passivateService() throws Exception
{
riakClient.shutdown();
riakClient = null;
@@ -248,7 +247,7 @@ public class RiakMapEntityStoreMixin implements ServiceActivation, MapEntityStor
changes.visitMap( new MapChanger()
{
@Override
- public Writer newEntity( final EntityReference ref, EntityDescriptor entityDescriptor )
+ public Writer newEntity( EntityReference ref, EntityDescriptor entityDescriptor )
{
return new StringWriter( 1000 )
{
@@ -272,7 +271,7 @@ public class RiakMapEntityStoreMixin implements ServiceActivation, MapEntityStor
}
@Override
- public Writer updateEntity( final EntityReference ref, EntityDescriptor entityDescriptor )
+ public Writer updateEntity( MapChange mapChange )
{
return new StringWriter( 1000 )
{
@@ -282,12 +281,13 @@ public class RiakMapEntityStoreMixin implements ServiceActivation, MapEntityStor
try
{
super.close();
- Location location = new Location( namespace, ref.identity().toString() );
+ EntityReference reference = mapChange.reference();
+ Location location = new Location( namespace, reference.identity().toString() );
FetchValue fetch = new FetchValue.Builder( location ).build();
FetchValue.Response response = riakClient.execute( fetch );
if( response.isNotFound() )
{
- throw new EntityNotFoundException( ref );
+ throw new EntityNotFoundException( reference );
}
StoreValue store = new StoreValue.Builder( toString() )
.withLocation( location )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-riak/src/test/java/org/apache/polygene/entitystore/riak/RiakMapEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-riak/src/test/java/org/apache/polygene/entitystore/riak/RiakMapEntityStoreTest.java b/extensions/entitystore-riak/src/test/java/org/apache/polygene/entitystore/riak/RiakMapEntityStoreTest.java
index 54a8f81..b02f361 100644
--- a/extensions/entitystore-riak/src/test/java/org/apache/polygene/entitystore/riak/RiakMapEntityStoreTest.java
+++ b/extensions/entitystore-riak/src/test/java/org/apache/polygene/entitystore/riak/RiakMapEntityStoreTest.java
@@ -24,7 +24,6 @@ import org.apache.polygene.entitystore.riak.assembly.RiakEntityStoreAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
import org.apache.polygene.test.internal.DockerRule;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.junit.ClassRule;
public class RiakMapEntityStoreTest extends AbstractEntityStoreTest
@@ -58,7 +57,6 @@ public class RiakMapEntityStoreTest extends AbstractEntityStoreTest
super.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
// START SNIPPET: assembly
new RiakEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
// END SNIPPET: assembly
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-riak/src/test/java/org/apache/polygene/entitystore/riak/RiakMapEntityStoreWithCacheTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-riak/src/test/java/org/apache/polygene/entitystore/riak/RiakMapEntityStoreWithCacheTest.java b/extensions/entitystore-riak/src/test/java/org/apache/polygene/entitystore/riak/RiakMapEntityStoreWithCacheTest.java
index 85946cd..a729d1d 100644
--- a/extensions/entitystore-riak/src/test/java/org/apache/polygene/entitystore/riak/RiakMapEntityStoreWithCacheTest.java
+++ b/extensions/entitystore-riak/src/test/java/org/apache/polygene/entitystore/riak/RiakMapEntityStoreWithCacheTest.java
@@ -27,7 +27,6 @@ import org.apache.polygene.entitystore.riak.assembly.RiakEntityStoreAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.cache.AbstractEntityStoreWithCacheTest;
import org.apache.polygene.test.internal.DockerRule;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.junit.ClassRule;
public class RiakMapEntityStoreWithCacheTest extends AbstractEntityStoreWithCacheTest
@@ -60,7 +59,6 @@ public class RiakMapEntityStoreWithCacheTest extends AbstractEntityStoreWithCach
super.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
new RiakEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
RiakEntityStoreConfiguration riakConfig = config.forMixin( RiakEntityStoreConfiguration.class )
.declareDefaults();
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/build.gradle b/extensions/entitystore-sql/build.gradle
index ee99f52..8ab34f8 100644
--- a/extensions/entitystore-sql/build.gradle
+++ b/extensions/entitystore-sql/build.gradle
@@ -27,7 +27,9 @@ jar { manifest { name = "Apache Polygene\u2122 Extension - EntityStore - SQL" } }
dependencies {
api polygene.core.bootstrap
api polygene.library( 'sql' )
+ api libraries.jooq
+ implementation polygene.library( 'sql-liquibase' )
implementation libraries.javaSqlGenerator
implementation( libraries.javaSqlGeneratorImpl ) {
exclude group: 'junit'
@@ -37,7 +39,6 @@ dependencies {
testImplementation polygene.internals.testsupport
testImplementation polygene.library( 'sql-dbcp' )
- testImplementation polygene.extension( 'valueserialization-orgjson' )
testImplementation libraries.derby // Needed at compile time for polite test shutdown
testRuntimeOnly libraries.logback
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLEntityStoreMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLEntityStoreMixin.java
deleted file mode 100644
index 123a613..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLEntityStoreMixin.java
+++ /dev/null
@@ -1,624 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.sql;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.time.Instant;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Spliterator;
-import java.util.Spliterators;
-import java.util.UUID;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.function.Consumer;
-import java.util.stream.Stream;
-import java.util.stream.StreamSupport;
-import org.apache.polygene.api.common.Optional;
-import org.apache.polygene.api.common.QualifiedName;
-import org.apache.polygene.api.entity.EntityDescriptor;
-import org.apache.polygene.api.entity.EntityReference;
-import org.apache.polygene.api.identity.Identity;
-import org.apache.polygene.api.identity.IdentityGenerator;
-import org.apache.polygene.api.injection.scope.Service;
-import org.apache.polygene.api.injection.scope.Structure;
-import org.apache.polygene.api.injection.scope.This;
-import org.apache.polygene.api.service.ServiceActivation;
-import org.apache.polygene.api.service.qualifier.Tagged;
-import org.apache.polygene.api.structure.Application;
-import org.apache.polygene.api.structure.ModuleDescriptor;
-import org.apache.polygene.api.type.ValueType;
-import org.apache.polygene.api.unitofwork.NoSuchEntityTypeException;
-import org.apache.polygene.api.usecase.Usecase;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.entitystore.sql.internal.DatabaseSQLService;
-import org.apache.polygene.entitystore.sql.internal.DatabaseSQLService.EntityValueResult;
-import org.apache.polygene.entitystore.sql.internal.SQLEntityState;
-import org.apache.polygene.entitystore.sql.internal.SQLEntityState.DefaultSQLEntityState;
-import org.apache.polygene.library.sql.common.SQLUtil;
-import org.apache.polygene.spi.PolygeneSPI;
-import org.apache.polygene.spi.entity.EntityState;
-import org.apache.polygene.spi.entity.EntityStatus;
-import org.apache.polygene.spi.entitystore.DefaultEntityStoreUnitOfWork;
-import org.apache.polygene.spi.entitystore.EntityNotFoundException;
-import org.apache.polygene.spi.entitystore.EntityStore;
-import org.apache.polygene.spi.entitystore.EntityStoreException;
-import org.apache.polygene.spi.entitystore.EntityStoreSPI;
-import org.apache.polygene.spi.entitystore.EntityStoreUnitOfWork;
-import org.apache.polygene.spi.entitystore.StateCommitter;
-import org.apache.polygene.spi.entitystore.helpers.DefaultEntityState;
-import org.apache.polygene.spi.entitystore.helpers.JSONKeys;
-import org.apache.polygene.spi.entitystore.helpers.Migration;
-import org.apache.polygene.spi.entitystore.helpers.StateStore;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.json.JSONTokener;
-import org.json.JSONWriter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * SQL EntityStore core Mixin.
- */
-// TODO Rewrite reusing JSONMapEntityStoreMixin
-// Old notes:
-// Most of this code is copy-paste from {@link org.apache.polygene.spi.entitystore.helpers.MapEntityStoreMixin}.
-// Refactor stuff that has to do with general things than actual MapEntityStore from MapEntityStoreMixin
-// so that this class could extend some "AbstractJSONEntityStoreMixin".
-public class SQLEntityStoreMixin
- implements EntityStore, EntityStoreSPI, StateStore, ServiceActivation
-{
-
- private static final Logger LOGGER = LoggerFactory.getLogger( SQLEntityStoreMixin.class );
-
- @Service
- private DatabaseSQLService database;
-
- @This
- private EntityStoreSPI entityStoreSPI;
-
- @Structure
- private PolygeneSPI spi;
-
- @Structure
- private Application application;
-
- @Service
- @Tagged( ValueSerialization.Formats.JSON )
- private ValueSerialization valueSerialization;
-
- @Optional
- @Service
- private Migration migration;
-
- private String uuid;
-
- private final AtomicInteger count = new AtomicInteger();
-
- @Service
- private IdentityGenerator identityGenerator;
-
- @Override
- public void activateService()
- throws Exception
- {
- uuid = UUID.randomUUID().toString() + "-";
- count.set( 0 );
- database.startDatabase();
- }
-
- @Override
- public void passivateService()
- throws Exception
- {
- database.stopDatabase();
- }
-
- @Override
- public StateCommitter applyChanges( final EntityStoreUnitOfWork unitofwork, final Iterable<EntityState> states )
- {
- return new StateCommitter()
- {
- @Override
- public void commit()
- {
- Connection connection = null;
- PreparedStatement insertPS = null;
- PreparedStatement updatePS = null;
- PreparedStatement removePS = null;
- try
- {
- connection = database.getConnection();
- connection.setAutoCommit( false );
- insertPS = database.prepareInsertEntityStatement( connection );
- updatePS = database.prepareUpdateEntityStatement( connection );
- removePS = database.prepareRemoveEntityStatement( connection );
- for( EntityState state : states )
- {
- EntityStatus status = state.status();
- DefaultEntityState defState = ( (SQLEntityState) state ).getDefaultEntityState();
- Long entityPK = ( (SQLEntityState) state ).getEntityPK();
- if( EntityStatus.REMOVED.equals( status ) )
- {
- database.populateRemoveEntityStatement( removePS, entityPK, state.entityReference() );
- removePS.addBatch();
- }
- else
- {
- StringWriter writer = new StringWriter();
- writeEntityState( defState, writer, unitofwork.identity().toString() );
- writer.flush();
- if( EntityStatus.UPDATED.equals( status ) )
- {
- Long entityOptimisticLock = ( (SQLEntityState) state ).getEntityOptimisticLock();
- database.populateUpdateEntityStatement( updatePS, entityPK, entityOptimisticLock,
- defState.entityReference(), writer.toString(),
- unitofwork.currentTime() );
- updatePS.addBatch();
- }
- else if( EntityStatus.NEW.equals( status ) )
- {
- database.populateInsertEntityStatement( insertPS, defState.entityReference(),
- writer.toString(), unitofwork.currentTime() );
- insertPS.addBatch();
- }
- }
- }
-
- removePS.executeBatch();
- insertPS.executeBatch();
- updatePS.executeBatch();
-
- connection.commit();
- }
- catch( SQLException sqle )
- {
- SQLUtil.rollbackQuietly( connection );
- throw new EntityStoreException( "Unable to apply state changes",
- SQLUtil.withAllSQLExceptions( sqle ) );
- }
- catch( RuntimeException re )
- {
- SQLUtil.rollbackQuietly( connection );
- throw new EntityStoreException( re );
- }
- finally
- {
- SQLUtil.closeQuietly( insertPS );
- SQLUtil.closeQuietly( updatePS );
- SQLUtil.closeQuietly( removePS );
- SQLUtil.closeQuietly( connection );
- }
- }
-
- @Override
- public void cancel()
- {
- }
- };
- }
-
- @Override
- public EntityState entityStateOf( EntityStoreUnitOfWork unitOfWork,
- ModuleDescriptor module,
- EntityReference entityRef
- )
- {
- EntityValueResult valueResult = getValue( entityRef );
- DefaultEntityState state = readEntityState( module, valueResult.getReader() );
- return new DefaultSQLEntityState( state, valueResult.getEntityPK(), valueResult.getEntityOptimisticLock() );
- }
-
- @Override
- public String versionOf( EntityStoreUnitOfWork unitOfWork, EntityReference entityRef )
- {
- EntityValueResult valueResult = getValue( entityRef );
- Reader entityState = valueResult.getReader();
- try
- {
- JSONObject jsonObject = new JSONObject( new JSONTokener( entityState ) );
- final String version = jsonObject.getString( JSONKeys.VERSION );
- return version;
- }
- catch( JSONException e )
- {
- throw new EntityStoreException( e );
- }
- }
-
- @Override
- public EntityState newEntityState( EntityStoreUnitOfWork unitOfWork,
- EntityReference entityRef,
- EntityDescriptor entityDescriptor
- )
- {
- return new DefaultSQLEntityState(
- new DefaultEntityState( unitOfWork.currentTime(), entityRef, entityDescriptor ) );
- }
-
- @Override
- public EntityStoreUnitOfWork newUnitOfWork( ModuleDescriptor module, Usecase usecase, Instant currentTime )
- {
- return new DefaultEntityStoreUnitOfWork( module, entityStoreSPI, newUnitOfWorkId(), usecase, currentTime );
- }
-
- @Override
- public Stream<EntityState> entityStates( final ModuleDescriptor module )
- {
- try
- {
- Connection connection = database.getConnection();
- PreparedStatement ps = database.prepareGetAllEntitiesStatement( connection );
- database.populateGetAllEntitiesStatement( ps );
- ResultSet rs = ps.executeQuery();
- return StreamSupport.stream(
- new Spliterators.AbstractSpliterator<EntityState>( Long.MAX_VALUE, Spliterator.ORDERED )
- {
- @Override
- public boolean tryAdvance( final Consumer<? super EntityState> action )
- {
- try
- {
- if( !rs.next() ) { return false; }
- EntityState entityState = readEntityState( module,
- database.getEntityValue( rs ).getReader() );
- action.accept( entityState );
- return true;
- }
- catch( SQLException ex )
- {
- SQLUtil.closeQuietly( rs, ex );
- SQLUtil.closeQuietly( ps, ex );
- SQLUtil.closeQuietly( connection, ex );
- throw new EntityStoreException( "Unable to get next entity state",
- SQLUtil.withAllSQLExceptions( ex ) );
- }
- }
- },
- false
- ).onClose(
- () ->
- {
- SQLUtil.closeQuietly( rs );
- SQLUtil.closeQuietly( ps );
- SQLUtil.closeQuietly( connection );
- }
- );
- }
- catch( SQLException ex )
- {
- throw new EntityStoreException( "Unable to get entity states", SQLUtil.withAllSQLExceptions( ex ) );
- }
- }
-
- protected Identity newUnitOfWorkId()
- {
- return identityGenerator.generate( EntityStore.class );
- }
-
- protected DefaultEntityState readEntityState( ModuleDescriptor module, Reader entityState )
- throws EntityStoreException
- {
- try
- {
- JSONObject jsonObject = new JSONObject( new JSONTokener( entityState ) );
- final EntityStatus[] status = { EntityStatus.LOADED };
-
- String version = jsonObject.getString( JSONKeys.VERSION );
- Instant modified = Instant.ofEpochMilli( jsonObject.getLong( JSONKeys.MODIFIED ) );
- String identity = jsonObject.getString( JSONKeys.IDENTITY );
-
- // Check if version is correct
- String currentAppVersion = jsonObject.optString( JSONKeys.APPLICATION_VERSION, "0.0" );
- if( !currentAppVersion.equals( application.version() ) )
- {
- if( migration != null )
- {
- migration.migrate( jsonObject, application.version(), this );
- }
- else
- {
- // Do nothing - set version to be correct
- jsonObject.put( JSONKeys.APPLICATION_VERSION, application.version() );
- }
-
- LOGGER.trace( "Updated version nr on {} from {} to {}",
- identity, currentAppVersion, application.version() );
-
- // State changed
- status[ 0 ] = EntityStatus.UPDATED;
- }
-
- String type = jsonObject.getString( JSONKeys.TYPE );
-
- EntityDescriptor entityDescriptor = module.entityDescriptor( type );
- if( entityDescriptor == null )
- {
- throw new NoSuchEntityTypeException( type, module.name(), module.typeLookup() );
- }
-
- Map<QualifiedName, Object> properties = new HashMap<>();
- JSONObject props = jsonObject.getJSONObject( JSONKeys.PROPERTIES );
- entityDescriptor.state().properties().forEach(
- propertyDescriptor ->
- {
- Object jsonValue;
- try
- {
- jsonValue = props.get(
- propertyDescriptor.qualifiedName().name() );
- if( JSONObject.NULL.equals( jsonValue ) )
- {
- properties.put( propertyDescriptor.qualifiedName(), null );
- }
- else
- {
- Object value = valueSerialization.deserialize( module,
- propertyDescriptor.valueType(),
- jsonValue.toString() );
- properties.put( propertyDescriptor.qualifiedName(), value );
- }
- }
- catch( JSONException e )
- {
- // Value not found, default it
- Object initialValue = propertyDescriptor.resolveInitialValue( module );
- properties.put( propertyDescriptor.qualifiedName(), initialValue );
- status[ 0 ] = EntityStatus.UPDATED;
- }
- }
- );
-
- Map<QualifiedName, EntityReference> associations = new HashMap<>();
- JSONObject assocs = jsonObject.getJSONObject( JSONKeys.ASSOCIATIONS );
- entityDescriptor.state().associations().forEach(
- associationType ->
- {
- try
- {
- Object jsonValue = assocs.get( associationType.qualifiedName().name() );
- EntityReference value = jsonValue == JSONObject.NULL
- ? null
- : EntityReference.parseEntityReference( (String) jsonValue );
- associations.put( associationType.qualifiedName(), value );
- }
- catch( JSONException e )
- {
- // Association not found, default it to null
- associations.put( associationType.qualifiedName(), null );
- status[ 0 ] = EntityStatus.UPDATED;
- }
- }
- );
-
- JSONObject manyAssocs = jsonObject.getJSONObject( JSONKeys.MANY_ASSOCIATIONS );
- Map<QualifiedName, List<EntityReference>> manyAssociations = new HashMap<>();
- entityDescriptor.state().manyAssociations().forEach(
- manyAssociationType ->
- {
- List<EntityReference> references = new ArrayList<>();
- try
- {
- JSONArray jsonValues = manyAssocs.getJSONArray( manyAssociationType.qualifiedName().name() );
- for( int i = 0; i < jsonValues.length(); i++ )
- {
- Object jsonValue = jsonValues.getString( i );
- EntityReference value = jsonValue == JSONObject.NULL
- ? null
- : EntityReference.parseEntityReference( (String) jsonValue );
- references.add( value );
- }
- manyAssociations.put( manyAssociationType.qualifiedName(), references );
- }
- catch( JSONException e )
- {
- // ManyAssociation not found, default to empty one
- manyAssociations.put( manyAssociationType.qualifiedName(), references );
- }
- } );
-
- JSONObject namedAssocs = jsonObject.has( JSONKeys.NAMED_ASSOCIATIONS )
- ? jsonObject.getJSONObject( JSONKeys.NAMED_ASSOCIATIONS )
- : new JSONObject();
- Map<QualifiedName, Map<String, EntityReference>> namedAssociations = new HashMap<>();
- entityDescriptor.state().namedAssociations().forEach(
- namedAssociationType ->
- {
- Map<String, EntityReference> references = new LinkedHashMap<>();
- try
- {
- JSONObject jsonValues = namedAssocs.getJSONObject( namedAssociationType.qualifiedName().name() );
- JSONArray names = jsonValues.names();
- if( names != null )
- {
- for( int idx = 0; idx < names.length(); idx++ )
- {
- String name = names.getString( idx );
- String jsonValue = jsonValues.getString( name );
- references.put( name, EntityReference.parseEntityReference( jsonValue ) );
- }
- }
- namedAssociations.put( namedAssociationType.qualifiedName(), references );
- }
- catch( JSONException e )
- {
- // NamedAssociation not found, default to empty one
- namedAssociations.put( namedAssociationType.qualifiedName(), references );
- }
- } );
-
- return new DefaultEntityState( version, modified,
- EntityReference.parseEntityReference( identity ), status[ 0 ],
- entityDescriptor,
- properties, associations, manyAssociations, namedAssociations );
- }
- catch( JSONException e )
- {
- throw new EntityStoreException( e );
- }
- }
-
- @Override
- public JSONObject jsonStateOf( String id )
- throws IOException
- {
- JSONObject jsonObject;
- try( Reader reader = getValue( EntityReference.parseEntityReference( id ) ).getReader() )
- {
- jsonObject = new JSONObject( new JSONTokener( reader ) );
- }
- catch( JSONException e )
- {
- throw new IOException( e );
- }
- return jsonObject;
- }
-
- protected EntityValueResult getValue( EntityReference ref )
- {
- Connection connection = null;
- PreparedStatement ps = null;
- ResultSet rs = null;
- try
- {
- connection = database.getConnection();
- ps = database.prepareGetEntityStatement( connection );
- database.populateGetEntityStatement( ps, ref );
- rs = ps.executeQuery();
- if( !rs.next() )
- {
- throw new EntityNotFoundException( ref );
- }
- return database.getEntityValue( rs );
- }
- catch( SQLException sqle )
- {
- throw new EntityStoreException( "Unable to get Entity " + ref, SQLUtil.withAllSQLExceptions( sqle ) );
- }
- finally
- {
- SQLUtil.closeQuietly( rs );
- SQLUtil.closeQuietly( ps );
- SQLUtil.closeQuietly( connection );
- }
- }
-
- protected void writeEntityState( DefaultEntityState state, Writer writer, String version )
- throws EntityStoreException
- {
- try
- {
- JSONWriter json = new JSONWriter( writer );
- JSONWriter properties = json.object()
- .key( JSONKeys.IDENTITY )
- .value( state.entityReference().identity().toString() )
- .key( JSONKeys.APPLICATION_VERSION )
- .value( application.version() )
- .key( JSONKeys.TYPE )
- .value( state.entityDescriptor().types().findFirst().get().getName() )
- .key( JSONKeys.VERSION )
- .value( version )
- .key( JSONKeys.MODIFIED )
- .value( state.lastModified().toEpochMilli() )
- .key( JSONKeys.PROPERTIES )
- .object();
-
- state.entityDescriptor().state().properties().forEach(
- persistentProperty ->
- {
- try
- {
- Object value = state.properties().get( persistentProperty.qualifiedName() );
- json.key( persistentProperty.qualifiedName().name() );
- if( value == null || ValueType.isPrimitiveValue( value ) )
- {
- json.value( value );
- }
- else
- {
- String serialized = valueSerialization.serialize( value );
- if( serialized.startsWith( "{" ) )
- {
- json.value( new JSONObject( serialized ) );
- }
- else if( serialized.startsWith( "[" ) )
- {
- json.value( new JSONArray( serialized ) );
- }
- else
- {
- json.value( serialized );
- }
- }
- }
- catch( JSONException e )
- {
- throw new EntityStoreException(
- "Could not store EntityState", e );
- }
- } );
-
- JSONWriter associations = properties.endObject().key( JSONKeys.ASSOCIATIONS ).object();
- for( Map.Entry<QualifiedName, EntityReference> stateNameEntityRefEntry : state.associations().entrySet() )
- {
- EntityReference value = stateNameEntityRefEntry.getValue();
- associations.key( stateNameEntityRefEntry.getKey().name() )
- .value( value != null ? value.identity().toString() : null );
- }
-
- JSONWriter manyAssociations = associations.endObject().key( JSONKeys.MANY_ASSOCIATIONS ).object();
- for( Map.Entry<QualifiedName, List<EntityReference>> stateNameListEntry : state.manyAssociations().entrySet() )
- {
- JSONWriter assocs = manyAssociations.key( stateNameListEntry.getKey().name() ).array();
- for( EntityReference entityReference : stateNameListEntry.getValue() )
- {
- assocs.value( entityReference.identity().toString() );
- }
- assocs.endArray();
- }
-
- JSONWriter namedAssociations = manyAssociations.endObject().key( JSONKeys.NAMED_ASSOCIATIONS ).object();
- for( Map.Entry<QualifiedName, Map<String, EntityReference>> stateNameMapEntry : state.namedAssociations().entrySet() )
- {
- JSONWriter assocs = namedAssociations.key( stateNameMapEntry.getKey().name() ).object();
- for( Map.Entry<String, EntityReference> entry : stateNameMapEntry.getValue().entrySet() )
- {
- assocs.key( entry.getKey() ).value( entry.getValue().identity().toString() );
- }
- assocs.endObject();
- }
- namedAssociations.endObject().endObject();
- }
- catch( JSONException e )
- {
- throw new EntityStoreException( "Could not store EntityState", e );
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLEntityStoreService.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLEntityStoreService.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLEntityStoreService.java
deleted file mode 100644
index fe8c4aa..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLEntityStoreService.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.sql;
-
-import org.apache.polygene.api.concern.Concerns;
-import org.apache.polygene.api.mixin.Mixins;
-import org.apache.polygene.api.service.ServiceActivation;
-import org.apache.polygene.api.service.ServiceComposite;
-import org.apache.polygene.spi.entitystore.ConcurrentModificationCheckConcern;
-import org.apache.polygene.spi.entitystore.EntityStateVersions;
-import org.apache.polygene.spi.entitystore.EntityStore;
-import org.apache.polygene.spi.entitystore.StateChangeNotificationConcern;
-
-/**
- * SQL EntityStore service.
- */
-@Concerns( { StateChangeNotificationConcern.class, ConcurrentModificationCheckConcern.class } )
-@Mixins( { SQLEntityStoreMixin.class } )
-public interface SQLEntityStoreService
- extends EntityStore, EntityStateVersions, ServiceComposite, ServiceActivation
-{
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMapping.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMapping.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMapping.java
new file mode 100644
index 0000000..67f6066
--- /dev/null
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMapping.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.entitystore.sql;
+
+import org.jooq.DataType;
+import org.jooq.impl.SQLDataType;
+
+/**
+ * Mapping for the entities table.
+ *
+ * If you change this once the table is created you'll have to ALTER it yourself.
+ */
+public interface SQLMapEntityStoreMapping
+{
+ default String defaultSchemaName()
+ {
+ return "POLYGENE_ES";
+ }
+
+ default String tableName()
+ {
+ return "POLYGENE_ENTITIES";
+ }
+
+ default String identityColumnName()
+ {
+ return "ENTITY_IDENTITY";
+ }
+
+ default String versionColumnName()
+ {
+ return "ENTITY_VERSION";
+ }
+
+ default String stateColumnName()
+ {
+ return "ENTITY_STATE";
+ }
+
+ default DataType<String> identityDataType()
+ {
+ return SQLDataType.VARCHAR( 64 );
+ }
+
+ default DataType<String> versionDataType()
+ {
+ return SQLDataType.VARCHAR( 64 );
+ }
+
+ default DataType<String> stateDataType()
+ {
+ return SQLDataType.VARCHAR( 10 * 1024 );
+ }
+}
[39/50] [abbrv] polygene-java git commit: POLYGENE-231 Assert various
deserialization scenarii
Posted by pa...@apache.org.
POLYGENE-231 Assert various deserialization scenarii
- do not choke on missing optional state
- do not choke on superfluous state
- works with shuffled state
And fix msgpack serialization that failed on the former use case
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/928a285b
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/928a285b
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/928a285b
Branch: refs/heads/serialization-3.0
Commit: 928a285bc003fef0bc267bee8039aabd8cfd3f02
Parents: 264e704
Author: Paul Merlin <pa...@apache.org>
Authored: Mon Mar 6 14:54:17 2017 +0100
Committer: Paul Merlin <pa...@apache.org>
Committed: Mon Mar 13 11:24:42 2017 +0100
----------------------------------------------------------------------
...AbstractValueCompositeSerializationTest.java | 110 ++++++++++++++++++-
.../msgpack/MessagePackDeserializer.java | 2 +-
2 files changed, 107 insertions(+), 5 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/928a285b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
index 6c10776..dced530 100644
--- a/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
+++ b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
@@ -71,9 +71,6 @@ import static org.junit.Assert.assertThat;
*/
// TODO Assert Arrays behaviour!
// TODO Assert Generics behaviour!
-// TODO Assert deserialization using a value super type that has less properties/associations (e.g. ignore spurious state)
-// TODO Assert deserialization from state missing optional values (e.g. do not fail on missing optional values)
-// TODO Assert deserialization from state with different properties/associations order (e.g. do not fail on unordered values)
public abstract class AbstractValueCompositeSerializationTest
extends AbstractPolygeneTest
{
@@ -99,7 +96,8 @@ public abstract class AbstractValueCompositeSerializationTest
public void assemble( ModuleAssembly module )
throws AssemblyException
{
- module.values( Some.class, AnotherValue.class, FooValue.class, CustomFooValue.class,
+ module.values( Some.class, SomeExtended.class, SomeShuffled.class,
+ AnotherValue.class, FooValue.class, CustomFooValue.class,
SpecificCollection.class /*, SpecificValue.class, GenericValue.class */ );
new EntityTestAssembler().visibleIn( Visibility.layer ).assemble( module.layer().module( "persistence" ) );
@@ -147,6 +145,61 @@ public abstract class AbstractValueCompositeSerializationTest
}
@Test
+ public void canDeserializeUsingSuperTypeWithLessState()
+ {
+ try( UnitOfWork uow = unitOfWorkFactory.newUnitOfWork() )
+ {
+ SomeExtended someExtended = buildSomeExtendedValue( moduleInstance, uow, "42" );
+
+ String serialized = serialization.serialize( someExtended );
+ System.out.println( serialized );
+
+ Some deserialized = serialization.deserialize( module, Some.class, serialized );
+ System.out.println( deserialized );
+ }
+ }
+
+ @Test
+ public void canDeserializeUsingChildTypeWithSupplementaryOptionalState()
+ {
+ try( UnitOfWork uow = unitOfWorkFactory.newUnitOfWork() )
+ {
+ Some some = buildSomeValue( moduleInstance, uow, "42" );
+
+ String serialized = serialization.serialize( some );
+ System.out.println( serialized );
+
+ SomeExtended deserialized = serialization.deserialize( module, SomeExtended.class, serialized );
+ System.out.println( deserialized );
+ }
+ }
+
+ /**
+ * State model order depend on declaration order, this test ensures that moving a state method up/down into a type
+ * does not break deserialization.
+ */
+ @Test
+ public void canDeserializeFromShuffledState()
+ {
+ try( UnitOfWork uow = unitOfWorkFactory.newUnitOfWork() )
+ {
+ SomeExtended someExtended = buildSomeExtendedValue( moduleInstance, uow, "42" );
+
+ String serialized = serialization.serialize( someExtended );
+ System.out.println( serialized );
+
+ SomeShuffled deserialized = serialization.deserialize( module, SomeShuffled.class, serialized );
+ System.out.println( deserialized );
+
+ serialized = serialization.serialize( deserialized );
+ System.out.println( serialized );
+
+ serialization.deserialize( module, SomeExtended.class, serialized );
+ System.out.println( deserialized );
+ }
+ }
+
+ @Test
@Ignore( "JSONEntityState cannot handle polymorphic deserialization" )
// TODO Entity == Identity + Value
// JSONEntityState does not allow for polymorphic serialization
@@ -208,6 +261,19 @@ public abstract class AbstractValueCompositeSerializationTest
return builder.newInstance();
}
+ protected static SomeExtended buildSomeExtendedValue( Module module, UnitOfWork uow, String identity )
+ {
+ ValueBuilder<SomeExtended> builder = module.newValueBuilder( SomeExtended.class );
+ SomeExtended proto = builder.prototype();
+ proto.identity().set( StringIdentity.fromString( identity ) );
+ setSomeValueState( module, uow, proto );
+ proto.extraProperty().set( "extra property" );
+ proto.extraAssociation().set( buildBarEntity( uow, "extra association" ) );
+ proto.extraManyAssociation().add( buildBarEntity( uow, "extra many association" ) );
+ proto.extraNamedAssociation().put( "extra", buildBarEntity( uow, "extra named association" ) );
+ return builder.newInstance();
+ }
+
/**
* @return a Some EntityComposite whose state is populated with test data.
*/
@@ -407,6 +473,42 @@ public abstract class AbstractValueCompositeSerializationTest
NamedAssociation<BarEntity> barEntityNamedAssociation();
}
+ interface SomeExtended extends Some
+ {
+ @Optional
+ Property<String> extraProperty();
+
+ @Optional
+ Association<Bar> extraAssociation();
+
+ ManyAssociation<Bar> extraManyAssociation();
+
+ NamedAssociation<Bar> extraNamedAssociation();
+ }
+
+ interface SomeShuffled extends SomeExtended
+ {
+ NamedAssociation<Bar> extraNamedAssociation();
+
+ @Override
+ NamedAssociation<Bar> barNamedAssociation();
+
+ ManyAssociation<Bar> extraManyAssociation();
+
+ @Override
+ ManyAssociation<Bar> barManyAssociation();
+
+ Association<Bar> extraAssociation();
+
+ @Override
+ Association<Bar> barAssociation();
+
+ Property<String> extraProperty();
+
+ @Override
+ Property<String> string();
+ }
+
public interface SpecificCollection
extends GenericCollection<String>
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/928a285b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
index caba249..56f32e6 100644
--- a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
+++ b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
@@ -94,7 +94,7 @@ public interface MessagePackDeserializer extends Deserializer
{
try
{
- if( value.isNilValue() )
+ if( value == null || value.isNilValue() )
{
return null;
}
[11/50] [abbrv] polygene-java git commit: Fixed Serialization missing
in RdfIndexingAssembler,
causing failed tests. Fixed additional issues in Yeoman generator.
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/PreferencesEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/PreferencesEntityStoreMixin.java b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/PreferencesEntityStoreMixin.java
deleted file mode 100644
index 3198347..0000000
--- a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/PreferencesEntityStoreMixin.java
+++ /dev/null
@@ -1,658 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.prefs;
-
-import java.time.Instant;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-import java.util.prefs.BackingStoreException;
-import java.util.prefs.Preferences;
-import java.util.stream.Stream;
-import org.apache.polygene.api.cache.CacheOptions;
-import org.apache.polygene.api.common.QualifiedName;
-import org.apache.polygene.api.entity.EntityDescriptor;
-import org.apache.polygene.api.entity.EntityReference;
-import org.apache.polygene.api.identity.Identity;
-import org.apache.polygene.api.identity.IdentityGenerator;
-import org.apache.polygene.api.injection.scope.Service;
-import org.apache.polygene.api.injection.scope.Structure;
-import org.apache.polygene.api.injection.scope.This;
-import org.apache.polygene.api.injection.scope.Uses;
-import org.apache.polygene.api.property.PropertyDescriptor;
-import org.apache.polygene.api.service.ServiceActivation;
-import org.apache.polygene.api.service.ServiceDescriptor;
-import org.apache.polygene.api.service.qualifier.Tagged;
-import org.apache.polygene.api.structure.Application;
-import org.apache.polygene.api.structure.ModuleDescriptor;
-import org.apache.polygene.api.time.SystemTime;
-import org.apache.polygene.api.type.CollectionType;
-import org.apache.polygene.api.type.EnumType;
-import org.apache.polygene.api.type.MapType;
-import org.apache.polygene.api.type.ValueCompositeType;
-import org.apache.polygene.api.type.ValueType;
-import org.apache.polygene.api.unitofwork.NoSuchEntityException;
-import org.apache.polygene.api.unitofwork.NoSuchEntityTypeException;
-import org.apache.polygene.api.usecase.Usecase;
-import org.apache.polygene.api.usecase.UsecaseBuilder;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.api.value.ValueSerializationException;
-import org.apache.polygene.spi.PolygeneSPI;
-import org.apache.polygene.spi.entity.EntityState;
-import org.apache.polygene.spi.entity.EntityStatus;
-import org.apache.polygene.spi.entitystore.DefaultEntityStoreUnitOfWork;
-import org.apache.polygene.spi.entitystore.EntityStore;
-import org.apache.polygene.spi.entitystore.EntityStoreException;
-import org.apache.polygene.spi.entitystore.EntityStoreSPI;
-import org.apache.polygene.spi.entitystore.EntityStoreUnitOfWork;
-import org.apache.polygene.spi.entitystore.StateCommitter;
-import org.apache.polygene.spi.entitystore.helpers.DefaultEntityState;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Implementation of EntityStore that is backed by the Preferences API.
- *
- * <p>@see Preferences</p>
- * <p>
- * Associations are stored as the reference of the referenced Entity, ManyAssociations are stored as multi-line strings
- * (one reference per line), and NamedAssociations are stored as multi-line strings (one name on a line, reference on the
- * next line).
- * </p>
- * <p>Nested ValuesComposites, Collections and Maps are stored using available ValueSerialization service.</p>
- */
-public class PreferencesEntityStoreMixin
- implements ServiceActivation, EntityStore, EntityStoreSPI
-{
- @Structure
- private PolygeneSPI spi;
-
- @This
- private EntityStoreSPI entityStoreSpi;
-
- @Uses
- private ServiceDescriptor descriptor;
-
- @Structure
- private Application application;
-
- @Service
- @Tagged( ValueSerialization.Formats.JSON )
- private ValueSerialization valueSerialization;
-
- private Preferences root;
-
- public Logger logger;
-
- public ScheduledThreadPoolExecutor reloadExecutor;
-
- @Service
- private IdentityGenerator identityGenerator;
-
- @Override
- public void activateService()
- throws Exception
- {
- root = getApplicationRoot();
- logger = LoggerFactory.getLogger( PreferencesEntityStoreService.class.getName() );
- logger.info( "Preferences store:" + root.absolutePath() );
-
- // Reload underlying store every 60 seconds
- reloadExecutor = new ScheduledThreadPoolExecutor( 1 );
- reloadExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy( false );
- reloadExecutor.scheduleAtFixedRate( () -> {
- try
- {
- //noinspection SynchronizeOnNonFinalField
- synchronized( root )
- {
- root.sync();
- }
- }
- catch( BackingStoreException e )
- {
- logger.warn( "Could not reload preferences", e );
- }
- }, 0, 60, TimeUnit.SECONDS );
- }
-
- private Preferences getApplicationRoot()
- {
- PreferencesEntityStoreInfo storeInfo = descriptor.metaInfo( PreferencesEntityStoreInfo.class );
-
- Preferences preferences;
- if( storeInfo == null )
- {
- // Default to use system root + application name
- preferences = Preferences.systemRoot();
- String name = application.name();
- preferences = preferences.node( name );
- }
- else
- {
- preferences = storeInfo.rootNode();
- }
-
- return preferences;
- }
-
- @Override
- public void passivateService()
- throws Exception
- {
- reloadExecutor.shutdown();
- reloadExecutor.awaitTermination( 10, TimeUnit.SECONDS );
- }
-
- @Override
- public EntityStoreUnitOfWork newUnitOfWork( ModuleDescriptor module, Usecase usecase, Instant currentTime )
- {
- return new DefaultEntityStoreUnitOfWork( module, entityStoreSpi, newUnitOfWorkId(), usecase, currentTime );
- }
-
- @Override
- public Stream<EntityState> entityStates( final ModuleDescriptor module )
- {
- UsecaseBuilder builder = UsecaseBuilder.buildUsecase( "polygene.entitystore.preferences.visit" );
- Usecase visitUsecase = builder.withMetaInfo( CacheOptions.NEVER ).newUsecase();
- EntityStoreUnitOfWork uow = newUnitOfWork( module, visitUsecase, SystemTime.now() );
-
- try
- {
- return Stream.of( root.childrenNames() )
- .map( EntityReference::parseEntityReference )
- .map( ref -> uow.entityStateOf( module, ref ) )
- .onClose( uow::discard );
- }
- catch( BackingStoreException e )
- {
- throw new EntityStoreException( e );
- }
- }
-
- @Override
- public EntityState newEntityState( EntityStoreUnitOfWork unitOfWork,
- EntityReference reference,
- EntityDescriptor entityDescriptor
- )
- {
- return new DefaultEntityState( unitOfWork.currentTime(), reference, entityDescriptor );
- }
-
- @Override
- public EntityState entityStateOf( EntityStoreUnitOfWork unitOfWork,
- ModuleDescriptor module,
- EntityReference reference
- )
- {
- try
- {
- if( !root.nodeExists( reference.identity().toString() ) )
- {
- throw new NoSuchEntityException( reference, UnknownType.class, unitOfWork.usecase() );
- }
-
- Preferences entityPrefs = root.node( reference.identity().toString() );
-
- String type = entityPrefs.get( "type", null );
- EntityStatus status = EntityStatus.LOADED;
-
- EntityDescriptor entityDescriptor = module.entityDescriptor( type );
- if( entityDescriptor == null )
- {
- throw new NoSuchEntityTypeException( type, module.name(), module.typeLookup() );
- }
-
- Map<QualifiedName, Object> properties = new HashMap<>();
- final Preferences propsPrefs = entityPrefs.node( "properties" );
- entityDescriptor.state().properties().forEach(
- persistentPropertyDescriptor ->
- {
- if( persistentPropertyDescriptor.qualifiedName().name().equals( "reference" ) )
- {
- // Fake reference property
- properties.put( persistentPropertyDescriptor.qualifiedName(), reference.identity().toString() );
- }
- else
- {
- ValueType propertyType = persistentPropertyDescriptor.valueType();
- Class<?> primaryType = propertyType.primaryType();
- if( Number.class.isAssignableFrom( primaryType ) )
- {
- if( primaryType.equals( Long.class ) )
- {
- properties.put( persistentPropertyDescriptor.qualifiedName(),
- this.getNumber( propsPrefs, module, persistentPropertyDescriptor, LONG_PARSER ) );
- }
- else if( primaryType.equals( Integer.class ) )
- {
- properties.put( persistentPropertyDescriptor.qualifiedName(),
- this.getNumber( propsPrefs, module, persistentPropertyDescriptor, INT_PARSER ) );
- }
- else if( primaryType.equals( Double.class ) )
- {
- properties.put( persistentPropertyDescriptor.qualifiedName(),
- this.getNumber( propsPrefs, module, persistentPropertyDescriptor, DOUBLE_PARSER ) );
- }
- else if( primaryType.equals( Float.class ) )
- {
- properties.put( persistentPropertyDescriptor.qualifiedName(),
- this.getNumber( propsPrefs, module, persistentPropertyDescriptor, FLOAT_PARSER ) );
- }
- else
- {
- // Load as string even though it's a number
- String json = propsPrefs.get( persistentPropertyDescriptor.qualifiedName()
- .name(), null );
- Object value;
- if( json == null )
- {
- value = null;
- }
- else
- {
- value = valueSerialization.deserialize( module, persistentPropertyDescriptor.valueType(), json );
- }
- properties.put( persistentPropertyDescriptor.qualifiedName(), value );
- }
- }
- else if( primaryType.equals( Boolean.class ) )
- {
- Boolean initialValue = (Boolean) persistentPropertyDescriptor.resolveInitialValue(module);
- properties.put( persistentPropertyDescriptor.qualifiedName(),
- propsPrefs.getBoolean( persistentPropertyDescriptor.qualifiedName().name(),
- initialValue == null ? false : initialValue ) );
- }
- else if( propertyType instanceof ValueCompositeType
- || propertyType instanceof MapType
- || propertyType instanceof CollectionType
- || propertyType instanceof EnumType )
- {
- String json = propsPrefs.get( persistentPropertyDescriptor.qualifiedName().name(), null );
- Object value;
- if( json == null )
- {
- value = null;
- }
- else
- {
- value = valueSerialization.deserialize( module, persistentPropertyDescriptor.valueType(), json );
- }
- properties.put( persistentPropertyDescriptor.qualifiedName(), value );
- }
- else
- {
- String json = propsPrefs.get( persistentPropertyDescriptor.qualifiedName().name(), null );
- if( json == null )
- {
- if( persistentPropertyDescriptor.resolveInitialValue( module ) != null )
- {
- properties.put( persistentPropertyDescriptor.qualifiedName(),
- persistentPropertyDescriptor.resolveInitialValue( module ) );
- }
- else
- {
- properties.put( persistentPropertyDescriptor.qualifiedName(), null );
- }
- }
- else
- {
- Object value = valueSerialization.deserialize( module, propertyType, json );
- properties.put( persistentPropertyDescriptor.qualifiedName(), value );
- }
- }
- }
- } );
-
- // Associations
- Map<QualifiedName, EntityReference> associations = new HashMap<>();
- final Preferences assocs = entityPrefs.node( "associations" );
- entityDescriptor.state().associations().forEach( associationType -> {
- String associatedEntity = assocs.get( associationType.qualifiedName().name(), null );
- EntityReference value = associatedEntity == null
- ? null
- : EntityReference.parseEntityReference( associatedEntity );
- associations.put( associationType.qualifiedName(), value );
- } );
-
- // ManyAssociations
- Map<QualifiedName, List<EntityReference>> manyAssociations = new HashMap<>();
- Preferences manyAssocs = entityPrefs.node( "manyassociations" );
- entityDescriptor.state().manyAssociations().forEach( manyAssociationType -> {
- List<EntityReference> references = new ArrayList<>();
- String entityReferences = manyAssocs.get( manyAssociationType
- .qualifiedName()
- .name(), null );
- if( entityReferences == null )
- {
- // ManyAssociation not found, default to empty one
- manyAssociations.put( manyAssociationType.qualifiedName(), references );
- }
- else
- {
- String[] refs = entityReferences.split( "\n" );
- for( String ref : refs )
- {
- EntityReference value = ref == null
- ? null
- : EntityReference.parseEntityReference( ref );
- references.add( value );
- }
- manyAssociations.put( manyAssociationType.qualifiedName(), references );
- }
- } );
-
- // NamedAssociations
- Map<QualifiedName, Map<String, EntityReference>> namedAssociations = new HashMap<>();
- Preferences namedAssocs = entityPrefs.node( "namedassociations" );
- entityDescriptor.state().namedAssociations().forEach( namedAssociationType -> {
- Map<String, EntityReference> references = new LinkedHashMap<>();
- String entityReferences = namedAssocs.get( namedAssociationType.qualifiedName().name(), null );
- if( entityReferences == null )
- {
- // NamedAssociation not found, default to empty one
- namedAssociations.put( namedAssociationType.qualifiedName(), references );
- }
- else
- {
- String[] namedRefs = entityReferences.split( "\n" );
- if( namedRefs.length % 2 != 0 )
- {
- throw new EntityStoreException( "Invalid NamedAssociation storage format" );
- }
- for( int idx = 0; idx < namedRefs.length; idx += 2 )
- {
- String name = namedRefs[ idx ];
- String ref = namedRefs[ idx + 1 ];
- references.put( name, EntityReference.parseEntityReference( ref ) );
- }
- namedAssociations.put( namedAssociationType.qualifiedName(), references );
- }
- } );
-
- return new DefaultEntityState( entityPrefs.get( "version", "" ),
- Instant.ofEpochMilli(entityPrefs.getLong( "modified", unitOfWork.currentTime().toEpochMilli() )),
- reference,
- status,
- entityDescriptor,
- properties,
- associations,
- manyAssociations,
- namedAssociations
- );
- }
- catch( ValueSerializationException | BackingStoreException e )
- {
- throw new EntityStoreException( e );
- }
- }
-
- @Override
- public String versionOf( EntityStoreUnitOfWork unitOfWork, EntityReference reference )
- {
- try
- {
- if( !root.nodeExists( reference.identity().toString() ) )
- {
- throw new NoSuchEntityException( reference, UnknownType.class, unitOfWork.usecase() );
- }
-
- Preferences entityPrefs = root.node( reference.identity().toString() );
- return entityPrefs.get( "version", "" );
- }
- catch( BackingStoreException e )
- {
- throw new EntityStoreException( e );
- }
- }
-
- @Override
- public StateCommitter applyChanges( final EntityStoreUnitOfWork unitofwork, final Iterable<EntityState> state )
- {
- return new StateCommitter()
- {
- @SuppressWarnings( "SynchronizeOnNonFinalField" )
- @Override
- public void commit()
- {
- try
- {
- synchronized( root )
- {
- for( EntityState entityState : state )
- {
- DefaultEntityState state = (DefaultEntityState) entityState;
- if( state.status().equals( EntityStatus.NEW ) )
- {
- Preferences entityPrefs = root.node( state.entityReference().identity().toString() );
- writeEntityState( state, entityPrefs, unitofwork.identity(), unitofwork.currentTime() );
- }
- else if( state.status().equals( EntityStatus.UPDATED ) )
- {
- Preferences entityPrefs = root.node( state.entityReference().identity().toString() );
- writeEntityState( state, entityPrefs, unitofwork.identity(), unitofwork.currentTime() );
- }
- else if( state.status().equals( EntityStatus.REMOVED ) )
- {
- root.node( state.entityReference().identity().toString() ).removeNode();
- }
- }
- root.flush();
- }
- }
- catch( BackingStoreException e )
- {
- throw new EntityStoreException( e );
- }
- }
-
- @Override
- public void cancel()
- {
- }
- };
- }
-
- protected void writeEntityState( DefaultEntityState state,
- Preferences entityPrefs,
- Identity identity,
- Instant lastModified
- )
- throws EntityStoreException
- {
- try
- {
- // Store into Preferences API
- entityPrefs.put( "type", state.entityDescriptor().types().findFirst().get().getName() );
- entityPrefs.put( "version", identity.toString() );
- entityPrefs.putLong( "modified", lastModified.toEpochMilli() );
-
- // Properties
- Preferences propsPrefs = entityPrefs.node( "properties" );
- state.entityDescriptor().state().properties()
- .filter( property -> !property.qualifiedName().name().equals( "reference" ) )
- .forEach( persistentProperty ->
- {
- Object value = state.properties().get( persistentProperty.qualifiedName() );
-
- if( value == null )
- {
- propsPrefs.remove( persistentProperty.qualifiedName().name() );
- }
- else
- {
- ValueType valueType = persistentProperty.valueType();
- Class<?> primaryType = valueType.primaryType();
- if( Number.class.isAssignableFrom( primaryType ) )
- {
- if( primaryType.equals( Long.class ) )
- {
- propsPrefs.putLong( persistentProperty.qualifiedName().name(), (Long) value );
- }
- else if( primaryType.equals( Integer.class ) )
- {
- propsPrefs.putInt( persistentProperty.qualifiedName()
- .name(), (Integer) value );
- }
- else if( primaryType.equals( Double.class ) )
- {
- propsPrefs.putDouble( persistentProperty.qualifiedName()
- .name(), (Double) value );
- }
- else if( primaryType.equals( Float.class ) )
- {
- propsPrefs.putFloat( persistentProperty.qualifiedName()
- .name(), (Float) value );
- }
- else
- {
- // Store as string even though it's a number
- String jsonString = valueSerialization.serialize( value );
- propsPrefs.put( persistentProperty.qualifiedName().name(), jsonString );
- }
- }
- else if( primaryType.equals( Boolean.class ) )
- {
- propsPrefs.putBoolean( persistentProperty.qualifiedName()
- .name(), (Boolean) value );
- }
- else if( valueType instanceof ValueCompositeType
- || valueType instanceof MapType
- || valueType instanceof CollectionType
- || valueType instanceof EnumType )
- {
- String jsonString = valueSerialization.serialize( value );
- propsPrefs.put( persistentProperty.qualifiedName().name(), jsonString );
- }
- else
- {
- String jsonString = valueSerialization.serialize( value );
- propsPrefs.put( persistentProperty.qualifiedName().name(), jsonString );
- }
- }
- } );
-
- // Associations
- if( !state.associations().isEmpty() )
- {
- Preferences assocsPrefs = entityPrefs.node( "associations" );
- for( Map.Entry<QualifiedName, EntityReference> association : state.associations().entrySet() )
- {
- if( association.getValue() == null )
- {
- assocsPrefs.remove( association.getKey().name() );
- }
- else
- {
- assocsPrefs.put( association.getKey().name(), association.getValue().identity().toString() );
- }
- }
- }
-
- // ManyAssociations
- if( !state.manyAssociations().isEmpty() )
- {
- Preferences manyAssocsPrefs = entityPrefs.node( "manyassociations" );
- for( Map.Entry<QualifiedName, List<EntityReference>> manyAssociation : state.manyAssociations()
- .entrySet() )
- {
- StringBuilder manyAssocs = new StringBuilder();
- for( EntityReference entityReference : manyAssociation.getValue() )
- {
- if( manyAssocs.length() > 0 )
- {
- manyAssocs.append( "\n" );
- }
- manyAssocs.append( entityReference.identity().toString() );
- }
- if( manyAssocs.length() > 0 )
- {
- manyAssocsPrefs.put( manyAssociation.getKey().name(), manyAssocs.toString() );
- }
- }
- }
-
- // NamedAssociations
- if( !state.namedAssociations().isEmpty() )
- {
- Preferences namedAssocsPrefs = entityPrefs.node( "namedassociations" );
- for( Map.Entry<QualifiedName, Map<String, EntityReference>> namedAssociation : state.namedAssociations()
- .entrySet() )
- {
- StringBuilder namedAssocs = new StringBuilder();
- for( Map.Entry<String, EntityReference> namedRef : namedAssociation.getValue().entrySet() )
- {
- if( namedAssocs.length() > 0 )
- {
- namedAssocs.append( "\n" );
- }
- namedAssocs.append( namedRef.getKey() ).append( "\n" ).append( namedRef.getValue().identity().toString() );
- }
- if( namedAssocs.length() > 0 )
- {
- namedAssocsPrefs.put( namedAssociation.getKey().name(), namedAssocs.toString() );
- }
- }
- }
- }
- catch( ValueSerializationException e )
- {
- throw new EntityStoreException( "Could not store EntityState", e );
- }
- }
-
- protected Identity newUnitOfWorkId()
- {
- return identityGenerator.generate(EntityStore.class);
- }
-
- private interface NumberParser<T>
- {
- T parse( String str );
- }
-
- private static final NumberParser<Long> LONG_PARSER = Long::parseLong;
-
- private static final NumberParser<Integer> INT_PARSER = Integer::parseInt;
-
- private static final NumberParser<Double> DOUBLE_PARSER = Double::parseDouble;
-
- private static final NumberParser<Float> FLOAT_PARSER = Float::parseFloat;
-
- private <T> T getNumber( Preferences prefs, ModuleDescriptor module, PropertyDescriptor pDesc, NumberParser<T> parser )
- {
- Object initialValue = pDesc.resolveInitialValue( module );
- String str = prefs.get( pDesc.qualifiedName().name(), initialValue == null ? null : initialValue.toString() );
- T result = null;
- if( str != null )
- {
- result = parser.parse( str );
- }
- return result;
- }
-
- private static class UnknownType
- {
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/PreferencesEntityStoreService.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/PreferencesEntityStoreService.java b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/PreferencesEntityStoreService.java
deleted file mode 100644
index a3801de..0000000
--- a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/PreferencesEntityStoreService.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-
-package org.apache.polygene.entitystore.prefs;
-
-import org.apache.polygene.api.concern.Concerns;
-import org.apache.polygene.api.mixin.Mixins;
-import org.apache.polygene.api.service.ServiceActivation;
-import org.apache.polygene.api.service.ServiceComposite;
-import org.apache.polygene.spi.entitystore.ConcurrentModificationCheckConcern;
-import org.apache.polygene.spi.entitystore.EntityStateVersions;
-import org.apache.polygene.spi.entitystore.EntityStore;
-
-/**
- * EntityStore backed by Preferences API.
- * <p>
- * A root node is created in the System preferences, whose name
- * is the same as the Application name (default:"Application").
- * </p>
- * <p>
- * Each entity is stored under its identity name.
- * </p>
- * <p>
- * Property types are converted to native Preferences API types
- * as much as possible. All others will be serialized to a string using JSON.
- * </p>
- * <p>
- * Associations are stored as the identity of the referenced Entity, ManyAssociations are stored as multi-line strings
- * (one reference per line), and NamedAssociations are stored as multi-line strings (one name on a line, reference on the
- * next line).
- * </p>
- * <p>
- * The main use of the EntityStore is for storage of ConfigurationComposites for ServiceComposites.
- * </p>
- * @see org.apache.polygene.api.service.ServiceComposite
- * @see org.apache.polygene.api.configuration.Configuration
- */
-@Concerns( ConcurrentModificationCheckConcern.class )
-@Mixins( PreferencesEntityStoreMixin.class )
-public interface PreferencesEntityStoreService
- extends EntityStore, ServiceComposite, EntityStateVersions, ServiceActivation
-{
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/assembly/PreferenceEntityStoreAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/assembly/PreferenceEntityStoreAssembler.java b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/assembly/PreferenceEntityStoreAssembler.java
deleted file mode 100644
index 4371047..0000000
--- a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/assembly/PreferenceEntityStoreAssembler.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.prefs.assembly;
-
-import java.util.prefs.Preferences;
-import org.apache.polygene.bootstrap.Assemblers;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.bootstrap.ServiceDeclaration;
-import org.apache.polygene.entitystore.prefs.PreferencesEntityStoreInfo;
-import org.apache.polygene.entitystore.prefs.PreferencesEntityStoreService;
-
-public class PreferenceEntityStoreAssembler
- extends Assemblers.VisibilityIdentity<PreferenceEntityStoreAssembler>
-{
- @Override
- public void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- String applicationName = module.layer().application().name();
-
- Preferences root = Preferences.userRoot();
- Preferences node = root.node( applicationName );
- PreferencesEntityStoreInfo info = new PreferencesEntityStoreInfo( node );
- ServiceDeclaration service = module.services( PreferencesEntityStoreService.class )
- .setMetaInfo( info )
- .visibleIn( visibility() )
- .instantiateOnStartup();
- if( hasIdentity() )
- {
- service.identifiedBy( identity() );
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/assembly/package.html
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/assembly/package.html b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/assembly/package.html
deleted file mode 100644
index 564de79..0000000
--- a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/assembly/package.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one
- ~ or more contributor license agreements. See the NOTICE file
- ~ distributed with this work for additional information
- ~ regarding copyright ownership. The ASF licenses this file
- ~ to you under the Apache License, Version 2.0 (the
- ~ "License"); you may not use this file except in compliance
- ~ with the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- ~
- ~
- -->
-<html>
- <body>
- <h2>Preferences EntityStore Assembly.</h2>
- </body>
-</html>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/package.html
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/package.html b/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/package.html
deleted file mode 100644
index 8e39337..0000000
--- a/extensions/entitystore-preferences/src/main/java/org/apache/polygene/entitystore/prefs/package.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one
- ~ or more contributor license agreements. See the NOTICE file
- ~ distributed with this work for additional information
- ~ regarding copyright ownership. The ASF licenses this file
- ~ to you under the Apache License, Version 2.0 (the
- ~ "License"); you may not use this file except in compliance
- ~ with the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- ~
- ~
- -->
-<html>
- <body>
- <h2>Preferences EntityStore.</h2>
- </body>
-</html>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/entitystore-preferences/src/test/java/org/apache/polygene/entitystore/DocumentationSupport.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/test/java/org/apache/polygene/entitystore/DocumentationSupport.java b/extensions/entitystore-preferences/src/test/java/org/apache/polygene/entitystore/DocumentationSupport.java
index 7715f9e..53f049a 100644
--- a/extensions/entitystore-preferences/src/test/java/org/apache/polygene/entitystore/DocumentationSupport.java
+++ b/extensions/entitystore-preferences/src/test/java/org/apache/polygene/entitystore/DocumentationSupport.java
@@ -21,7 +21,7 @@ package org.apache.polygene.entitystore;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.entitystore.prefs.assembly.PreferenceEntityStoreAssembler;
+import org.apache.polygene.entitystore.preferences.assembly.PreferencesEntityStoreAssembler;
import org.apache.polygene.test.AbstractPolygeneTest;
public class DocumentationSupport
@@ -32,7 +32,7 @@ public class DocumentationSupport
public void assemble( ModuleAssembly module )
throws AssemblyException
{
- new PreferenceEntityStoreAssembler().assemble( module );
+ new PreferencesEntityStoreAssembler().assemble( module );
}
// END SNIPPET: assembly
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/entitystore-preferences/src/test/java/org/apache/polygene/entitystore/PreferencesEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-preferences/src/test/java/org/apache/polygene/entitystore/PreferencesEntityStoreTest.java b/extensions/entitystore-preferences/src/test/java/org/apache/polygene/entitystore/PreferencesEntityStoreTest.java
index f2cf4e4..10be81e 100644
--- a/extensions/entitystore-preferences/src/test/java/org/apache/polygene/entitystore/PreferencesEntityStoreTest.java
+++ b/extensions/entitystore-preferences/src/test/java/org/apache/polygene/entitystore/PreferencesEntityStoreTest.java
@@ -22,8 +22,8 @@ package org.apache.polygene.entitystore;
import java.util.prefs.Preferences;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.entitystore.prefs.PreferencesEntityStoreInfo;
-import org.apache.polygene.entitystore.prefs.PreferencesEntityStoreService;
+import org.apache.polygene.entitystore.preferences.PreferencesEntityStoreInfo;
+import org.apache.polygene.entitystore.preferences.PreferencesEntityStoreService;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.junit.Rule;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/SQLEntityStoreAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/SQLEntityStoreAssembler.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/SQLEntityStoreAssembler.java
new file mode 100644
index 0000000..1477c6b
--- /dev/null
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/SQLEntityStoreAssembler.java
@@ -0,0 +1,28 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.entitystore.sql.assembly;
+
+/**
+ * This is a dummy Assembler to support the Yeoman Polygene Generator, which require naming conventions for
+ * the systems that it supports.
+ */
+public class SQLEntityStoreAssembler extends H2SQLEntityStoreAssembler
+{}
+
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/indexing-elasticsearch/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/indexing-elasticsearch/build.gradle b/extensions/indexing-elasticsearch/build.gradle
index fac6eec..faa63b8 100644
--- a/extensions/indexing-elasticsearch/build.gradle
+++ b/extensions/indexing-elasticsearch/build.gradle
@@ -34,6 +34,7 @@ dependencies {
runtimeOnly polygene.core.runtime
testImplementation polygene.core.testsupport
+ testImplementation polygene.extension( 'valueserialization-jackson' )
testRuntimeOnly libraries.logback
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/indexing-elasticsearch/src/test/java/org/apache/polygene/index/elasticsearch/ElasticSearchQueryTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-elasticsearch/src/test/java/org/apache/polygene/index/elasticsearch/ElasticSearchQueryTest.java b/extensions/indexing-elasticsearch/src/test/java/org/apache/polygene/index/elasticsearch/ElasticSearchQueryTest.java
index 6b6feab..ecd35fb 100644
--- a/extensions/indexing-elasticsearch/src/test/java/org/apache/polygene/index/elasticsearch/ElasticSearchQueryTest.java
+++ b/extensions/indexing-elasticsearch/src/test/java/org/apache/polygene/index/elasticsearch/ElasticSearchQueryTest.java
@@ -30,6 +30,7 @@ import org.apache.polygene.library.fileconfig.FileConfigurationOverride;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.indexing.AbstractQueryTest;
import org.apache.polygene.test.util.NotYetImplemented;
+import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
@@ -78,6 +79,9 @@ public class ElasticSearchQueryTest extends AbstractQueryTest
testName.getMethodName() ) );
esConfig.indexNonAggregatedAssociations().set( Boolean.TRUE );
+ // Serialization
+ new JacksonValueSerializationAssembler().assemble( module );
+
// FileConfig
new FileConfigurationAssembler()
.withOverride( new FileConfigurationOverride().withConventionalRoot( tmpDir.getRoot() ) )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/indexing-rdf/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/build.gradle b/extensions/indexing-rdf/build.gradle
index 2eb52e9..ad465a4 100644
--- a/extensions/indexing-rdf/build.gradle
+++ b/extensions/indexing-rdf/build.gradle
@@ -33,7 +33,7 @@ dependencies {
runtimeOnly polygene.core.runtime
testImplementation polygene.core.testsupport
- testImplementation polygene.extension( 'valueserialization-orgjson' )
+ testImplementation polygene.extension( 'valueserialization-jackson' )
testImplementation polygene.extension( 'entitystore-preferences' )
testImplementation polygene.extension( 'entitystore-jdbm' )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/query/RdfQueryParserFactory.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/query/RdfQueryParserFactory.java b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/query/RdfQueryParserFactory.java
index 8f11649..fa2c6ae 100644
--- a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/query/RdfQueryParserFactory.java
+++ b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/query/RdfQueryParserFactory.java
@@ -43,6 +43,7 @@ public interface RdfQueryParserFactory
{
@Structure
private PolygeneSPI spi;
+
@Service
@Tagged( ValueSerialization.Formats.JSON )
private ValueSerializer valueSerializer;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryMultimoduleTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryMultimoduleTest.java b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryMultimoduleTest.java
index 23c8f13..21f5d46 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryMultimoduleTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryMultimoduleTest.java
@@ -27,6 +27,7 @@ import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
import org.apache.polygene.index.rdf.assembly.RdfMemoryStoreAssembler;
import org.apache.polygene.test.EntityTestAssembler;
+import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
public class RdfNamedQueryMultimoduleTest
extends RdfNamedQueryTest
@@ -47,6 +48,7 @@ public class RdfNamedQueryMultimoduleTest
ModuleAssembly indexModule = layer.module( "index" );
new DefaultUnitOfWorkAssembler().assemble( indexModule );
new RdfMemoryStoreAssembler( Visibility.layer, Visibility.module ).assemble( indexModule );
+ new JacksonValueSerializationAssembler().assemble( indexModule );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryTest.java b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryTest.java
index e327387..6ebbee8 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryTest.java
@@ -27,6 +27,8 @@ import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.index.rdf.assembly.RdfMemoryStoreAssembler;
import org.apache.polygene.index.rdf.query.SesameExpressions;
import org.apache.polygene.test.indexing.AbstractNamedQueryTest;
+import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
+import org.slf4j.LoggerFactory;
public class RdfNamedQueryTest extends AbstractNamedQueryTest
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfQueryMultimoduleTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfQueryMultimoduleTest.java b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfQueryMultimoduleTest.java
index 0ed4774..d9d0cf1 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfQueryMultimoduleTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfQueryMultimoduleTest.java
@@ -28,6 +28,7 @@ import org.apache.polygene.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
import org.apache.polygene.index.rdf.assembly.RdfNativeSesameStoreAssembler;
import org.apache.polygene.library.rdf.repository.NativeConfiguration;
import org.apache.polygene.test.EntityTestAssembler;
+import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
@@ -53,6 +54,7 @@ public class RdfQueryMultimoduleTest
ModuleAssembly indexModule = layer.module( "index" );
new RdfNativeSesameStoreAssembler( Visibility.layer, Visibility.module ).assemble( indexModule );
new DefaultUnitOfWorkAssembler().assemble( indexModule );
+ new JacksonValueSerializationAssembler().assemble( indexModule );
LayerAssembly configLayer = module.layer().application().layer( "config" );
module.layer().uses( configLayer );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/qi95/Qi95IssueTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/qi95/Qi95IssueTest.java b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/qi95/Qi95IssueTest.java
index 1d57ef0..9dd94b7 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/qi95/Qi95IssueTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/qi95/Qi95IssueTest.java
@@ -24,6 +24,7 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.apache.polygene.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
+import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
import org.junit.Rule;
import org.junit.Test;
import org.apache.polygene.api.common.Visibility;
@@ -43,7 +44,6 @@ import org.apache.polygene.index.rdf.assembly.RdfMemoryStoreAssembler;
import org.apache.polygene.index.rdf.assembly.RdfNativeSesameStoreAssembler;
import org.apache.polygene.library.rdf.repository.NativeConfiguration;
import org.apache.polygene.test.EntityTestAssembler;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.junit.rules.TemporaryFolder;
import static org.junit.Assert.assertTrue;
@@ -221,6 +221,7 @@ public class Qi95IssueTest
public ModuleAssembly buildModuleAssembly( LayerAssembly layer, String name )
throws AssemblyException
{
+ addModule( layer, name, new JacksonValueSerializationAssembler() );
return addModule( layer, name, new RdfNativeSesameStoreAssembler() );
}
};
@@ -241,6 +242,7 @@ public class Qi95IssueTest
public ModuleAssembly buildModuleAssembly( LayerAssembly layer, String name )
throws AssemblyException
{
+ addModule( layer, name, new JacksonValueSerializationAssembler() );
return addModule( layer, name, new RdfMemoryStoreAssembler() );
}
};
@@ -322,7 +324,7 @@ public class Qi95IssueTest
public void assemble( ModuleAssembly module )
throws AssemblyException
{
- new OrgJsonValueSerializationAssembler().assemble( module );
+ new JacksonValueSerializationAssembler().assemble( module );
new JdbmEntityStoreAssembler().visibleIn( Visibility.application ).assemble( module );
new DefaultUnitOfWorkAssembler().assemble( module );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/indexing-solr/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/indexing-solr/build.gradle b/extensions/indexing-solr/build.gradle
index 608bec3..fd991f6 100644
--- a/extensions/indexing-solr/build.gradle
+++ b/extensions/indexing-solr/build.gradle
@@ -34,6 +34,7 @@ dependencies {
runtimeOnly polygene.core.runtime
testImplementation polygene.core.testsupport
+ testImplementation polygene.extension( 'valueserialization-jackson' )
testRuntimeOnly libraries.logback
testRuntimeOnly libraries.servlet_api
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/indexing-solr/src/main/java/org/apache/polygene/index/solr/assembly/SolrAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-solr/src/main/java/org/apache/polygene/index/solr/assembly/SolrAssembler.java b/extensions/indexing-solr/src/main/java/org/apache/polygene/index/solr/assembly/SolrAssembler.java
deleted file mode 100644
index 38b97e3..0000000
--- a/extensions/indexing-solr/src/main/java/org/apache/polygene/index/solr/assembly/SolrAssembler.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-
-package org.apache.polygene.index.solr.assembly;
-
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.bootstrap.Assemblers;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.bootstrap.ServiceDeclaration;
-import org.apache.polygene.index.solr.EmbeddedSolrService;
-import org.apache.polygene.index.solr.SolrQueryService;
-import org.apache.polygene.library.rdf.entity.EntityStateSerializer;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
-
-public class SolrAssembler extends Assemblers.VisibilityIdentity
-{
- @Override
- public void assemble( ModuleAssembly module ) throws AssemblyException
- {
- module.services( EmbeddedSolrService.class ).identifiedBy( "solr" ).instantiateOnStartup();
- ServiceDeclaration queryService = module.services( SolrQueryService.class );
- queryService.
- taggedWith( "solr", "search", "indexing", "query" ).
- identifiedBy( identity() ).
- visibleIn( visibility() ).
- instantiateOnStartup();
- module.services( OrgJsonValueSerializationService.class ).taggedWith( ValueSerialization.Formats.JSON );
- module.objects( EntityStateSerializer.class );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/indexing-solr/src/main/java/org/apache/polygene/index/solr/assembly/SolrIndexingAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-solr/src/main/java/org/apache/polygene/index/solr/assembly/SolrIndexingAssembler.java b/extensions/indexing-solr/src/main/java/org/apache/polygene/index/solr/assembly/SolrIndexingAssembler.java
new file mode 100644
index 0000000..fa6b59c
--- /dev/null
+++ b/extensions/indexing-solr/src/main/java/org/apache/polygene/index/solr/assembly/SolrIndexingAssembler.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+
+package org.apache.polygene.index.solr.assembly;
+
+import org.apache.polygene.api.value.ValueSerialization;
+import org.apache.polygene.bootstrap.Assemblers;
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.bootstrap.ServiceDeclaration;
+import org.apache.polygene.index.solr.EmbeddedSolrService;
+import org.apache.polygene.index.solr.SolrQueryService;
+import org.apache.polygene.library.rdf.entity.EntityStateSerializer;
+import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
+
+public class SolrIndexingAssembler extends Assemblers.VisibilityIdentityConfig<SolrIndexingAssembler>
+{
+ @Override
+ public void assemble( ModuleAssembly module ) throws AssemblyException
+ {
+ module.services( EmbeddedSolrService.class ).identifiedBy( "solr" ).instantiateOnStartup();
+ ServiceDeclaration queryService = module.services( SolrQueryService.class );
+ queryService.
+ taggedWith( "solr", "search", "indexing", "query" ).
+ identifiedBy( identity() ).
+ visibleIn( visibility() ).
+ instantiateOnStartup();
+ module.objects( EntityStateSerializer.class );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrEntityFinderTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrEntityFinderTest.java b/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrEntityFinderTest.java
index d51ca13..c67e70b 100644
--- a/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrEntityFinderTest.java
+++ b/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrEntityFinderTest.java
@@ -21,7 +21,7 @@ package org.apache.polygene.index.solr;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.index.solr.assembly.SolrAssembler;
+import org.apache.polygene.index.solr.assembly.SolrIndexingAssembler;
import org.apache.polygene.library.fileconfig.FileConfigurationAssembler;
import org.apache.polygene.library.fileconfig.FileConfigurationOverride;
import org.apache.polygene.test.indexing.AbstractEntityFinderTest;
@@ -44,6 +44,6 @@ public class SolrEntityFinderTest
new FileConfigurationAssembler()
.withOverride( new FileConfigurationOverride().withConventionalRoot( tmpDir.getRoot() ) )
.assemble( module );
- new SolrAssembler().assemble( module );
+ new SolrIndexingAssembler().assemble( module );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrNamedQueryTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrNamedQueryTest.java b/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrNamedQueryTest.java
index fab66ac..daba9b3 100644
--- a/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrNamedQueryTest.java
+++ b/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrNamedQueryTest.java
@@ -23,7 +23,7 @@ import java.util.function.Predicate;
import org.apache.polygene.api.composite.Composite;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.index.solr.assembly.SolrAssembler;
+import org.apache.polygene.index.solr.assembly.SolrIndexingAssembler;
import org.apache.polygene.library.fileconfig.FileConfigurationAssembler;
import org.apache.polygene.library.fileconfig.FileConfigurationOverride;
import org.apache.polygene.test.indexing.AbstractNamedQueryTest;
@@ -46,7 +46,7 @@ public class SolrNamedQueryTest
new FileConfigurationAssembler()
.withOverride( new FileConfigurationOverride().withConventionalRoot( tmpDir.getRoot() ) )
.assemble( module );
- new SolrAssembler().assemble( module );
+ new SolrIndexingAssembler().assemble( module );
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrQueryServiceTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrQueryServiceTest.java b/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrQueryServiceTest.java
index c5b06f9..01d3440 100644
--- a/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrQueryServiceTest.java
+++ b/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrQueryServiceTest.java
@@ -21,7 +21,7 @@ package org.apache.polygene.index.solr;
import java.util.ArrayList;
import java.util.List;
-import org.apache.polygene.index.solr.assembly.SolrAssembler;
+import org.apache.polygene.index.solr.assembly.SolrIndexingAssembler;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
@@ -64,7 +64,7 @@ public class SolrQueryServiceTest
new EntityTestAssembler().assemble( module );
// START SNIPPET: assembly
- new SolrAssembler().assemble( module );
+ new SolrIndexingAssembler().assemble( module );
// END SNIPPET: assembly
module.entities( TestEntity.class );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrQueryTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrQueryTest.java b/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrQueryTest.java
index 376574c..f61b665 100644
--- a/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrQueryTest.java
+++ b/extensions/indexing-solr/src/test/java/org/apache/polygene/index/solr/SolrQueryTest.java
@@ -21,7 +21,7 @@ package org.apache.polygene.index.solr;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.index.solr.assembly.SolrAssembler;
+import org.apache.polygene.index.solr.assembly.SolrIndexingAssembler;
import org.apache.polygene.library.fileconfig.FileConfigurationAssembler;
import org.apache.polygene.library.fileconfig.FileConfigurationOverride;
import org.apache.polygene.test.indexing.AbstractQueryTest;
@@ -44,6 +44,6 @@ public class SolrQueryTest
new FileConfigurationAssembler()
.withOverride( new FileConfigurationOverride().withConventionalRoot( tmpDir.getRoot() ) )
.assemble( module );
- new SolrAssembler().assemble( module );
+ new SolrIndexingAssembler().assemble( module );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/indexing-sql/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/indexing-sql/build.gradle b/extensions/indexing-sql/build.gradle
index e0e50e8..0c8a21e 100644
--- a/extensions/indexing-sql/build.gradle
+++ b/extensions/indexing-sql/build.gradle
@@ -38,6 +38,7 @@ dependencies {
testImplementation polygene.internals.testsupport
testImplementation polygene.library( 'sql-dbcp' )
+ testImplementation polygene.extension( 'valueserialization-jackson' )
testRuntimeOnly libraries.logback
testRuntimeOnly libraries.derby
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/assembly/SQLIndexingAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/assembly/SQLIndexingAssembler.java b/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/assembly/SQLIndexingAssembler.java
new file mode 100644
index 0000000..af137de
--- /dev/null
+++ b/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/assembly/SQLIndexingAssembler.java
@@ -0,0 +1,24 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.index.sql.assembly;
+
+public class SQLIndexingAssembler extends PostgreSQLIndexQueryAssembler
+{
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/metrics-codahale/src/main/java/org/apache/polygene/metrics/codahale/assembly/CodahaleMetricsAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/metrics-codahale/src/main/java/org/apache/polygene/metrics/codahale/assembly/CodahaleMetricsAssembler.java b/extensions/metrics-codahale/src/main/java/org/apache/polygene/metrics/codahale/assembly/CodahaleMetricsAssembler.java
index 7e9b843..a737c06 100644
--- a/extensions/metrics-codahale/src/main/java/org/apache/polygene/metrics/codahale/assembly/CodahaleMetricsAssembler.java
+++ b/extensions/metrics-codahale/src/main/java/org/apache/polygene/metrics/codahale/assembly/CodahaleMetricsAssembler.java
@@ -36,7 +36,7 @@ import org.apache.polygene.bootstrap.ServiceDeclaration;
import org.apache.polygene.metrics.codahale.CodahaleMetricsProvider;
public class CodahaleMetricsAssembler
- extends Assemblers.VisibilityIdentity<CodahaleMetricsAssembler>
+ extends Assemblers.VisibilityIdentityConfig<CodahaleMetricsAssembler>
{
private final CodahaleMetricsDeclaration declaration = new CodahaleMetricsDeclaration();
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/JacksonValueSerializationAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/JacksonValueSerializationAssembler.java b/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/JacksonValueSerializationAssembler.java
deleted file mode 100644
index 8f6421d..0000000
--- a/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/JacksonValueSerializationAssembler.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.jackson;
-
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.bootstrap.Assemblers;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-
-/**
- * Assemble a ValueSerialization Service producing and consuming JSON documents.
- */
-public class JacksonValueSerializationAssembler
- extends Assemblers.Visibility<JacksonValueSerializationAssembler>
-{
- @Override
- public void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- module.services( JacksonValueSerializationService.class ).
- visibleIn( visibility() ).
- taggedWith( ValueSerialization.Formats.JSON );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/assembly/JacksonValueSerializationAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/assembly/JacksonValueSerializationAssembler.java b/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/assembly/JacksonValueSerializationAssembler.java
new file mode 100644
index 0000000..7bff000
--- /dev/null
+++ b/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/assembly/JacksonValueSerializationAssembler.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.valueserialization.jackson.assembly;
+
+import org.apache.polygene.api.value.ValueSerialization;
+import org.apache.polygene.bootstrap.Assemblers;
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.valueserialization.jackson.JacksonValueSerializationService;
+
+/**
+ * Assemble a ValueSerialization Service producing and consuming JSON documents.
+ */
+public class JacksonValueSerializationAssembler
+ extends Assemblers.Visibility<JacksonValueSerializationAssembler>
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ throws AssemblyException
+ {
+ module.services( JacksonValueSerializationService.class )
+ .visibleIn( visibility() )
+ .taggedWith( ValueSerialization.Formats.JSON );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonCollectionSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonCollectionSerializationTest.java b/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonCollectionSerializationTest.java
index 8160c55..f4069c3 100644
--- a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonCollectionSerializationTest.java
+++ b/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonCollectionSerializationTest.java
@@ -22,6 +22,7 @@ package org.apache.polygene.valueserialization.jackson;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.test.value.AbstractCollectionSerializationTest;
+import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
public class JacksonCollectionSerializationTest
extends AbstractCollectionSerializationTest
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonConfigurationDeserializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonConfigurationDeserializationTest.java b/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonConfigurationDeserializationTest.java
index fb59e8e..1948d62 100644
--- a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonConfigurationDeserializationTest.java
+++ b/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonConfigurationDeserializationTest.java
@@ -23,6 +23,7 @@ package org.apache.polygene.valueserialization.jackson;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.test.entity.AbstractConfigurationDeserializationTest;
+import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
public class JacksonConfigurationDeserializationTest
extends AbstractConfigurationDeserializationTest
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonJsonDateFormatTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonJsonDateFormatTest.java b/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonJsonDateFormatTest.java
index 78f27b0..bbc141d 100644
--- a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonJsonDateFormatTest.java
+++ b/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonJsonDateFormatTest.java
@@ -22,6 +22,7 @@ package org.apache.polygene.valueserialization.jackson;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.test.value.AbstractJsonDateFormatTest;
+import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
public class JacksonJsonDateFormatTest
extends AbstractJsonDateFormatTest
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonPlainValueSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonPlainValueSerializationTest.java b/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonPlainValueSerializationTest.java
index b4ad6a4..cdcce17 100644
--- a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonPlainValueSerializationTest.java
+++ b/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonPlainValueSerializationTest.java
@@ -21,6 +21,7 @@ package org.apache.polygene.valueserialization.jackson;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.test.value.AbstractPlainValueSerializationTest;
+import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
public class JacksonPlainValueSerializationTest
extends AbstractPlainValueSerializationTest
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonValueCompositeSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonValueCompositeSerializationTest.java b/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonValueCompositeSerializationTest.java
index 49f7eba..2a757ab 100644
--- a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonValueCompositeSerializationTest.java
+++ b/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonValueCompositeSerializationTest.java
@@ -22,6 +22,7 @@ package org.apache.polygene.valueserialization.jackson;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.test.value.AbstractValueCompositeSerializationTest;
+import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
public class JacksonValueCompositeSerializationTest
extends AbstractValueCompositeSerializationTest
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/StaxValueSerializationAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/StaxValueSerializationAssembler.java b/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/StaxValueSerializationAssembler.java
deleted file mode 100644
index e972acb..0000000
--- a/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/StaxValueSerializationAssembler.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.stax;
-
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.bootstrap.Assemblers;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-
-/**
- * Assemble a ValueSerialization Service producing and consuming XML documents.
- */
-public class StaxValueSerializationAssembler
- extends Assemblers.Visibility<StaxValueSerializationAssembler>
-{
- @Override
- public void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- module.services( StaxValueSerializationService.class ).
- visibleIn( visibility() ).
- taggedWith( ValueSerialization.Formats.XML );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/assembly/StaxValueSerializationAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/assembly/StaxValueSerializationAssembler.java b/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/assembly/StaxValueSerializationAssembler.java
new file mode 100644
index 0000000..8eaede4
--- /dev/null
+++ b/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/assembly/StaxValueSerializationAssembler.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.valueserialization.stax.assembly;
+
+import org.apache.polygene.api.value.ValueSerialization;
+import org.apache.polygene.bootstrap.Assemblers;
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.valueserialization.stax.StaxValueSerializationService;
+
+/**
+ * Assemble a ValueSerialization Service producing and consuming XML documents.
+ */
+public class StaxValueSerializationAssembler
+ extends Assemblers.Visibility<StaxValueSerializationAssembler>
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ throws AssemblyException
+ {
+ module.services( StaxValueSerializationService.class )
+ .visibleIn( visibility() )
+ .taggedWith( ValueSerialization.Formats.XML );
+ }
+}
[19/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/StaxValueDeserializer.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/StaxValueDeserializer.java b/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/StaxValueDeserializer.java
deleted file mode 100644
index 80d282b..0000000
--- a/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/StaxValueDeserializer.java
+++ /dev/null
@@ -1,522 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.stax;
-
-import java.io.InputStream;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.util.Collection;
-import java.util.Map;
-import java.util.function.Function;
-import javax.xml.stream.XMLEventReader;
-import javax.xml.stream.XMLInputFactory;
-import javax.xml.stream.XMLStreamException;
-import javax.xml.stream.events.XMLEvent;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMResult;
-import javax.xml.transform.stream.StreamSource;
-import org.apache.commons.lang3.StringEscapeUtils;
-import org.apache.polygene.api.structure.ModuleDescriptor;
-import org.apache.polygene.api.value.ValueSerializationException;
-import org.apache.polygene.spi.value.ValueDeserializerAdapter;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-/**
- * ValueDeserializer reading Values from XML documents.
- */
-public class StaxValueDeserializer
- extends ValueDeserializerAdapter<XMLEventReader, Node>
-{
-
- private final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
- private final TransformerFactory transformerFactory = TransformerFactory.newInstance();
-
- public StaxValueDeserializer()
- {
- // Input Factory setup
- inputFactory.setProperty( "javax.xml.stream.isValidating", Boolean.FALSE );
- inputFactory.setProperty( "javax.xml.stream.isNamespaceAware", Boolean.FALSE );
- inputFactory.setProperty( "javax.xml.stream.supportDTD", Boolean.FALSE );
- inputFactory.setProperty( "javax.xml.stream.isCoalescing", Boolean.TRUE );
- inputFactory.setProperty( "javax.xml.stream.isReplacingEntityReferences", Boolean.FALSE );
- }
-
- @Override
- protected XMLEventReader adaptInput( ModuleDescriptor module, InputStream input )
- throws Exception
- {
- return inputFactory.createXMLEventReader( input, "UTF-8" );
- }
-
- @Override
- protected Object readPlainValue( ModuleDescriptor module, XMLEventReader input )
- throws Exception
- {
- if( !input.hasNext() )
- {
- return null;
- }
- XMLEvent nextEvent = input.nextEvent();
- if( nextEvent.getEventType() == XMLEvent.START_ELEMENT
- && "null".equals( nextEvent.asStartElement().getName().getLocalPart() ) )
- {
- input.nextTag();
- return null;
- }
- if( nextEvent.getEventType() != XMLEvent.CHARACTERS )
- {
- throw new ValueSerializationException( "Expected characters but got: " + nextEvent );
- }
- String stringValue = nextEvent.asCharacters().getData();
- return detectAndConvertStringValue( stringValue );
- }
-
- @Override
- protected <T> Collection<T> readArrayInCollection( ModuleDescriptor module,
- XMLEventReader input,
- Function<XMLEventReader, T> deserializer,
- Collection<T> collection
- )
- throws Exception
- {
- if( !input.hasNext() )
- {
- return null;
- }
- XMLEvent nextTag = input.nextTag();
- if( nextTag.isStartElement() && "null".equals( nextTag.asStartElement().getName().getLocalPart() ) )
- {
- input.nextTag();
- return null;
- }
- if( !nextTag.isStartElement() || !"array".equals( nextTag.asStartElement().getName().getLocalPart() ) )
- {
- throw new ValueSerializationException( "Expected an <array/> but got: " + nextTag );
- }
- WHILE:
- while( input.hasNext() )
- {
- XMLEvent currentTag = input.nextTag();
- if( currentTag.isEndElement() )
- {
- String endElementName = currentTag.asEndElement().getName().getLocalPart();
- switch( endElementName )
- {
- case "array":
- break WHILE;
- case "value":
- continue;
- }
- }
- if( !"value".equals( currentTag.asStartElement().getName().getLocalPart() ) )
- {
- throw new ValueSerializationException( "Expected a <value/> but got: " + currentTag );
- }
- T item = deserializer.apply( input );
- collection.add( item );
- }
- return collection;
- }
-
- @Override
- protected <K, V> Map<K, V> readMapInMap( ModuleDescriptor module,
- XMLEventReader input,
- Function<XMLEventReader, K> keyDeserializer,
- Function<XMLEventReader, V> valueDeserializer,
- Map<K, V> map
- )
- throws Exception
- {
- if( !input.hasNext() )
- {
- return null;
- }
- XMLEvent nextTag = input.nextTag();
- if( nextTag.isStartElement() && "null".equals( nextTag.asStartElement().getName().getLocalPart() ) )
- {
- input.nextTag();
- return null;
- }
- if( !nextTag.isStartElement() || !"array".equals( nextTag.asStartElement().getName().getLocalPart() ) )
- {
- throw new ValueSerializationException( "Expected an <array/> but got: " + nextTag );
- }
- XMLEvent currentTag = input.nextTag(); // <object>
- while( !currentTag.isEndElement() || !"array".equals( currentTag.asEndElement().getName().getLocalPart() ) )
- {
- if( !currentTag.isStartElement() || !"object".equals( currentTag.asStartElement()
- .getName()
- .getLocalPart() ) )
- {
- throw new ValueSerializationException( "Expected an <object/> but got: " + nextTag );
- }
- currentTag = input.nextTag(); // <field>
- K key = null;
- V value = null;
- while( !currentTag.isEndElement() || !"object".equals( currentTag.asEndElement()
- .getName()
- .getLocalPart() ) )
- {
- input.nextTag(); // <name>
- String keyOrValue = input.nextEvent().asCharacters().getData();
- input.nextTag(); // </name>
- input.nextTag(); // <value>
- switch( keyOrValue )
- {
- case "key":
- key = keyDeserializer.apply( input );
- break;
- case "value":
- value = valueDeserializer.apply( input );
- break;
- default:
- readObjectTree( module, input );
- break;
- }
- input.nextTag(); // </value>
- input.nextTag(); // </field>
- currentTag = input.nextTag();
- }
- if( key != null )
- {
- map.put( key, value );
- }
- currentTag = input.nextTag();
- }
- return map;
- }
-
- @Override
- protected Node readObjectTree( ModuleDescriptor module, XMLEventReader input )
- throws Exception
- {
- XMLEvent peek = input.peek();
- if( peek.isStartElement() && "null".equals( peek.asStartElement().getName().getLocalPart() ) )
- {
- input.nextTag();// <null>
- input.nextTag();// </null>
- return null;
- }
- String elementBody = readElementBody( input );
- Transformer transformer = transformerFactory.newTransformer();
- DOMResult domResult = new DOMResult();
- transformer.transform( new StreamSource( new StringReader( elementBody ) ), domResult );
- return ( (Document) domResult.getNode() ).getDocumentElement();
- }
-
- private static String readElementBody( XMLEventReader input )
- throws XMLStreamException
- {
- StringWriter buf = new StringWriter( 1024 );
- int depth = 0;
- while( input.hasNext() )
- {
- // peek event
- XMLEvent xmlEvent = input.peek();
- if( xmlEvent.isStartElement() )
- {
- ++depth;
- }
- else if( xmlEvent.isEndElement() )
- {
- --depth;
- // reached END_ELEMENT tag?
- // break loop, leave event in stream
- if( depth < 0 )
- {
- break;
- }
- }
- // consume event
- xmlEvent = input.nextEvent();
- // print out event
- xmlEvent.writeAsEncodedUnicode( buf );
- }
- return buf.getBuffer().toString();
- }
-
- @Override
- protected Object asSimpleValue( ModuleDescriptor module, Node inputNode )
- throws Exception
- {
- if( inputNode == null )
- {
- return null;
- }
- if( inputNode.getNodeType() == Node.ELEMENT_NODE && "null".equals( inputNode.getLocalName() ) )
- {
- return null;
- }
- if( inputNode.getNodeType() != Node.TEXT_NODE && inputNode.getNodeType() != Node.CDATA_SECTION_NODE )
- {
- throw new ValueSerializationException( "Expected a TEXT or CDATA node but got " + inputNode );
- }
- String stringValue = inputNode.getNodeValue();
- return detectAndConvertStringValue( stringValue );
- }
-
- @Override
- @SuppressWarnings( "SimplifiableIfStatement" )
- protected boolean isObjectValue( ModuleDescriptor module, Node inputNode )
- throws Exception
- {
- if( inputNode == null )
- {
- return false;
- }
- if( "object".equals( inputNode.getLocalName() ) )
- {
- return true;
- }
- if( !"value".equals( inputNode.getLocalName() ) )
- {
- return false;
- }
- return getDirectChildNode( inputNode, "object" ) != null;
- }
-
- @Override
- protected boolean objectHasField( ModuleDescriptor module, Node inputNode, String key )
- throws Exception
- {
- if( inputNode == null )
- {
- return false;
- }
- Node objectNode;
- if( "value".equals( inputNode.getLocalName() ) )
- {
- objectNode = getDirectChildNode( inputNode, "object" );
- }
- else
- {
- objectNode = inputNode;
- }
- if( objectNode == null )
- {
- return false;
- }
- if( !"object".equals( objectNode.getLocalName() ) )
- {
- throw new ValueSerializationException( "Expected an object value but got: " + objectNode );
- }
- return getObjectFieldNode( objectNode, key ) != null;
- }
-
- @Override
- @SuppressWarnings( "unchecked" )
- protected <T> T getObjectFieldValue( ModuleDescriptor module,
- Node inputNode,
- String key,
- Function<Node, T> valueDeserializer
- )
- throws Exception
- {
- if( inputNode == null )
- {
- return null;
- }
- Node objectNode;
- if( "value".equals( inputNode.getLocalName() ) )
- {
- objectNode = getDirectChildNode( inputNode, "object" );
- }
- else
- {
- objectNode = inputNode;
- }
- if( objectNode == null )
- {
- return null;
- }
- if( !"object".equals( objectNode.getLocalName() ) )
- {
- throw new ValueSerializationException( "Expected an object value but got: " + objectNode );
- }
- Node fieldNode = getObjectFieldNode( objectNode, key );
- if( fieldNode == null )
- {
- return null;
- }
- Node valueElement = getDirectChildNode( fieldNode, "value" );
- if( valueElement == null )
- {
- return null;
- }
- Node valueNode = valueElement.getFirstChild();
- if( valueNode == null )
- {
- return (T) "";
- }
- if( valueNode.getNodeType() == Node.ELEMENT_NODE && "null".equals( valueNode.getLocalName() ) )
- {
- return null;
- }
- return valueDeserializer.apply( valueNode );
- }
-
- @Override
- protected <T> void putArrayNodeInCollection( ModuleDescriptor module,
- Node inputNode,
- Function<Node, T> deserializer,
- Collection<T> collection
- )
- throws Exception
- {
- if( inputNode == null )
- {
- return;
- }
- if( !( inputNode instanceof Element ) )
- {
- throw new ValueSerializationException( "Expected an Element but got " + inputNode );
- }
- NodeList arrayValues = inputNode.getChildNodes();
- for( int arrayValuesIndex = 0; arrayValuesIndex < arrayValues.getLength(); arrayValuesIndex++ )
- {
- Node arrayValue = arrayValues.item( arrayValuesIndex );
- T value = deserializer.apply( arrayValue.getFirstChild() );
- collection.add( value );
- }
- }
-
- @Override
- protected <K, V> void putArrayNodeInMap( ModuleDescriptor module,
- Node inputNode,
- Function<Node, K> keyDeserializer,
- Function<Node, V> valueDeserializer, Map<K, V> map
- )
- throws Exception
- {
- if( inputNode == null )
- {
- return;
- }
- if( !"array".equals( inputNode.getLocalName() ) )
- {
- throw new ValueSerializationException( "Expected an <array/> but got " + inputNode );
- }
- NodeList entriesNodes = inputNode.getChildNodes();
- for( int idx = 0; idx < entriesNodes.getLength(); idx++ )
- {
- Node entryNode = entriesNodes.item( idx );
- K key = getObjectFieldValue( module, entryNode, "key", keyDeserializer );
- V value = getObjectFieldValue( module, entryNode, "value", valueDeserializer );
- if( key != null )
- {
- map.put( key, value );
- }
- }
- }
-
- @Override
- protected <V> void putObjectNodeInMap( ModuleDescriptor module,
- Node inputNode,
- Function<Node, V> valueDeserializer,
- Map<String, V> map
- )
- throws Exception
- {
- if( inputNode == null )
- {
- return;
- }
- if( !"object".equals( inputNode.getLocalName() ) )
- {
- throw new ValueSerializationException( "Expected an <object/> but got " + inputNode );
- }
- NodeList fieldsNodes = inputNode.getChildNodes();
- for( int idx = 0; idx < fieldsNodes.getLength(); idx++ )
- {
- Node fieldNode = fieldsNodes.item( idx );
- Node node = getDirectChildNode( fieldNode, "name" );
- String key = node != null ? node.getTextContent() : null;
- if( key != null && key.length() > 0 )
- {
- V value = getObjectFieldValue( module, inputNode, key, valueDeserializer );
- map.put( key, value );
- }
- }
- }
-
- @SuppressWarnings( "AssignmentToMethodParameter" )
- private Object detectAndConvertStringValue( String stringValue )
- {
- if( stringValue == null || stringValue.length() == 0 )
- {
- return "";
- }
- stringValue = StringEscapeUtils.unescapeXml( stringValue );
- if( stringValue.matches( "[+-]?\\d+(\\.\\d+)?([eE][+-]?\\d+(\\.\\d+)?)?" ) )
- {
- if( stringValue.indexOf( '.' ) != -1 )
- {
- return new BigDecimal( stringValue );
- }
- return new BigInteger( stringValue );
- }
- if( "true".equalsIgnoreCase( stringValue ) || "false".equalsIgnoreCase( stringValue ) )
- {
- return Boolean.parseBoolean( stringValue );
- }
- return stringValue;
- }
-
- private static Node getObjectFieldNode( Node inputNode, String key )
- {
- if( inputNode == null )
- {
- return null;
- }
- if( !( inputNode instanceof Element ) )
- {
- throw new ValueSerializationException( "Excpected an Element but got " + inputNode );
- }
- NodeList fieldNodes = inputNode.getChildNodes();
- for( int idx = 0; idx < fieldNodes.getLength(); idx++ )
- {
- Node fieldNode = fieldNodes.item( idx );
- Node nameNode = getDirectChildNode( fieldNode, "name" );
- if( nameNode != null && key.equals( nameNode.getTextContent() ) )
- {
- return fieldNode;
- }
- }
- return null;
- }
-
- private static Node getDirectChildNode( Node parent, String name )
- {
- for( Node child = parent.getFirstChild(); child != null; child = child.getNextSibling() )
- {
- if( name.equals( child.getNodeName() ) )
- {
- return child;
- }
- }
- return null;
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/StaxValueSerializationService.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/StaxValueSerializationService.java b/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/StaxValueSerializationService.java
deleted file mode 100644
index 11c752b..0000000
--- a/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/StaxValueSerializationService.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.stax;
-
-import org.apache.polygene.api.mixin.Mixins;
-import org.apache.polygene.api.value.ValueSerialization;
-
-/**
- * ValueSerialization Service producing and consuming XML documents.
- */
-@Mixins( { StaxValueSerializer.class, StaxValueDeserializer.class } )
-public interface StaxValueSerializationService
- extends ValueSerialization
-{
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/StaxValueSerializer.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/StaxValueSerializer.java b/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/StaxValueSerializer.java
deleted file mode 100644
index ef292d1..0000000
--- a/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/StaxValueSerializer.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.stax;
-
-import java.io.OutputStream;
-import javax.xml.stream.XMLOutputFactory;
-import javax.xml.stream.XMLStreamWriter;
-import org.apache.commons.lang3.StringEscapeUtils;
-import org.apache.polygene.spi.value.ValueSerializerAdapter;
-
-/**
- * ValueSerializer producing Values state as XML documents.
- */
-public class StaxValueSerializer
- extends ValueSerializerAdapter<XMLStreamWriter>
-{
-
- private final XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
-
- public StaxValueSerializer()
- {
- // Output Factory setup
- outputFactory.setProperty( "javax.xml.stream.isRepairingNamespaces", Boolean.FALSE );
- }
-
- @Override
- protected XMLStreamWriter adaptOutput( OutputStream output )
- throws Exception
- {
- XMLStreamWriter xmlStreamWriter = outputFactory.createXMLStreamWriter( output, "UTF-8" );
- xmlStreamWriter.writeStartDocument( "utf-8", "1.1" );
- return xmlStreamWriter;
- }
-
- @Override
- protected void onSerializationEnd( Object object, XMLStreamWriter output )
- throws Exception
- {
- output.writeEndDocument();
- output.flush();
- output.close();
- }
-
- @Override
- protected void onArrayStart( XMLStreamWriter output )
- throws Exception
- {
- output.writeStartElement( "array" );
- }
-
- @Override
- protected void onArrayEnd( XMLStreamWriter output )
- throws Exception
- {
- output.writeEndElement();
- }
-
- @Override
- protected void onObjectStart( XMLStreamWriter output )
- throws Exception
- {
- output.writeStartElement( "object" );
- }
-
- @Override
- protected void onObjectEnd( XMLStreamWriter output )
- throws Exception
- {
- output.writeEndElement();
- }
-
- @Override
- protected void onFieldStart( XMLStreamWriter output, String key )
- throws Exception
- {
- output.writeStartElement( "field" );
- output.writeStartElement( "name" );
- output.writeCharacters( key );
- output.writeEndElement();
- }
-
- @Override
- protected void onFieldEnd( XMLStreamWriter output )
- throws Exception
- {
- output.writeEndElement();
- }
-
- @Override
- protected void onValueStart( XMLStreamWriter output )
- throws Exception
- {
- output.writeStartElement( "value" );
- }
-
- @Override
- protected void onValue( XMLStreamWriter output, Object value )
- throws Exception
- {
- if( value == null )
- {
- output.writeStartElement( "null" );
- output.writeEndElement();
- }
- else
- {
- output.writeCharacters( StringEscapeUtils.escapeXml( value.toString() ) );
- }
- }
-
- @Override
- protected void onValueEnd( XMLStreamWriter output )
- throws Exception
- {
- output.writeEndElement();
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/assembly/StaxValueSerializationAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/assembly/StaxValueSerializationAssembler.java b/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/assembly/StaxValueSerializationAssembler.java
deleted file mode 100644
index 8eaede4..0000000
--- a/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/assembly/StaxValueSerializationAssembler.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.stax.assembly;
-
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.bootstrap.Assemblers;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.valueserialization.stax.StaxValueSerializationService;
-
-/**
- * Assemble a ValueSerialization Service producing and consuming XML documents.
- */
-public class StaxValueSerializationAssembler
- extends Assemblers.Visibility<StaxValueSerializationAssembler>
-{
- @Override
- public void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- module.services( StaxValueSerializationService.class )
- .visibleIn( visibility() )
- .taggedWith( ValueSerialization.Formats.XML );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/package.html
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/package.html b/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/package.html
deleted file mode 100644
index a79d1b0..0000000
--- a/extensions/valueserialization-stax/src/main/java/org/apache/polygene/valueserialization/stax/package.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one
- ~ or more contributor license agreements. See the NOTICE file
- ~ distributed with this work for additional information
- ~ regarding copyright ownership. The ASF licenses this file
- ~ to you under the Apache License, Version 2.0 (the
- ~ "License"); you may not use this file except in compliance
- ~ with the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- ~
- ~
- -->
-<html>
- <body>
- <h2>XML StAX Value Serializer.</h2>
- </body>
-</html>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxCollectionSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxCollectionSerializationTest.java b/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxCollectionSerializationTest.java
deleted file mode 100644
index 04ed30a..0000000
--- a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxCollectionSerializationTest.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.stax;
-
-import org.apache.polygene.valueserialization.stax.assembly.StaxValueSerializationAssembler;
-import org.junit.BeforeClass;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.value.AbstractCollectionSerializationTest;
-
-import static org.apache.polygene.test.util.Assume.assumeNoIbmJdk;
-
-public class StaxCollectionSerializationTest
- extends AbstractCollectionSerializationTest
-{
-
- @BeforeClass
- public static void beforeClass_IBMJDK()
- {
- assumeNoIbmJdk();
- }
-
- @Override
- public void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- super.assemble( module );
- new StaxValueSerializationAssembler().assemble( module );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxConfigurationDeserializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxConfigurationDeserializationTest.java b/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxConfigurationDeserializationTest.java
deleted file mode 100644
index 052072f..0000000
--- a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxConfigurationDeserializationTest.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-
-package org.apache.polygene.valueserialization.stax;
-
-import org.apache.polygene.api.identity.StringIdentity;
-import org.apache.polygene.valueserialization.stax.assembly.StaxValueSerializationAssembler;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.apache.polygene.api.injection.scope.Service;
-import org.apache.polygene.api.value.ValueBuilder;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.entity.AbstractConfigurationDeserializationTest;
-
-@Ignore( "Complex configurations are not yet support in Stax ValueSerialization, due to handling arrays with Java serialization.")
-public class StaxConfigurationDeserializationTest
- extends AbstractConfigurationDeserializationTest
-{
- @Service
- private ValueSerialization valueSerialization;
-
- @Override
- public void assemble( final ModuleAssembly module )
- throws AssemblyException
- {
- super.assemble( module );
- new StaxValueSerializationAssembler()
- .assemble( module );
- }
-
- @Test
- public void serializeTest()
- {
- ValueBuilder<ConfigSerializationConfig> builder = valueBuilderFactory.newValueBuilder( ConfigSerializationConfig.class );
- builder.prototype().name().set( "main" );
- builder.prototype().host().set( createHost() );
- builder.prototype().identity().set( new StringIdentity( "configtest" ) );
- ConfigSerializationConfig value = builder.newInstance();
-
- valueSerialization.serialize( value, System.out );
- }
-
- private Host createHost()
- {
- ValueBuilder<Host> builder = valueBuilderFactory.newValueBuilder( Host.class );
- builder.prototype().ip().set( "12.23.34.45" );
- builder.prototype().port().set( 1234 );
- return builder.newInstance();
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxPlainValueSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxPlainValueSerializationTest.java b/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxPlainValueSerializationTest.java
deleted file mode 100644
index 11f1e7d..0000000
--- a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxPlainValueSerializationTest.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.stax;
-
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.value.AbstractPlainValueSerializationTest;
-import org.apache.polygene.valueserialization.stax.assembly.StaxValueSerializationAssembler;
-import org.junit.BeforeClass;
-
-import static org.apache.polygene.test.util.Assume.assumeNoIbmJdk;
-
-public class StaxPlainValueSerializationTest
- extends AbstractPlainValueSerializationTest
-{
- @BeforeClass
- public static void beforeClass_IBMJDK()
- {
- assumeNoIbmJdk();
- }
-
- // START SNIPPET: assembly
- @Override
- public void assemble( ModuleAssembly module )
- {
- new StaxValueSerializationAssembler().assemble( module );
- }
- // END SNIPPET: assembly
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxValueCompositeSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxValueCompositeSerializationTest.java b/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxValueCompositeSerializationTest.java
deleted file mode 100644
index 65d66f6..0000000
--- a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxValueCompositeSerializationTest.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.stax;
-
-import org.apache.polygene.valueserialization.stax.assembly.StaxValueSerializationAssembler;
-import org.junit.BeforeClass;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.value.AbstractValueCompositeSerializationTest;
-
-import static org.apache.polygene.test.util.Assume.assumeNoIbmJdk;
-
-public class StaxValueCompositeSerializationTest
- extends AbstractValueCompositeSerializationTest
-{
-
- @BeforeClass
- public static void beforeClass_IBMJDK()
- {
- assumeNoIbmJdk();
- }
-
- @Override
- public void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- super.assemble( module );
- new StaxValueSerializationAssembler().assemble( module );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-stax/src/test/resources/configtest.xml
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/src/test/resources/configtest.xml b/extensions/valueserialization-stax/src/test/resources/configtest.xml
deleted file mode 100644
index e8100ad..0000000
--- a/extensions/valueserialization-stax/src/test/resources/configtest.xml
+++ /dev/null
@@ -1,50 +0,0 @@
-<?xml version="1.0" ?>
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one
- ~ or more contributor license agreements. See the NOTICE file
- ~ distributed with this work for additional information
- ~ regarding copyright ownership. The ASF licenses this file
- ~ to you under the Apache License, Version 2.0 (the
- ~ "License"); you may not use this file except in compliance
- ~ with the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- ~
- ~
- -->
-
-<object>
- <field>
- <name>name</name>
- <value>main</value>
- </field>
- <field>
- <name>host</name>
- <value>
- <object>
- <field>
- <name>_type</name>
- <value>org.apache.polygene.test.entity.AbstractConfigurationDeserializationTest$Host</value>
- </field>
- <field>
- <name>port</name>
- <value>1234</value>
- </field>
- <field>
- <name>ip</name>
- <value>12.23.34.45</value>
- </field>
- </object>
- </value>
- </field>
- <field>
- <name>identity</name>
- <value>configtest</value>
- </field>
-</object>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/internals/testsupport-internal/build.gradle
----------------------------------------------------------------------
diff --git a/internals/testsupport-internal/build.gradle b/internals/testsupport-internal/build.gradle
index fc70ba0..3878ee0 100644
--- a/internals/testsupport-internal/build.gradle
+++ b/internals/testsupport-internal/build.gradle
@@ -19,10 +19,15 @@
apply plugin: 'polygene-internal'
apply plugin: 'polygene-internal-docker'
+description = "Apache Polygene\u2122 Internal Test Support"
+
+jar { manifest { name = "Apache Polygene\u2122 Internals - Test Support" } }
+
dependencies {
api polygene.core.testsupport
implementation libraries.docker_junit
runtimeOnly polygene.core.runtime
+ runtimeOnly libraries.johnzon // TODO Quid?
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/appbrowser/src/test/java/org/apache/polygene/library/appbrowser/AppBrowserTest.java
----------------------------------------------------------------------
diff --git a/libraries/appbrowser/src/test/java/org/apache/polygene/library/appbrowser/AppBrowserTest.java b/libraries/appbrowser/src/test/java/org/apache/polygene/library/appbrowser/AppBrowserTest.java
index 4a4ffc2..3c59c82 100644
--- a/libraries/appbrowser/src/test/java/org/apache/polygene/library/appbrowser/AppBrowserTest.java
+++ b/libraries/appbrowser/src/test/java/org/apache/polygene/library/appbrowser/AppBrowserTest.java
@@ -31,7 +31,6 @@ import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.property.Property;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
@@ -47,7 +46,6 @@ public class AppBrowserTest extends AbstractPolygeneTest
module.entities( Person.class );
module.values( Age.class );
module.services( MemoryEntityStoreService.class );
- module.importedServices( ValueSerialization.class );
}
@Test
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/constraints/src/test/java/org/apache/polygene/library/constraints/ConstraintTest.java
----------------------------------------------------------------------
diff --git a/libraries/constraints/src/test/java/org/apache/polygene/library/constraints/ConstraintTest.java b/libraries/constraints/src/test/java/org/apache/polygene/library/constraints/ConstraintTest.java
index a0d6346..2c526b5 100644
--- a/libraries/constraints/src/test/java/org/apache/polygene/library/constraints/ConstraintTest.java
+++ b/libraries/constraints/src/test/java/org/apache/polygene/library/constraints/ConstraintTest.java
@@ -20,14 +20,14 @@
package org.apache.polygene.library.constraints;
import java.util.ArrayList;
-import java.util.Arrays;
+import java.util.Collections;
import java.util.HashSet;
-import org.apache.polygene.test.AbstractPolygeneTest;
-import org.junit.Test;
import org.apache.polygene.api.composite.TransientBuilder;
import org.apache.polygene.api.constraint.ConstraintViolationException;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.test.AbstractPolygeneTest;
+import org.junit.Test;
import static org.junit.Assert.fail;
@@ -236,8 +236,8 @@ public class ConstraintTest
{
TransientBuilder<TestCaseComposite> cb = transientBuilderFactory.newTransientBuilder( TestCaseComposite.class );
cb.prototype().notEmptyString().set( "X" );
- cb.prototype().notEmptyCollection().set( Arrays.asList( "X" ) );
- cb.prototype().notEmptyList().set( Arrays.asList( "X" ) );
+ cb.prototype().notEmptyCollection().set( Collections.singletonList( "X" ) );
+ cb.prototype().notEmptyList().set( Collections.singletonList( "X" ) );
}
@Test( expected = ConstraintViolationException.class )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rdf/build.gradle
----------------------------------------------------------------------
diff --git a/libraries/rdf/build.gradle b/libraries/rdf/build.gradle
index c3f175c..50babbe 100644
--- a/libraries/rdf/build.gradle
+++ b/libraries/rdf/build.gradle
@@ -34,7 +34,6 @@ dependencies {
runtimeOnly polygene.core.runtime
testImplementation polygene.core.testsupport
- testImplementation polygene.extension( 'valueserialization-orgjson' )
testRuntimeOnly libraries.logback
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rdf/src/main/java/org/apache/polygene/library/rdf/entity/EntityStateSerializer.java
----------------------------------------------------------------------
diff --git a/libraries/rdf/src/main/java/org/apache/polygene/library/rdf/entity/EntityStateSerializer.java b/libraries/rdf/src/main/java/org/apache/polygene/library/rdf/entity/EntityStateSerializer.java
index 7477179..0bd823b 100644
--- a/libraries/rdf/src/main/java/org/apache/polygene/library/rdf/entity/EntityStateSerializer.java
+++ b/libraries/rdf/src/main/java/org/apache/polygene/library/rdf/entity/EntityStateSerializer.java
@@ -27,17 +27,15 @@ import org.apache.polygene.api.entity.EntityDescriptor;
import org.apache.polygene.api.entity.EntityReference;
import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.property.PropertyDescriptor;
-import org.apache.polygene.api.service.qualifier.Tagged;
+import org.apache.polygene.api.serialization.Serializer;
import org.apache.polygene.api.type.ValueCompositeType;
import org.apache.polygene.api.type.ValueType;
import org.apache.polygene.api.util.Classes;
import org.apache.polygene.api.value.ValueComposite;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.api.value.ValueSerializer;
-import org.apache.polygene.api.value.ValueSerializer.Options;
import org.apache.polygene.library.rdf.Rdfs;
import org.apache.polygene.spi.entity.EntityState;
import org.apache.polygene.spi.entity.ManyAssociationState;
+import org.apache.polygene.spi.serialization.JsonSerializer;
import org.openrdf.model.BNode;
import org.openrdf.model.Graph;
import org.openrdf.model.Literal;
@@ -52,10 +50,8 @@ import org.openrdf.model.impl.GraphImpl;
*/
public class EntityStateSerializer
{
-
@Service
- @Tagged( ValueSerialization.Formats.JSON )
- private ValueSerializer valueSerializer;
+ private JsonSerializer serializer;
public URI createEntityURI( ValueFactory valueFactory, EntityReference reference )
{
@@ -87,7 +83,8 @@ public class EntityStateSerializer
graph.add( entityUri,
Rdfs.TYPE,
- values.createURI( Classes.toURI( entityState.entityDescriptor().types().findFirst().orElse( null ) ) ) );
+ values.createURI(
+ Classes.toURI( entityState.entityDescriptor().types().findFirst().orElse( null ) ) ) );
serializeProperties( entityState,
graph,
@@ -108,29 +105,26 @@ public class EntityStateSerializer
includeNonQueryable );
}
- private void serializeProperties( final EntityState entityState,
- final Graph graph,
- final Resource subject,
- final EntityDescriptor entityType,
- final boolean includeNonQueryable
- )
+ private void serializeProperties( EntityState entityState,
+ Graph graph, Resource subject,
+ EntityDescriptor entityType,
+ boolean includeNonQueryable )
{
// Properties
- entityType.state().properties().forEach( persistentProperty -> {
- Object property = entityState.propertyValueOf( persistentProperty.qualifiedName() );
- if( property != null )
+ entityType.state().properties().forEach(
+ persistentProperty ->
{
- serializeProperty( persistentProperty, property, subject, graph, includeNonQueryable );
- }
- } );
+ Object property = entityState.propertyValueOf( persistentProperty.qualifiedName() );
+ if( property != null )
+ {
+ serializeProperty( persistentProperty, property, subject, graph, includeNonQueryable );
+ }
+ } );
}
- private void serializeProperty( PropertyDescriptor persistentProperty,
- Object property,
- Resource subject,
- Graph graph,
- boolean includeNonQueryable
- )
+ private void serializeProperty( PropertyDescriptor persistentProperty, Object property,
+ Resource subject, Graph graph,
+ boolean includeNonQueryable )
{
if( !( includeNonQueryable || persistentProperty.queryable() ) )
{
@@ -152,7 +146,7 @@ public class EntityStateSerializer
}
else
{
- String stringProperty = valueSerializer.serialize( new Options().withoutTypeInfo(), property );
+ String stringProperty = serializer.serialize( Serializer.Options.NO_TYPE_INFO, property );
final Literal object = valueFactory.createLiteral( stringProperty );
graph.add( subject, predicate, object );
}
@@ -170,29 +164,44 @@ public class EntityStateSerializer
BNode collection = valueFactory.createBNode();
graph.add( subject, predicate, collection );
- ( (ValueCompositeType) valueType ).properties().forEach( persistentProperty -> {
- Object propertyValue = PolygeneAPI.FUNCTION_COMPOSITE_INSTANCE_OF
- .apply( value )
- .state()
- .propertyFor( persistentProperty.accessor() )
- .get();
-
- if( propertyValue != null )
+ ( (ValueCompositeType) valueType ).properties().forEach(
+ persistentProperty ->
{
- ValueType type = persistentProperty.valueType();
- if( type instanceof ValueCompositeType )
- {
- URI pred = valueFactory.createURI( baseUri, persistentProperty.qualifiedName().name() );
- serializeValueComposite( collection, pred, (ValueComposite) propertyValue, type, graph,
- baseUri + persistentProperty.qualifiedName().name() + "/",
- includeNonQueryable );
- }
- else
+ Object propertyValue
+ = PolygeneAPI.FUNCTION_COMPOSITE_INSTANCE_OF
+ .apply( value )
+ .state()
+ .propertyFor( persistentProperty.accessor() )
+ .get();
+
+ if( propertyValue != null )
{
- serializeProperty( persistentProperty, propertyValue, collection, graph, includeNonQueryable );
+ ValueType type = persistentProperty
+ .valueType();
+ if( type instanceof ValueCompositeType )
+ {
+ URI pred = valueFactory.createURI( baseUri,
+ persistentProperty
+ .qualifiedName()
+ .name() );
+ serializeValueComposite( collection, pred,
+ (ValueComposite) propertyValue,
+ type, graph,
+ baseUri
+ + persistentProperty
+ .qualifiedName()
+ .name() + "/",
+ includeNonQueryable );
+ }
+ else
+ {
+ serializeProperty( persistentProperty,
+ propertyValue,
+ collection, graph,
+ includeNonQueryable );
+ }
}
- }
- } );
+ } );
}
private void serializeAssociations( final EntityState entityState,
@@ -204,15 +213,30 @@ public class EntityStateSerializer
ValueFactory values = graph.getValueFactory();
// Associations
- associations.filter( type -> includeNonQueryable || type.queryable() ).forEach( associationType -> {
- EntityReference associatedId = entityState.associationValueOf( associationType.qualifiedName() );
- if( associatedId != null )
+ associations.filter( type -> includeNonQueryable || type.queryable() ).forEach(
+ associationType ->
{
- URI assocURI = values.createURI( associationType.qualifiedName().toURI() );
- URI assocEntityURI = values.createURI( associatedId.toURI() );
- graph.add( entityUri, assocURI, assocEntityURI );
- }
- } );
+ EntityReference associatedId
+ = entityState
+ .associationValueOf(
+ associationType
+ .qualifiedName() );
+ if( associatedId != null )
+ {
+ URI assocURI = values
+ .createURI(
+ associationType
+ .qualifiedName()
+ .toURI() );
+ URI assocEntityURI
+ = values.createURI(
+ associatedId
+ .toURI() );
+ graph.add( entityUri,
+ assocURI,
+ assocEntityURI );
+ }
+ } );
}
private void serializeManyAssociations( final EntityState entityState,
@@ -225,17 +249,37 @@ public class EntityStateSerializer
ValueFactory values = graph.getValueFactory();
// Many-Associations
- associations.filter( type -> includeNonQueryable || type.queryable() ).forEach( associationType -> {
- BNode collection = values.createBNode();
- graph.add( entityUri, values.createURI( associationType.qualifiedName().toURI() ), collection );
- graph.add( collection, Rdfs.TYPE, Rdfs.SEQ );
-
- ManyAssociationState associatedIds = entityState.manyAssociationValueOf( associationType.qualifiedName() );
- for( EntityReference associatedId : associatedIds )
+ associations.filter( type -> includeNonQueryable || type.queryable() ).forEach(
+ associationType ->
{
- URI assocEntityURI = values.createURI( associatedId.toURI() );
- graph.add( collection, Rdfs.LIST_ITEM, assocEntityURI );
- }
- } );
+ BNode collection = values
+ .createBNode();
+ graph.add( entityUri, values
+ .createURI(
+ associationType
+ .qualifiedName()
+ .toURI() ),
+ collection );
+ graph.add( collection,
+ Rdfs.TYPE,
+ Rdfs.SEQ );
+
+ ManyAssociationState
+ associatedIds
+ = entityState
+ .manyAssociationValueOf(
+ associationType
+ .qualifiedName() );
+ for( EntityReference associatedId : associatedIds )
+ {
+ URI assocEntityURI
+ = values.createURI(
+ associatedId
+ .toURI() );
+ graph.add( collection,
+ Rdfs.LIST_ITEM,
+ assocEntityURI );
+ }
+ } );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rdf/src/test/java/org/apache/polygene/library/rdf/entity/EntitySerializerTest.java
----------------------------------------------------------------------
diff --git a/libraries/rdf/src/test/java/org/apache/polygene/library/rdf/entity/EntitySerializerTest.java b/libraries/rdf/src/test/java/org/apache/polygene/library/rdf/entity/EntitySerializerTest.java
index 0ef8475..fb5b0c3 100644
--- a/libraries/rdf/src/test/java/org/apache/polygene/library/rdf/entity/EntitySerializerTest.java
+++ b/libraries/rdf/src/test/java/org/apache/polygene/library/rdf/entity/EntitySerializerTest.java
@@ -22,17 +22,12 @@ package org.apache.polygene.library.rdf.entity;
import java.io.PrintWriter;
import java.time.Instant;
-import org.apache.polygene.api.identity.StringIdentity;
-import org.apache.polygene.api.time.SystemTime;
-import org.apache.polygene.test.AbstractPolygeneTest;
-import org.junit.Before;
-import org.junit.Test;
-import org.openrdf.model.Statement;
-import org.openrdf.rio.RDFHandlerException;
import org.apache.polygene.api.entity.EntityBuilder;
import org.apache.polygene.api.entity.EntityReference;
+import org.apache.polygene.api.identity.StringIdentity;
import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.injection.scope.Uses;
+import org.apache.polygene.api.time.SystemTime;
import org.apache.polygene.api.unitofwork.UnitOfWork;
import org.apache.polygene.api.unitofwork.UnitOfWorkCompletionException;
import org.apache.polygene.api.usecase.Usecase;
@@ -46,8 +41,12 @@ import org.apache.polygene.library.rdf.serializer.RdfXmlSerializer;
import org.apache.polygene.spi.entity.EntityState;
import org.apache.polygene.spi.entitystore.EntityStore;
import org.apache.polygene.spi.entitystore.EntityStoreUnitOfWork;
+import org.apache.polygene.test.AbstractPolygeneTest;
import org.apache.polygene.test.EntityTestAssembler;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
+import org.junit.Before;
+import org.junit.Test;
+import org.openrdf.model.Statement;
+import org.openrdf.rio.RDFHandlerException;
/**
* JAVADOC
@@ -64,7 +63,6 @@ public class EntitySerializerTest
throws AssemblyException
{
new EntityTestAssembler().assemble( module );
- new OrgJsonValueSerializationAssembler().assemble( module );
module.entities( TestEntity.class );
module.values( TestValue.class, Test2Value.class );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-client/build.gradle
----------------------------------------------------------------------
diff --git a/libraries/rest-client/build.gradle b/libraries/rest-client/build.gradle
index da6455c..2270e41 100644
--- a/libraries/rest-client/build.gradle
+++ b/libraries/rest-client/build.gradle
@@ -33,7 +33,6 @@ dependencies {
testImplementation polygene.core.testsupport
testImplementation polygene.library( 'rest-server' )
- testImplementation polygene.extension( 'valueserialization-orgjson' )
testRuntimeOnly libraries.logback
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/requestwriter/ValueCompositeRequestWriter.java
----------------------------------------------------------------------
diff --git a/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/requestwriter/ValueCompositeRequestWriter.java b/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/requestwriter/ValueCompositeRequestWriter.java
index 90ad77a..8a77d40 100644
--- a/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/requestwriter/ValueCompositeRequestWriter.java
+++ b/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/requestwriter/ValueCompositeRequestWriter.java
@@ -26,11 +26,11 @@ import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.injection.scope.Structure;
import org.apache.polygene.api.property.StateHolder;
import org.apache.polygene.api.service.qualifier.Tagged;
+import org.apache.polygene.api.serialization.Serialization;
+import org.apache.polygene.api.serialization.SerializationException;
+import org.apache.polygene.api.serialization.Serializer;
import org.apache.polygene.api.value.ValueComposite;
import org.apache.polygene.api.value.ValueDescriptor;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.api.value.ValueSerializationException;
-import org.apache.polygene.api.value.ValueSerializer;
import org.apache.polygene.library.rest.client.spi.RequestWriter;
import org.apache.polygene.spi.PolygeneSPI;
import org.restlet.Request;
@@ -38,7 +38,6 @@ import org.restlet.data.CharacterSet;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Reference;
-import org.restlet.engine.io.WriterOutputStream;
import org.restlet.representation.WriterRepresentation;
import org.restlet.resource.ResourceException;
@@ -52,8 +51,8 @@ public class ValueCompositeRequestWriter
private PolygeneSPI spi;
@Service
- @Tagged( ValueSerialization.Formats.JSON )
- private ValueSerializer valueSerializer;
+ @Tagged( Serialization.Formats.JSON )
+ private Serializer serializer;
@Override
public boolean writeRequest(Object requestObject, Request request) throws ResourceException
@@ -80,11 +79,11 @@ public class ValueCompositeRequestWriter
}
else
{
- param = valueSerializer.serialize( value );
+ param = serializer.serialize( value );
}
ref.addQueryParameter( propertyDescriptor.qualifiedName().name(), param );
}
- catch( ValueSerializationException e )
+ catch( SerializationException e )
{
throw new ResourceException( e );
}
@@ -99,7 +98,7 @@ public class ValueCompositeRequestWriter
throws IOException
{
setCharacterSet( CharacterSet.UTF_8 );
- valueSerializer.serialize( valueObject, new WriterOutputStream( writer, CharacterSet.UTF_8 ) );
+ serializer.serialize( writer, valueObject );
}
});
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/responsereader/DefaultResponseReader.java
----------------------------------------------------------------------
diff --git a/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/responsereader/DefaultResponseReader.java b/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/responsereader/DefaultResponseReader.java
index 6d3111b..ff8060b 100644
--- a/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/responsereader/DefaultResponseReader.java
+++ b/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/responsereader/DefaultResponseReader.java
@@ -20,10 +20,11 @@
package org.apache.polygene.library.rest.client.responsereader;
-import java.io.IOException;
-import org.json.JSONException;
-import org.json.JSONTokener;
+import org.apache.polygene.api.injection.scope.Service;
+import org.apache.polygene.api.injection.scope.Structure;
+import org.apache.polygene.api.structure.ModuleDescriptor;
import org.apache.polygene.library.rest.client.spi.ResponseReader;
+import org.apache.polygene.spi.serialization.JsonDeserializer;
import org.restlet.Response;
import org.restlet.data.MediaType;
import org.restlet.resource.ResourceException;
@@ -32,34 +33,31 @@ import org.restlet.resource.ResourceException;
* ResponseReader for simple types from JSON
*/
public class DefaultResponseReader
- implements ResponseReader
+ implements ResponseReader
{
+ @Structure
+ private ModuleDescriptor module;
+
+ @Service
+ private JsonDeserializer jsonDeserializer;
+
@Override
- public Object readResponse(Response response, Class<?> resultType) throws ResourceException
- {
- if (MediaType.APPLICATION_JSON.equals(response.getEntity().getMediaType()))
- if (resultType.equals(String.class))
- {
- try
+ public Object readResponse( Response response, Class<?> resultType ) throws ResourceException
+ {
+ if( MediaType.APPLICATION_JSON.equals( response.getEntity().getMediaType() ) )
+ {
+ if( resultType.equals( String.class ) || Number.class.isAssignableFrom( resultType ) )
{
- return response.getEntity().getText();
- } catch (IOException e)
- {
- throw new ResourceException(e);
+ try
+ {
+ return jsonDeserializer.deserialize( module, resultType, response.getEntityAsText() );
+ }
+ catch( Exception e )
+ {
+ throw new ResourceException( e );
+ }
}
- } else if (Number.class.isAssignableFrom(resultType))
- {
- try
- {
- Number value = (Number) new JSONTokener(response.getEntityAsText()).nextValue();
- if (resultType.equals(Integer.class))
- return Integer.valueOf(value.intValue());
- } catch (JSONException e)
- {
- throw new ResourceException(e);
- }
- }
-
- return null;
- }
+ }
+ return null;
+ }
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/responsereader/JSONResponseReader.java
----------------------------------------------------------------------
diff --git a/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/responsereader/JSONResponseReader.java b/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/responsereader/JSONResponseReader.java
index 7b8d6a0..335c26b 100644
--- a/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/responsereader/JSONResponseReader.java
+++ b/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/responsereader/JSONResponseReader.java
@@ -20,18 +20,19 @@
package org.apache.polygene.library.rest.client.responsereader;
-import java.util.Iterator;
+import java.io.IOException;
+import javax.json.Json;
+import javax.json.JsonException;
+import javax.json.JsonObject;
+import javax.json.JsonString;
+import javax.json.JsonValue;
import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.injection.scope.Structure;
-import org.apache.polygene.api.service.qualifier.Tagged;
import org.apache.polygene.api.structure.ModuleDescriptor;
import org.apache.polygene.api.type.ValueCompositeType;
import org.apache.polygene.api.value.ValueComposite;
-import org.apache.polygene.api.value.ValueDeserializer;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.library.rest.client.spi.ResponseReader;
-import org.json.JSONException;
-import org.json.JSONObject;
+import org.apache.polygene.spi.serialization.JsonDeserializer;
import org.restlet.Response;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
@@ -41,47 +42,50 @@ import org.restlet.resource.ResourceException;
* JAVADOC
*/
public class JSONResponseReader
- implements ResponseReader
+ implements ResponseReader
{
- @Structure
- private ModuleDescriptor module;
+ @Structure
+ private ModuleDescriptor module;
- @Service
- @Tagged( ValueSerialization.Formats.JSON )
- private ValueDeserializer valueDeserializer;
+ @Service
+ private JsonDeserializer jsonDeserializer;
@Override
- public Object readResponse( Response response, Class<?> resultType )
- {
- if (response.getEntity().getMediaType().equals( MediaType.APPLICATION_JSON))
- {
- if (ValueComposite.class.isAssignableFrom( resultType ))
- {
- String jsonValue = response.getEntityAsText();
- ValueCompositeType valueType = module.valueDescriptor( resultType.getName() ).valueType();
- return valueDeserializer.deserialize( module, valueType, jsonValue );
- }
- else if (resultType.equals(Form.class))
- {
- try
+ public Object readResponse( Response response, Class<?> resultType )
+ {
+ if( response.getEntity().getMediaType().equals( MediaType.APPLICATION_JSON ) )
+ {
+ if( ValueComposite.class.isAssignableFrom( resultType ) )
{
- String jsonValue = response.getEntityAsText();
- JSONObject jsonObject = new JSONObject(jsonValue);
- Iterator<?> keys = jsonObject.keys();
- Form form = new Form();
- while (keys.hasNext())
- {
- Object key = keys.next();
- form.set(key.toString(), jsonObject.get(key.toString()).toString());
- }
- return form;
- } catch (JSONException e)
- {
- throw new ResourceException(e);
+ String jsonValue = response.getEntityAsText();
+ ValueCompositeType valueType = module.valueDescriptor( resultType.getName() ).valueType();
+ return jsonDeserializer.deserialize( module, valueType, jsonValue );
}
- }
- }
+ else if( resultType.equals( Form.class ) )
+ {
+ try
+ {
+ JsonObject jsonObject = Json.createReader( response.getEntity().getReader() ).readObject();
+ Form form = new Form();
+ jsonObject.entrySet().forEach(
+ entry ->
+ {
- return null;
- }
+ String key = entry.getKey();
+ JsonValue value = entry.getValue();
+ String valueString = value.getValueType() == JsonValue.ValueType.STRING
+ ? ( (JsonString) value ).getString()
+ : value.toString();
+ form.set( key, valueString );
+ } );
+ return form;
+ }
+ catch( IOException | JsonException e )
+ {
+ throw new ResourceException( e );
+ }
+ }
+ }
+ return null;
+ }
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/responsereader/TableResponseReader.java
----------------------------------------------------------------------
diff --git a/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/responsereader/TableResponseReader.java b/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/responsereader/TableResponseReader.java
index 4c8ac66..55019a3 100644
--- a/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/responsereader/TableResponseReader.java
+++ b/libraries/rest-client/src/main/java/org/apache/polygene/library/rest/client/responsereader/TableResponseReader.java
@@ -22,15 +22,19 @@ package org.apache.polygene.library.rest.client.responsereader;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
-import java.time.format.DateTimeParseException;
+import java.util.List;
+import javax.json.Json;
+import javax.json.JsonArray;
+import javax.json.JsonObject;
+import javax.json.JsonString;
+import javax.json.JsonValue;
+import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.injection.scope.Structure;
import org.apache.polygene.api.structure.Module;
import org.apache.polygene.library.rest.client.spi.ResponseReader;
import org.apache.polygene.library.rest.common.table.Table;
import org.apache.polygene.library.rest.common.table.TableBuilder;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
+import org.apache.polygene.spi.serialization.JsonDeserializer;
import org.restlet.Response;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
@@ -40,74 +44,75 @@ import org.restlet.resource.ResourceException;
* JAVADOC
*/
public class TableResponseReader
- implements ResponseReader
+ implements ResponseReader
{
- @Structure
- Module module;
+ @Structure
+ private Module module;
- @Override
- public Object readResponse( Response response, Class<?> resultType ) throws ResourceException
- {
- if (response.getEntity().getMediaType().equals( MediaType.APPLICATION_JSON) && Table.class.isAssignableFrom( resultType ))
- {
- String jsonValue = response.getEntityAsText();
- try
- {
- JSONObject jsonObject = new JSONObject(jsonValue);
-
- JSONObject table = jsonObject.getJSONObject( "table" );
- TableBuilder builder = new TableBuilder(module);
+ @Service
+ private JsonDeserializer jsonDeserializer;
- JSONArray cols = table.getJSONArray( "cols" );
- for (int i = 0; i < cols.length(); i++)
+ @Override
+ public Object readResponse( Response response, Class<?> resultType ) throws ResourceException
+ {
+ if( response.getEntity().getMediaType().equals( MediaType.APPLICATION_JSON )
+ && Table.class.isAssignableFrom( resultType ) )
+ {
+ try
{
- JSONObject col = cols.getJSONObject( i );
- builder.column( col.optString( "id" ), col.getString( "label" ), col.getString( "type" ));
- }
+ JsonObject jsonObject = Json.createReader( response.getEntity().getReader() ).readObject();
+ JsonObject table = jsonObject.getJsonObject( "table" );
- JSONArray rows = table.getJSONArray( "rows" );
- for (int i = 0; i < rows.length(); i++)
- {
- builder.row();
- JSONObject row = rows.getJSONObject( i );
- JSONArray cells = row.getJSONArray( "c" );
- for (int j = 0; j < cells.length(); j++)
- {
- JSONObject cell = cells.getJSONObject( j );
- Object value = cell.opt( "v" );
- String formatted = cell.optString("f");
+ TableBuilder builder = new TableBuilder( module );
- if (cols.getJSONObject( j ).getString( "type" ).equals("datetime") && value != null)
- value = ZonedDateTime.parse( value.toString() );
- else if (cols.getJSONObject( j ).getString( "type" ).equals("date") && value != null)
- try
- {
- value = DateTimeFormatter.ofPattern( "yyyy-MM-dd").parse( value.toString() );
- } catch (DateTimeParseException e)
- {
- throw new ResourceException(e);
- }
- else if (cols.getJSONObject( j ).getString( "type" ).equals("timeofday") && value != null)
- try
- {
- value = DateTimeFormatter.ofPattern( "HH:mm:ss").parse( value.toString() );
- } catch (DateTimeParseException e)
- {
- throw new ResourceException(e);
- }
+ JsonArray cols = table.getJsonArray( "cols" );
+ cols.getValuesAs( JsonObject.class ).forEach(
+ col -> builder.column( col.getString( "id", null ),
+ col.getString( "label" ),
+ col.getString( "type" ) ) );
- builder.cell( value, formatted );
- }
- builder.endRow();
+ table.getJsonArray( "rows" ).getValuesAs( JsonObject.class ).forEach(
+ row ->
+ {
+ builder.row();
+ List<JsonObject> cells = row.getJsonArray( "c" ).getValuesAs( JsonObject.class );
+ for( int idx = 0; idx < cells.size(); idx++ )
+ {
+ JsonObject cell = cells.get( idx );
+ JsonValue jsonValue = cell.get( "v" );
+ String formatted = cell.getString( "f", null );
+ String type = cols.getJsonObject( idx ).getString( "type" );
+ Object value;
+ switch( type )
+ {
+ case "datetime":
+ value = ZonedDateTime.parse( ( (JsonString) jsonValue ).getString() );
+ break;
+ case "date":
+ value = DateTimeFormatter.ofPattern( "yyyy-MM-dd" )
+ .parse( ( (JsonString) jsonValue ).getString() );
+ break;
+ case "timeofday":
+ value = DateTimeFormatter.ofPattern( "HH:mm:ss" )
+ .parse( ( (JsonString) jsonValue ).getString() );
+ break;
+ default:
+ value = jsonValue.getValueType() == JsonValue.ValueType.STRING
+ ? ( (JsonString) jsonValue ).getString()
+ : jsonValue.toString();
+ }
+ builder.cell( value, formatted );
+ }
+ builder.endRow();
+ }
+ );
+ return builder.newTable();
}
-
- return builder.newTable();
- } catch (JSONException e)
- {
- throw new ResourceException( Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY, e);
- }
- }
-
- return null;
- }
+ catch( Exception e )
+ {
+ throw new ResourceException( Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY, e );
+ }
+ }
+ return null;
+ }
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-client/src/test/java/org/apache/polygene/library/rest/client/ContextResourceClientFactoryTest.java
----------------------------------------------------------------------
diff --git a/libraries/rest-client/src/test/java/org/apache/polygene/library/rest/client/ContextResourceClientFactoryTest.java b/libraries/rest-client/src/test/java/org/apache/polygene/library/rest/client/ContextResourceClientFactoryTest.java
index 771cbd6..e979d43 100644
--- a/libraries/rest-client/src/test/java/org/apache/polygene/library/rest/client/ContextResourceClientFactoryTest.java
+++ b/libraries/rest-client/src/test/java/org/apache/polygene/library/rest/client/ContextResourceClientFactoryTest.java
@@ -26,14 +26,12 @@ import org.apache.polygene.api.common.Optional;
import org.apache.polygene.api.common.UseDefaults;
import org.apache.polygene.api.composite.TransientComposite;
import org.apache.polygene.api.constraint.Name;
-import org.apache.polygene.api.entity.EntityComposite;
import org.apache.polygene.api.injection.scope.Structure;
import org.apache.polygene.api.injection.scope.Uses;
import org.apache.polygene.api.property.Property;
import org.apache.polygene.api.structure.Application;
import org.apache.polygene.api.structure.ApplicationDescriptor;
import org.apache.polygene.api.structure.Module;
-import org.apache.polygene.api.type.HasTypes;
import org.apache.polygene.api.unitofwork.ConcurrentEntityModificationException;
import org.apache.polygene.api.unitofwork.UnitOfWorkCallback;
import org.apache.polygene.api.unitofwork.UnitOfWorkCompletionException;
@@ -72,7 +70,6 @@ import org.apache.polygene.library.rest.server.restlet.NullCommandResult;
import org.apache.polygene.library.rest.server.spi.CommandResult;
import org.apache.polygene.test.AbstractPolygeneTest;
import org.apache.polygene.test.util.FreePortFinder;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.hamcrest.CoreMatchers;
import org.junit.After;
import org.junit.Assert;
@@ -112,7 +109,6 @@ public class ContextResourceClientFactoryTest
throws AssemblyException
{
// General setup of client and server
- new OrgJsonValueSerializationAssembler().assemble( module );
new ClientAssembler().assemble( module );
new ValueAssembler().assemble( module );
new RestServerAssembler().assemble( module );
@@ -568,12 +564,12 @@ public class ContextResourceClientFactoryTest
public TestResult queryWithValue( TestQuery query )
{
- return vbf.newValueFromSerializedState( TestResult.class, "{'xyz':'"+query.abc().get()+"'}" );
+ return vbf.newValueFromSerializedState( TestResult.class, "{\"xyz\":\""+query.abc().get()+"\"}" );
}
public TestResult queryWithoutValue()
{
- return vbf.newValueFromSerializedState( TestResult.class, "{'xyz':'bar'}" );
+ return vbf.newValueFromSerializedState( TestResult.class, "{\"xyz\":\"bar\"}" );
}
public String queryWithStringResult( TestQuery query )
@@ -609,7 +605,7 @@ public class ContextResourceClientFactoryTest
public void beforeCompletion()
throws UnitOfWorkCompletionException
{
- throw new ConcurrentEntityModificationException( Collections.<EntityComposite, HasTypes>emptyMap(),
+ throw new ConcurrentEntityModificationException( Collections.emptyMap(),
UsecaseBuilder.newUsecase( "Testing" ) );
}
@@ -642,7 +638,7 @@ public class ContextResourceClientFactoryTest
public TestResult queryWithValue( TestQuery query )
{
- return module.newValueFromSerializedState( TestResult.class, "{'xyz':'bar'}" );
+ return module.newValueFromSerializedState( TestResult.class, "{\"xyz\":\"bar\"}" );
}
// Test interaction constraints
@@ -650,7 +646,7 @@ public class ContextResourceClientFactoryTest
@Requires( File.class )
public TestResult queryWithRoleRequirement( TestQuery query )
{
- return module.newValueFromSerializedState( TestResult.class, "{'xyz':'bar'}" );
+ return module.newValueFromSerializedState( TestResult.class, "{\"xyz\":\"bar\"}" );
}
@Requires( File.class )
@@ -697,7 +693,7 @@ public class ContextResourceClientFactoryTest
public TestResult genericQuery( TestQuery query )
{
- return module.newValueFromSerializedState( TestResult.class, "{'xyz':'bar'}" );
+ return module.newValueFromSerializedState( TestResult.class, "{\"xyz\":\"bar\"}" );
}
}
[24/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/SQLiteEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/SQLiteEntityStoreTest.java b/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/SQLiteEntityStoreTest.java
index aac68f8..24dd298 100644
--- a/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/SQLiteEntityStoreTest.java
+++ b/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/SQLiteEntityStoreTest.java
@@ -19,9 +19,6 @@
*/
package org.apache.polygene.entitystore.sql;
-import java.io.File;
-import org.apache.derby.iapi.services.io.FileUtil;
-import org.junit.BeforeClass;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
@@ -30,7 +27,7 @@ import org.apache.polygene.library.sql.assembly.DataSourceAssembler;
import org.apache.polygene.library.sql.dbcp.DBCPDataSourceServiceAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
+import org.junit.BeforeClass;
import static org.apache.polygene.test.util.Assume.assumeNoIbmJdk;
@@ -52,44 +49,28 @@ public class SQLiteEntityStoreTest
super.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
// START SNIPPET: assembly
// DataSourceService
- new DBCPDataSourceServiceAssembler().
- identifiedBy( "sqlite-datasource-service" ).
- visibleIn( Visibility.module ).
- withConfig( config, Visibility.layer ).
- assemble( module );
+ new DBCPDataSourceServiceAssembler()
+ .identifiedBy( "sqlite-datasource-service" )
+ .visibleIn( Visibility.module )
+ .withConfig( config, Visibility.layer )
+ .assemble( module );
// DataSource
- new DataSourceAssembler().
- withDataSourceServiceIdentity( "sqlite-datasource-service" ).
- identifiedBy( "sqlite-datasource" ).
- visibleIn( Visibility.module ).
- withCircuitBreaker().
- assemble( module );
+ new DataSourceAssembler()
+ .withDataSourceServiceIdentity( "sqlite-datasource-service" )
+ .identifiedBy( "sqlite-datasource" )
+ .visibleIn( Visibility.module )
+ .withCircuitBreaker()
+ .assemble( module );
// SQL EntityStore
- new SQLiteEntityStoreAssembler().
- visibleIn( Visibility.application ).
- withConfig( config, Visibility.layer ).
- assemble( module );
+ new SQLiteEntityStoreAssembler()
+ .visibleIn( Visibility.application )
+ .withConfig( config, Visibility.layer )
+ .assemble( module );
}
// END SNIPPET: assembly
-
- @Override
- public void tearDown()
- throws Exception
- {
- try
- {
- FileUtil.removeDirectory( new File( "target/polygene-data" ) );
- }
- finally
- {
- super.tearDown();
- }
- }
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-elasticsearch/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/indexing-elasticsearch/build.gradle b/extensions/indexing-elasticsearch/build.gradle
index faa63b8..fac6eec 100644
--- a/extensions/indexing-elasticsearch/build.gradle
+++ b/extensions/indexing-elasticsearch/build.gradle
@@ -34,7 +34,6 @@ dependencies {
runtimeOnly polygene.core.runtime
testImplementation polygene.core.testsupport
- testImplementation polygene.extension( 'valueserialization-jackson' )
testRuntimeOnly libraries.logback
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/ElasticSearchIndexer.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/ElasticSearchIndexer.java b/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/ElasticSearchIndexer.java
index 80172cc..ad023bd 100644
--- a/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/ElasticSearchIndexer.java
+++ b/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/ElasticSearchIndexer.java
@@ -19,10 +19,13 @@
*/
package org.apache.polygene.index.elasticsearch;
-import java.util.Collections;
+import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
-import java.util.stream.Collectors;
+import javax.json.Json;
+import javax.json.JsonArrayBuilder;
+import javax.json.JsonObjectBuilder;
+import javax.json.JsonValue;
import org.apache.polygene.api.entity.EntityDescriptor;
import org.apache.polygene.api.entity.EntityReference;
import org.apache.polygene.api.identity.Identity;
@@ -30,15 +33,12 @@ import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.injection.scope.Structure;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
-import org.apache.polygene.api.service.qualifier.Tagged;
+import org.apache.polygene.api.serialization.Serializer;
import org.apache.polygene.api.structure.ModuleDescriptor;
import org.apache.polygene.api.time.SystemTime;
-import org.apache.polygene.api.type.ValueType;
import org.apache.polygene.api.usecase.UsecaseBuilder;
import org.apache.polygene.api.util.Classes;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.api.value.ValueSerializer;
-import org.apache.polygene.api.value.ValueSerializer.Options;
+import org.apache.polygene.serialization.javaxjson.JavaxJson;
import org.apache.polygene.spi.entity.EntityState;
import org.apache.polygene.spi.entity.EntityStatus;
import org.apache.polygene.spi.entity.ManyAssociationState;
@@ -46,11 +46,9 @@ import org.apache.polygene.spi.entity.NamedAssociationState;
import org.apache.polygene.spi.entitystore.EntityStore;
import org.apache.polygene.spi.entitystore.EntityStoreUnitOfWork;
import org.apache.polygene.spi.entitystore.StateChangeListener;
+import org.apache.polygene.spi.serialization.JsonSerializer;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -60,14 +58,11 @@ import org.slf4j.LoggerFactory;
* QUID Use two indices, one for strict queries, one for full text and fuzzy search?
*/
@Mixins( ElasticSearchIndexer.Mixin.class )
-public interface ElasticSearchIndexer
- extends StateChangeListener
+public interface ElasticSearchIndexer extends StateChangeListener
{
-
class Mixin
implements StateChangeListener
{
-
private static final Logger LOGGER = LoggerFactory.getLogger( ElasticSearchIndexer.class );
@Structure
@@ -77,8 +72,7 @@ public interface ElasticSearchIndexer
private EntityStore entityStore;
@Service
- @Tagged( ValueSerialization.Formats.JSON )
- private ValueSerializer valueSerializer;
+ private JsonSerializer jsonSerializer;
@This
private ElasticSearchSupport support;
@@ -102,9 +96,9 @@ public interface ElasticSearchIndexer
}
EntityStoreUnitOfWork uow = entityStore.newUnitOfWork(
- module,
- UsecaseBuilder.newUsecase( "Load associations for indexing" ),
- SystemTime.now()
+ module,
+ UsecaseBuilder.newUsecase( "Load associations for indexing" ),
+ SystemTime.now()
);
// Bulk index request builder
@@ -117,27 +111,27 @@ public interface ElasticSearchIndexer
{
switch( changedState.status() )
{
- case REMOVED:
- LOGGER.trace( "Removing Entity State from Index: {}", changedState );
- remove( bulkBuilder, changedState.entityReference().identity().toString() );
- break;
- case UPDATED:
- LOGGER.trace( "Updating Entity State in Index: {}", changedState );
- remove( bulkBuilder, changedState.entityReference().identity().toString() );
- String updatedJson = toJSON( changedState, newStates, uow );
- LOGGER.trace( "Will index: {}", updatedJson );
- index( bulkBuilder, changedState.entityReference().identity().toString(), updatedJson );
- break;
- case NEW:
- LOGGER.trace( "Creating Entity State in Index: {}", changedState );
- String newJson = toJSON( changedState, newStates, uow );
- LOGGER.trace( "Will index: {}", newJson );
- index( bulkBuilder, changedState.entityReference().identity().toString(), newJson );
- break;
- case LOADED:
- default:
- // Ignored
- break;
+ case REMOVED:
+ LOGGER.trace( "Removing Entity State from Index: {}", changedState );
+ remove( bulkBuilder, changedState.entityReference().identity().toString() );
+ break;
+ case UPDATED:
+ LOGGER.trace( "Updating Entity State in Index: {}", changedState );
+ remove( bulkBuilder, changedState.entityReference().identity().toString() );
+ String updatedJson = toJSON( changedState, newStates, uow );
+ LOGGER.trace( "Will index: {}", updatedJson );
+ index( bulkBuilder, changedState.entityReference().identity().toString(), updatedJson );
+ break;
+ case NEW:
+ LOGGER.trace( "Creating Entity State in Index: {}", changedState );
+ String newJson = toJSON( changedState, newStates, uow );
+ LOGGER.trace( "Will index: {}", newJson );
+ index( bulkBuilder, changedState.entityReference().identity().toString(), newJson );
+ break;
+ case LOADED:
+ default:
+ // Ignored
+ break;
}
}
}
@@ -173,7 +167,7 @@ public interface ElasticSearchIndexer
{
bulkBuilder.add( support.client().
prepareIndex( support.index(), support.entitiesType(), identity ).
- setSource( json ) );
+ setSource( json ) );
}
/**
@@ -190,72 +184,40 @@ public interface ElasticSearchIndexer
*/
private String toJSON( EntityState state, Map<String, EntityState> newStates, EntityStoreUnitOfWork uow )
{
- JSONObject json = new JSONObject();
+ JsonObjectBuilder builder = Json.createObjectBuilder();
- try
- {
- json.put( "_identity", state.entityReference().identity().toString() );
- json.put( "_types", state.entityDescriptor()
- .mixinTypes()
- .map( Classes.toClassName() )
- .collect( Collectors.toList() ) );
- }
- catch( JSONException e )
- {
- throw new ElasticSearchIndexException( "Could not index EntityState", e );
- }
+ builder.add( "_identity", state.entityReference().identity().toString() );
+
+ JsonArrayBuilder typesBuilder = Json.createArrayBuilder();
+ state.entityDescriptor().mixinTypes().map( Classes.toClassName() ).forEach( typesBuilder::add );
+ builder.add( "_types", typesBuilder.build() );
EntityDescriptor entityType = state.entityDescriptor();
// Properties
- entityType.state().properties().forEach( propDesc -> {
- try
+ entityType.state().properties().forEach(
+ propDesc ->
{
if( propDesc.queryable() )
{
String key = propDesc.qualifiedName().name();
Object value = state.propertyValueOf( propDesc.qualifiedName() );
- if( value == null || ValueType.isPrimitiveValue( value ) )
- {
- json.put( key, value );
- }
- else
- {
- String serialized = valueSerializer.serialize( new Options().withoutTypeInfo(), value );
- // TODO Theses tests are pretty fragile, find a better way to fix this, Jackson API should behave better
- if( serialized.startsWith( "{" ) )
- {
- json.put( key, new JSONObject( serialized ) );
- }
- else if( serialized.startsWith( "[" ) )
- {
- json.put( key, new JSONArray( serialized ) );
- }
- else
- {
- json.put( key, serialized );
- }
- }
+ JsonValue jsonValue = jsonSerializer.toJson( Serializer.Options.NO_TYPE_INFO, value );
+ builder.add( key, jsonValue );
}
- }
- catch( JSONException e )
- {
- throw new ElasticSearchIndexException( "Could not index EntityState", e );
- }
- } );
+ } );
// Associations
- entityType.state().associations().forEach( assocDesc -> {
- try
+ entityType.state().associations().forEach(
+ assocDesc ->
{
if( assocDesc.queryable() )
{
String key = assocDesc.qualifiedName().name();
EntityReference associated = state.associationValueOf( assocDesc.qualifiedName() );
- Object value;
if( associated == null )
{
- value = null;
+ builder.add( key, JsonValue.NULL );
}
else
{
@@ -263,114 +225,120 @@ public interface ElasticSearchIndexer
{
if( newStates.containsKey( associated.identity().toString() ) )
{
- value = new JSONObject( toJSON( newStates.get( associated.identity().toString() ), newStates, uow ) );
+ builder.add( key,
+ Json.createReader( new StringReader(
+ toJSON( newStates.get( associated.identity().toString() ),
+ newStates, uow )
+ ) ).readObject() );
}
else
{
EntityReference reference = EntityReference.create( associated.identity() );
EntityState assocState = uow.entityStateOf( module, reference );
- value = new JSONObject( toJSON( assocState, newStates, uow ) );
+ builder.add( key,
+ Json.createReader( new StringReader(
+ toJSON( assocState, newStates, uow )
+ ) ).readObject() );
}
}
else
{
- value = new JSONObject( Collections.singletonMap( "reference", associated.identity().toString() ) );
+ builder.add( key, Json.createObjectBuilder()
+ .add( "reference", associated.identity().toString() ) );
}
}
- json.put( key, value );
}
- }
- catch( JSONException e )
- {
- throw new ElasticSearchIndexException( "Could not index EntityState", e );
- }
- } );
+ } );
// ManyAssociations
- entityType.state().manyAssociations().forEach( manyAssocDesc -> {
- try
+ entityType.state().manyAssociations().forEach(
+ manyAssocDesc ->
{
if( manyAssocDesc.queryable() )
{
String key = manyAssocDesc.qualifiedName().name();
- JSONArray array = new JSONArray();
- ManyAssociationState associateds = state.manyAssociationValueOf( manyAssocDesc.qualifiedName() );
- for( EntityReference associated : associateds )
+ JsonArrayBuilder assBuilder = Json.createArrayBuilder();
+ ManyAssociationState assocs = state.manyAssociationValueOf( manyAssocDesc.qualifiedName() );
+ for( EntityReference associated : assocs )
{
if( manyAssocDesc.isAggregated() || support.indexNonAggregatedAssociations() )
{
if( newStates.containsKey( associated.identity().toString() ) )
{
- array.put( new JSONObject( toJSON( newStates.get( associated.identity().toString() ), newStates, uow ) ) );
+ assBuilder.add(
+ Json.createReader( new StringReader(
+ toJSON( newStates.get( associated.identity().toString() ), newStates, uow )
+ ) ).readObject() );
}
else
{
EntityReference reference = EntityReference.create( associated.identity() );
EntityState assocState = uow.entityStateOf( module, reference );
- array.put( new JSONObject( toJSON( assocState, newStates, uow ) ) );
+ assBuilder.add(
+ Json.createReader( new StringReader(
+ toJSON( assocState, newStates, uow )
+ ) ).readObject() );
}
}
else
{
- array.put( new JSONObject( Collections.singletonMap( "reference", associated.identity().toString() ) ) );
+ assBuilder.add( Json.createObjectBuilder().add( "reference",
+ associated.identity().toString() ) );
}
}
- json.put( key, array );
+ builder.add( key, assBuilder.build() );
}
- }
- catch( JSONException e )
- {
- throw new ElasticSearchIndexException( "Could not index EntityState", e );
- }
- } );
+ } );
// NamedAssociations
- entityType.state().namedAssociations().forEach( namedAssocDesc -> {
- try
+ entityType.state().namedAssociations().forEach(
+ namedAssocDesc ->
{
if( namedAssocDesc.queryable() )
{
String key = namedAssocDesc.qualifiedName().name();
- JSONArray array = new JSONArray();
- NamedAssociationState associateds = state.namedAssociationValueOf( namedAssocDesc.qualifiedName() );
- for( String name : associateds )
+ JsonArrayBuilder assBuilder = Json.createArrayBuilder();
+ NamedAssociationState assocs = state.namedAssociationValueOf(
+ namedAssocDesc.qualifiedName() );
+ for( String name : assocs )
{
- Identity identity = associateds.get(name).identity();
+ Identity identity = assocs.get( name ).identity();
if( namedAssocDesc.isAggregated() || support.indexNonAggregatedAssociations() )
{
String identityString = identity.toString();
if( newStates.containsKey( identityString ) )
{
- JSONObject obj = new JSONObject( toJSON( newStates.get( identityString ), newStates, uow ) );
- obj.put( "_named", name );
- array.put( obj );
+ assBuilder.add(
+ JavaxJson.toBuilder(
+ Json.createReader( new StringReader(
+ toJSON( newStates.get( identityString ), newStates, uow ) )
+ ).readObject()
+ ).add( "_named", name ).build() );
}
else
{
EntityReference reference = EntityReference.create( identity );
EntityState assocState = uow.entityStateOf( module, reference );
- JSONObject obj = new JSONObject( toJSON( assocState, newStates, uow ) );
- obj.put( "_named", name );
- array.put( obj );
+ assBuilder.add(
+ JavaxJson.toBuilder(
+ Json.createReader( new StringReader(
+ toJSON( assocState, newStates, uow )
+ ) ).readObject()
+ ).add( "_named", name ).build() );
}
}
else
{
- JSONObject obj = new JSONObject();
- obj.put( "_named", name );
- obj.put( "reference", identity.toString() );
- array.put( obj );
+ assBuilder.add( Json.createObjectBuilder()
+ .add( "_named", name )
+ .add( "reference", identity.toString() )
+ .build() );
}
}
- json.put( key, array );
+ builder.add( key, assBuilder.build() );
}
- }
- catch( JSONException e )
- {
- throw new ElasticSearchIndexException( "Could not index EntityState", e );
- }
- } );
- return json.toString();
+ } );
+ return builder.build().toString();
}
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESClientIndexQueryAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESClientIndexQueryAssembler.java b/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESClientIndexQueryAssembler.java
index 10b1762..c6a0bdc 100644
--- a/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESClientIndexQueryAssembler.java
+++ b/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESClientIndexQueryAssembler.java
@@ -17,13 +17,11 @@
*/
package org.apache.polygene.index.elasticsearch.assembly;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.index.elasticsearch.ElasticSearchConfiguration;
import org.apache.polygene.index.elasticsearch.client.ESClientIndexQueryService;
import org.apache.polygene.index.elasticsearch.internal.AbstractElasticSearchAssembler;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
import org.elasticsearch.client.Client;
public class ESClientIndexQueryAssembler
@@ -46,9 +44,6 @@ public class ESClientIndexQueryAssembler
.visibleIn( visibility() )
.instantiateOnStartup();
- module.services( OrgJsonValueSerializationService.class )
- .taggedWith( ValueSerialization.Formats.JSON );
-
if( hasConfig() )
{
configModule().entities( ElasticSearchConfiguration.class )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESClusterIndexQueryAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESClusterIndexQueryAssembler.java b/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESClusterIndexQueryAssembler.java
index 269a877..f2d803d 100644
--- a/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESClusterIndexQueryAssembler.java
+++ b/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESClusterIndexQueryAssembler.java
@@ -19,13 +19,11 @@
*/
package org.apache.polygene.index.elasticsearch.assembly;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.index.elasticsearch.ElasticSearchClusterConfiguration;
import org.apache.polygene.index.elasticsearch.cluster.ESClusterIndexQueryService;
import org.apache.polygene.index.elasticsearch.internal.AbstractElasticSearchAssembler;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
public class ESClusterIndexQueryAssembler
extends AbstractElasticSearchAssembler<ESClusterIndexQueryAssembler>
@@ -40,9 +38,6 @@ public class ESClusterIndexQueryAssembler
.visibleIn( visibility() )
.instantiateOnStartup();
- module.services( OrgJsonValueSerializationService.class ).
- taggedWith( ValueSerialization.Formats.JSON );
-
if( hasConfig() )
{
configModule().entities( ElasticSearchClusterConfiguration.class ).
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESFilesystemIndexQueryAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESFilesystemIndexQueryAssembler.java b/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESFilesystemIndexQueryAssembler.java
index 015e2b0..1998fd8 100644
--- a/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESFilesystemIndexQueryAssembler.java
+++ b/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESFilesystemIndexQueryAssembler.java
@@ -19,13 +19,11 @@
*/
package org.apache.polygene.index.elasticsearch.assembly;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.index.elasticsearch.ElasticSearchConfiguration;
import org.apache.polygene.index.elasticsearch.filesystem.ESFilesystemIndexQueryService;
import org.apache.polygene.index.elasticsearch.internal.AbstractElasticSearchAssembler;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
public class ESFilesystemIndexQueryAssembler
extends AbstractElasticSearchAssembler<ESFilesystemIndexQueryAssembler>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-elasticsearch/src/test/java/org/apache/polygene/index/elasticsearch/ElasticSearchQueryTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-elasticsearch/src/test/java/org/apache/polygene/index/elasticsearch/ElasticSearchQueryTest.java b/extensions/indexing-elasticsearch/src/test/java/org/apache/polygene/index/elasticsearch/ElasticSearchQueryTest.java
index ecd35fb..6b6feab 100644
--- a/extensions/indexing-elasticsearch/src/test/java/org/apache/polygene/index/elasticsearch/ElasticSearchQueryTest.java
+++ b/extensions/indexing-elasticsearch/src/test/java/org/apache/polygene/index/elasticsearch/ElasticSearchQueryTest.java
@@ -30,7 +30,6 @@ import org.apache.polygene.library.fileconfig.FileConfigurationOverride;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.indexing.AbstractQueryTest;
import org.apache.polygene.test.util.NotYetImplemented;
-import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
@@ -79,9 +78,6 @@ public class ElasticSearchQueryTest extends AbstractQueryTest
testName.getMethodName() ) );
esConfig.indexNonAggregatedAssociations().set( Boolean.TRUE );
- // Serialization
- new JacksonValueSerializationAssembler().assemble( module );
-
// FileConfig
new FileConfigurationAssembler()
.withOverride( new FileConfigurationOverride().withConventionalRoot( tmpDir.getRoot() ) )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-rdf/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/build.gradle b/extensions/indexing-rdf/build.gradle
index ad465a4..73ebf31 100644
--- a/extensions/indexing-rdf/build.gradle
+++ b/extensions/indexing-rdf/build.gradle
@@ -33,7 +33,6 @@ dependencies {
runtimeOnly polygene.core.runtime
testImplementation polygene.core.testsupport
- testImplementation polygene.extension( 'valueserialization-jackson' )
testImplementation polygene.extension( 'entitystore-preferences' )
testImplementation polygene.extension( 'entitystore-jdbm' )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/query/RdfQueryParserFactory.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/query/RdfQueryParserFactory.java b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/query/RdfQueryParserFactory.java
index fa2c6ae..b317c48 100644
--- a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/query/RdfQueryParserFactory.java
+++ b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/query/RdfQueryParserFactory.java
@@ -20,17 +20,15 @@
package org.apache.polygene.index.rdf.query;
-import org.openrdf.query.QueryLanguage;
import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.injection.scope.Structure;
import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.service.ServiceComposite;
-import org.apache.polygene.api.service.qualifier.Tagged;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.api.value.ValueSerializer;
import org.apache.polygene.index.rdf.UnsupportedLanguageException;
import org.apache.polygene.index.rdf.query.internal.RdfQueryParserImpl;
import org.apache.polygene.spi.PolygeneSPI;
+import org.apache.polygene.spi.serialization.JsonSerializer;
+import org.openrdf.query.QueryLanguage;
@Mixins( RdfQueryParserFactory.RdfQueryParserFactoryMixin.class )
public interface RdfQueryParserFactory
@@ -45,15 +43,14 @@ public interface RdfQueryParserFactory
private PolygeneSPI spi;
@Service
- @Tagged( ValueSerialization.Formats.JSON )
- private ValueSerializer valueSerializer;
+ private JsonSerializer stateSerializer;
@Override
public RdfQueryParser newQueryParser( QueryLanguage language )
{
if( language.equals( QueryLanguage.SPARQL ) )
{
- return new RdfQueryParserImpl( spi, valueSerializer );
+ return new RdfQueryParserImpl( spi, stateSerializer );
}
throw new UnsupportedLanguageException( language );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/query/internal/RdfQueryParserImpl.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/query/internal/RdfQueryParserImpl.java b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/query/internal/RdfQueryParserImpl.java
index d176dd3..c0bec0d 100644
--- a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/query/internal/RdfQueryParserImpl.java
+++ b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/query/internal/RdfQueryParserImpl.java
@@ -47,15 +47,14 @@ import org.apache.polygene.api.query.grammar.NePredicate;
import org.apache.polygene.api.query.grammar.Notpredicate;
import org.apache.polygene.api.query.grammar.OrPredicate;
import org.apache.polygene.api.query.grammar.OrderBy;
-import org.apache.polygene.api.query.grammar.PropertyFunction;
import org.apache.polygene.api.query.grammar.PropertyNotNullPredicate;
import org.apache.polygene.api.query.grammar.PropertyNullPredicate;
import org.apache.polygene.api.query.grammar.QuerySpecification;
import org.apache.polygene.api.query.grammar.Variable;
-import org.apache.polygene.api.value.ValueSerializer;
-import org.apache.polygene.api.value.ValueSerializer.Options;
+import org.apache.polygene.api.serialization.Serializer;
import org.apache.polygene.index.rdf.query.RdfQueryParser;
import org.apache.polygene.spi.PolygeneSPI;
+import org.apache.polygene.spi.serialization.JsonSerializer;
import org.slf4j.LoggerFactory;
import static java.lang.String.format;
@@ -72,7 +71,7 @@ public class RdfQueryParserImpl
private final Namespaces namespaces = new Namespaces();
private final Triples triples = new Triples( namespaces );
private final PolygeneSPI spi;
- private final ValueSerializer valueSerializer;
+ private final JsonSerializer stateSerializer;
private Map<String, Object> variables;
static
@@ -90,10 +89,10 @@ public class RdfQueryParserImpl
) );
}
- public RdfQueryParserImpl( PolygeneSPI spi, ValueSerializer valueSerializer )
+ public RdfQueryParserImpl( PolygeneSPI spi, JsonSerializer stateSerializer )
{
this.spi = spi;
- this.valueSerializer = valueSerializer;
+ this.stateSerializer = stateSerializer;
}
@Override
@@ -328,7 +327,8 @@ public class RdfQueryParserImpl
private String createAndEscapeJSONString( Object value )
{
- return escapeJSONString( valueSerializer.serialize( new Options().withoutTypeInfo(), value ) );
+ String serialized = stateSerializer.serialize( Serializer.Options.NO_TYPE_INFO, value );
+ return escapeJSONString( serialized );
}
private String createRegexStringForContaining( String valueVariable, String containedString )
@@ -376,7 +376,7 @@ public class RdfQueryParserImpl
String jsonStr = "";
if( item != null )
{
- String serialized = valueSerializer.serialize( new Options().withoutTypeInfo(), item );
+ String serialized = stateSerializer.serialize( Serializer.Options.NO_TYPE_INFO, item );
if( item instanceof String )
{
serialized = "\"" + StringEscapeUtils.escapeJava( serialized ) + "\"";
@@ -424,7 +424,7 @@ public class RdfQueryParserImpl
if( predicate instanceof ComparisonPredicate )
{
ComparisonPredicate<?> comparisonPredicate = (ComparisonPredicate<?>) predicate;
- Triples.Triple triple = triples.addTriple( (PropertyFunction) comparisonPredicate.property(), false );
+ Triples.Triple triple = triples.addTriple( comparisonPredicate.property(), false );
// Don't use FILTER for equals-comparison. Do direct match instead
if( predicate instanceof EqPredicate && allowInline )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/ContainsAllTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/ContainsAllTest.java b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/ContainsAllTest.java
index 0db4bd0..3d7fb36 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/ContainsAllTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/ContainsAllTest.java
@@ -131,12 +131,12 @@ public class ContainsAllTest
private static void populateStrings( ExampleEntity proto, String... strings )
{
- proto.strings().set( new HashSet<String>( Arrays.asList( strings ) ) );
+ proto.strings().set( setOf( strings ) );
}
private static void populateComplexValue( ExampleEntity proto, ValueBuilderFactory vbf, String... valueStrings )
{
- Set<ExampleValue> values = new HashSet<ExampleValue>();
+ Set<ExampleValue> values = new HashSet<>();
for( String value : valueStrings )
{
ValueBuilder<ExampleValue2> vBuilder = vbf.newValueBuilder( ExampleValue2.class );
@@ -154,16 +154,9 @@ public class ContainsAllTest
public void simpleContainsAllQuerySuccessTest()
throws Exception
{
-
ExampleEntity result = this.performContainsAllStringsTest(
- new HashSet<String>( Arrays.asList(
- TEST_STRING_1, TEST_STRING_2, TEST_STRING_3
- )
- ),
- new HashSet<String>( Arrays.asList(
- TEST_STRING_1, TEST_STRING_2
- )
- )
+ setOf( TEST_STRING_1, TEST_STRING_2, TEST_STRING_3 ),
+ setOf( TEST_STRING_1, TEST_STRING_2 )
);
Assert.assertTrue( "The entity must have been found.", result != null );
@@ -174,14 +167,8 @@ public class ContainsAllTest
throws Exception
{
ExampleEntity result = this.performContainsAllStringsTest(
- new HashSet<String>( Arrays.asList(
- TEST_STRING_1, TEST_STRING_2, TEST_STRING_3
- )
- ),
- new HashSet<String>( Arrays.asList(
- TEST_STRING_1, TEST_STRING_2, TEST_STRING_3
- )
- )
+ setOf( TEST_STRING_1, TEST_STRING_2, TEST_STRING_3 ),
+ setOf( TEST_STRING_1, TEST_STRING_2, TEST_STRING_3 )
);
Assert.assertTrue( "The entity must have been found.", result != null );
@@ -192,14 +179,8 @@ public class ContainsAllTest
throws Exception
{
ExampleEntity result = this.performContainsAllStringsTest(
- new HashSet<String>( Arrays.asList(
- TEST_STRING_1, TEST_STRING_2, TEST_STRING_3
- )
- ),
- new HashSet<String>( Arrays.asList(
- TEST_STRING_1, TEST_STRING_2, TEST_STRING_3, TEST_STRING_4
- )
- )
+ setOf( TEST_STRING_1, TEST_STRING_2, TEST_STRING_3 ),
+ setOf( TEST_STRING_1, TEST_STRING_2, TEST_STRING_3, TEST_STRING_4 )
);
Assert.assertTrue( "The entity must not have been found.", result == null );
@@ -210,14 +191,8 @@ public class ContainsAllTest
throws Exception
{
ExampleEntity result = this.performContainsAllStringsTest(
- new HashSet<String>( Arrays.asList(
- TEST_STRING_1, TEST_STRING_2, TEST_STRING_3
- )
- ),
- new HashSet<String>( Arrays.asList(
- TEST_STRING_1, null, TEST_STRING_2
- )
- )
+ setOf( TEST_STRING_1, TEST_STRING_2, TEST_STRING_3 ),
+ setOf( TEST_STRING_1, null, TEST_STRING_2 )
);
Assert.assertTrue( "The entity must have been found.", result != null );
@@ -228,11 +203,8 @@ public class ContainsAllTest
throws Exception
{
ExampleEntity result = this.performContainsAllStringsTest(
- new HashSet<String>( Arrays.asList(
- TEST_STRING_1, TEST_STRING_2
- )
- ),
- new HashSet<String>()
+ setOf( TEST_STRING_1, TEST_STRING_2 ),
+ setOf()
);
Assert.assertTrue( "The entity must have been found.", result != null );
@@ -243,14 +215,8 @@ public class ContainsAllTest
throws Exception
{
ExampleEntity result = this.performContainsAllStringValueTest(
- new HashSet<String>( Arrays.asList(
- TEST_STRING_1, TEST_STRING_2
- )
- ),
- new HashSet<String>( Arrays.asList(
- TEST_STRING_1
- )
- )
+ setOf( TEST_STRING_1, TEST_STRING_2 ),
+ setOf( TEST_STRING_1 )
);
Assert.assertTrue( "The entity must have been found.", result != null );
@@ -261,14 +227,8 @@ public class ContainsAllTest
throws Exception
{
ExampleEntity result = this.performContainsAllStringValueTest(
- new HashSet<String>( Arrays.asList(
- TEST_STRING_1, TEST_STRING_2
- )
- ),
- new HashSet<String>( Arrays.asList(
- TEST_STRING_1, TEST_STRING_2
- )
- )
+ setOf( TEST_STRING_1, TEST_STRING_2 ),
+ setOf( TEST_STRING_1, TEST_STRING_2 )
);
Assert.assertTrue( "The entity must have been found", result != null );
@@ -279,14 +239,8 @@ public class ContainsAllTest
throws Exception
{
ExampleEntity result = this.performContainsAllStringValueTest(
- new HashSet<String>( Arrays.asList(
- TEST_STRING_1, TEST_STRING_2
- )
- ),
- new HashSet<String>( Arrays.asList(
- TEST_STRING_1, TEST_STRING_2, TEST_STRING_3
- )
- )
+ setOf( TEST_STRING_1, TEST_STRING_2 ),
+ setOf( TEST_STRING_1, TEST_STRING_2, TEST_STRING_3 )
);
Assert.assertTrue( "The entity must not have been found.", result == null );
@@ -297,11 +251,8 @@ public class ContainsAllTest
throws Exception
{
ExampleEntity result = this.performContainsAllStringValueTest(
- new HashSet<String>( Arrays.asList(
- TEST_STRING_1, TEST_STRING_2
- )
- ),
- new HashSet<String>()
+ setOf( TEST_STRING_1, TEST_STRING_2 ),
+ setOf()
);
Assert.assertTrue( "The entity must have been found.", result != null );
@@ -312,8 +263,8 @@ public class ContainsAllTest
QueryBuilder<ExampleEntity> builder = this.queryBuilderFactory.newQueryBuilder( ExampleEntity.class );
builder = builder.where( QueryExpressions.containsAll(
- QueryExpressions.templateFor( ExampleEntity.class ).strings(),
- Arrays.asList( strings ) ) );
+ QueryExpressions.templateFor( ExampleEntity.class ).strings(),
+ Arrays.asList( strings ) ) );
return this.unitOfWorkFactory.currentUnitOfWork().newQuery( builder ).find();
}
@@ -337,9 +288,9 @@ public class ContainsAllTest
{
QueryBuilder<ExampleEntity> builder = this.queryBuilderFactory.newQueryBuilder( ExampleEntity.class );
builder = builder.where( QueryExpressions.containsAll(
- QueryExpressions.templateFor( ExampleEntity.class ).complexValue(),
- valuez
- )
+ QueryExpressions.templateFor( ExampleEntity.class ).complexValue(),
+ valuez
+ )
);
return this.unitOfWorkFactory.currentUnitOfWork().newQuery( builder );
@@ -349,14 +300,14 @@ public class ContainsAllTest
throws Exception
{
UnitOfWork creatingUOW = this.unitOfWorkFactory.newUnitOfWork();
- String[] entityStringsArray = new String[entityStrings.size()];
+ String[] entityStringsArray = new String[ entityStrings.size() ];
createEntityWithStrings( creatingUOW, this.valueBuilderFactory, entityStrings.toArray( entityStringsArray ) );
creatingUOW.complete();
UnitOfWork queryingUOW = this.unitOfWorkFactory.newUnitOfWork();
try
{
- String[] queryableStringsArray = new String[queryableStrings.size()];
+ String[] queryableStringsArray = new String[ queryableStrings.size() ];
ExampleEntity entity = this.findEntity( queryableStrings.toArray( queryableStringsArray ) );
return entity;
}
@@ -370,15 +321,17 @@ public class ContainsAllTest
throws Exception
{
UnitOfWork creatingUOW = this.unitOfWorkFactory.newUnitOfWork();
- String[] entityStringsArray = new String[entityStrings.size()];
- createEntityWithComplexValues( creatingUOW, this.valueBuilderFactory, entityStrings.toArray( entityStringsArray ) );
+ String[] entityStringsArray = new String[ entityStrings.size() ];
+ createEntityWithComplexValues( creatingUOW, this.valueBuilderFactory,
+ entityStrings.toArray( entityStringsArray ) );
creatingUOW.complete();
UnitOfWork queryingUOW = this.unitOfWorkFactory.newUnitOfWork();
try
{
- String[] queryableStringsArray = new String[queryableStrings.size()];
- ExampleEntity entity = this.findEntityBasedOnValueStrings( queryableStrings.toArray( queryableStringsArray ) );
+ String[] queryableStringsArray = new String[ queryableStrings.size() ];
+ ExampleEntity entity = this.findEntityBasedOnValueStrings(
+ queryableStrings.toArray( queryableStringsArray ) );
return entity;
}
finally
@@ -386,4 +339,9 @@ public class ContainsAllTest
queryingUOW.discard();
}
}
+
+ static <T> Set<T> setOf( T... elements )
+ {
+ return new HashSet<T>( Arrays.asList( elements ) );
+ }
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/ContainsTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/ContainsTest.java b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/ContainsTest.java
index f96bc90..0cde1a7 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/ContainsTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/ContainsTest.java
@@ -20,8 +20,6 @@
package org.apache.polygene.index.rdf;
import java.io.File;
-import java.util.Arrays;
-import java.util.HashSet;
import java.util.Set;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.api.query.Query;
@@ -45,6 +43,12 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
+import static org.apache.polygene.index.rdf.ContainsAllTest.TEST_STRING_1;
+import static org.apache.polygene.index.rdf.ContainsAllTest.TEST_STRING_2;
+import static org.apache.polygene.index.rdf.ContainsAllTest.TEST_STRING_3;
+import static org.apache.polygene.index.rdf.ContainsAllTest.TEST_STRING_4;
+import static org.apache.polygene.index.rdf.ContainsAllTest.setOf;
+
public class ContainsTest extends AbstractPolygeneTest
{
@Rule
@@ -76,10 +80,8 @@ public class ContainsTest extends AbstractPolygeneTest
public void simpleContainsSuccessTest() throws Exception
{
ExampleEntity result = this.performContainsStringTest(
- new HashSet<>( Arrays.asList(
- ContainsAllTest.TEST_STRING_1, ContainsAllTest.TEST_STRING_2, ContainsAllTest.TEST_STRING_3
- ) ),
- ContainsAllTest.TEST_STRING_3
+ setOf( TEST_STRING_1, TEST_STRING_2, TEST_STRING_3 ),
+ TEST_STRING_3
);
Assert.assertTrue( "The entity must have been found", result != null );
@@ -89,10 +91,8 @@ public class ContainsTest extends AbstractPolygeneTest
public void simpleContainsSuccessFailTest() throws Exception
{
ExampleEntity result = this.performContainsStringTest(
- new HashSet<>( Arrays.asList(
- ContainsAllTest.TEST_STRING_1, ContainsAllTest.TEST_STRING_2, ContainsAllTest.TEST_STRING_3
- ) ),
- ContainsAllTest.TEST_STRING_4
+ setOf( TEST_STRING_1, TEST_STRING_2, TEST_STRING_3 ),
+ TEST_STRING_4
);
Assert.assertTrue( "The entity must not have been found", result == null );
@@ -102,9 +102,7 @@ public class ContainsTest extends AbstractPolygeneTest
public void simplecontainsNullTest() throws Exception
{
this.performContainsStringTest(
- new HashSet<>( Arrays.asList(
- ContainsAllTest.TEST_STRING_1, ContainsAllTest.TEST_STRING_2, ContainsAllTest.TEST_STRING_3
- ) ),
+ setOf( TEST_STRING_1, TEST_STRING_2, TEST_STRING_3 ),
null
);
}
@@ -113,10 +111,8 @@ public class ContainsTest extends AbstractPolygeneTest
public void simpleContainsStringValueSuccessTest() throws Exception
{
ExampleEntity result = this.performContainsStringValueTest(
- new HashSet<>( Arrays.asList(
- ContainsAllTest.TEST_STRING_1, ContainsAllTest.TEST_STRING_2, ContainsAllTest.TEST_STRING_3
- ) ),
- ContainsAllTest.TEST_STRING_3
+ setOf( TEST_STRING_1, TEST_STRING_2, TEST_STRING_3 ),
+ TEST_STRING_3
);
Assert.assertTrue( "The entity must have been found", result != null );
@@ -126,10 +122,8 @@ public class ContainsTest extends AbstractPolygeneTest
public void simpleContainsStringValueFailTest() throws Exception
{
ExampleEntity result = this.performContainsStringTest(
- new HashSet<>( Arrays.asList(
- ContainsAllTest.TEST_STRING_1, ContainsAllTest.TEST_STRING_2, ContainsAllTest.TEST_STRING_3
- ) ),
- ContainsAllTest.TEST_STRING_4
+ setOf( TEST_STRING_1, TEST_STRING_2, TEST_STRING_3 ),
+ TEST_STRING_4
);
Assert.assertTrue( "The entity must not have been found", result == null );
@@ -139,11 +133,8 @@ public class ContainsTest extends AbstractPolygeneTest
{
QueryBuilder<ExampleEntity> builder = this.queryBuilderFactory.newQueryBuilder( ExampleEntity.class );
- builder = builder.where( QueryExpressions.contains(
- QueryExpressions.templateFor( ExampleEntity.class ).strings(),
- string
- )
- );
+ builder = builder.where(
+ QueryExpressions.contains( QueryExpressions.templateFor( ExampleEntity.class ).strings(), string ) );
return this.unitOfWorkFactory.currentUnitOfWork().newQuery( builder ).find();
}
@@ -161,11 +152,8 @@ public class ContainsTest extends AbstractPolygeneTest
private Query<ExampleEntity> createComplexQuery( ExampleValue value )
{
QueryBuilder<ExampleEntity> builder = this.queryBuilderFactory.newQueryBuilder( ExampleEntity.class );
- builder = builder.where( QueryExpressions.contains(
- QueryExpressions.templateFor( ExampleEntity.class ).complexValue(),
- value
- )
- );
+ builder = builder.where(
+ QueryExpressions.contains( QueryExpressions.templateFor( ExampleEntity.class ).complexValue(), value ) );
return this.unitOfWorkFactory.currentUnitOfWork().newQuery( builder );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfComplexQueryTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfComplexQueryTest.java b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfComplexQueryTest.java
index 6102e8b..31c2d3c 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfComplexQueryTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfComplexQueryTest.java
@@ -19,15 +19,13 @@
*/
package org.apache.polygene.index.rdf;
-import org.junit.Ignore;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.library.rdf.entity.EntityStateSerializer;
import org.apache.polygene.library.rdf.entity.EntityTypeSerializer;
import org.apache.polygene.library.rdf.repository.MemoryRepositoryService;
import org.apache.polygene.test.indexing.AbstractComplexQueryTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
+import org.junit.Ignore;
@Ignore( "RDF Index/Query do not support Complex Queries, ie. queries by 'example values'" )
public class RdfComplexQueryTest
@@ -40,7 +38,6 @@ public class RdfComplexQueryTest
{
super.assemble( module );
module.services( RdfIndexingEngineService.class ).instantiateOnStartup();
- module.services( OrgJsonValueSerializationService.class ).taggedWith( ValueSerialization.Formats.JSON );
module.objects( EntityStateSerializer.class, EntityTypeSerializer.class );
module.services( MemoryRepositoryService.class ).identifiedBy( "rdf-indexing" ).instantiateOnStartup();
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfEntityFinderTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfEntityFinderTest.java b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfEntityFinderTest.java
index 626d184..86723ce 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfEntityFinderTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfEntityFinderTest.java
@@ -19,14 +19,12 @@
*/
package org.apache.polygene.index.rdf;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.library.rdf.entity.EntityStateSerializer;
import org.apache.polygene.library.rdf.entity.EntityTypeSerializer;
import org.apache.polygene.library.rdf.repository.MemoryRepositoryService;
import org.apache.polygene.test.indexing.AbstractEntityFinderTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
public class RdfEntityFinderTest extends AbstractEntityFinderTest
{
@@ -37,7 +35,6 @@ public class RdfEntityFinderTest extends AbstractEntityFinderTest
super.assemble( module );
module.objects( EntityStateSerializer.class, EntityTypeSerializer.class );
module.services( RdfIndexingEngineService.class ).instantiateOnStartup();
- module.services( OrgJsonValueSerializationService.class ).taggedWith( ValueSerialization.Formats.JSON );
module.services( MemoryRepositoryService.class ).identifiedBy( "rdf-indexing" ).instantiateOnStartup();
// module.services( NativeRdfRepositoryService.class ).identifiedBy( "rdf-indexing" );
// module.addComposites( NativeRdfConfiguration.class );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryMultimoduleTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryMultimoduleTest.java b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryMultimoduleTest.java
index 21f5d46..23c8f13 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryMultimoduleTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryMultimoduleTest.java
@@ -27,7 +27,6 @@ import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
import org.apache.polygene.index.rdf.assembly.RdfMemoryStoreAssembler;
import org.apache.polygene.test.EntityTestAssembler;
-import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
public class RdfNamedQueryMultimoduleTest
extends RdfNamedQueryTest
@@ -48,7 +47,6 @@ public class RdfNamedQueryMultimoduleTest
ModuleAssembly indexModule = layer.module( "index" );
new DefaultUnitOfWorkAssembler().assemble( indexModule );
new RdfMemoryStoreAssembler( Visibility.layer, Visibility.module ).assemble( indexModule );
- new JacksonValueSerializationAssembler().assemble( indexModule );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryTest.java b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryTest.java
index 6ebbee8..e327387 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfNamedQueryTest.java
@@ -27,8 +27,6 @@ import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.index.rdf.assembly.RdfMemoryStoreAssembler;
import org.apache.polygene.index.rdf.query.SesameExpressions;
import org.apache.polygene.test.indexing.AbstractNamedQueryTest;
-import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
-import org.slf4j.LoggerFactory;
public class RdfNamedQueryTest extends AbstractNamedQueryTest
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfQueryMultimoduleTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfQueryMultimoduleTest.java b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfQueryMultimoduleTest.java
index d9d0cf1..0ed4774 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfQueryMultimoduleTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/RdfQueryMultimoduleTest.java
@@ -28,7 +28,6 @@ import org.apache.polygene.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
import org.apache.polygene.index.rdf.assembly.RdfNativeSesameStoreAssembler;
import org.apache.polygene.library.rdf.repository.NativeConfiguration;
import org.apache.polygene.test.EntityTestAssembler;
-import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
@@ -54,7 +53,6 @@ public class RdfQueryMultimoduleTest
ModuleAssembly indexModule = layer.module( "index" );
new RdfNativeSesameStoreAssembler( Visibility.layer, Visibility.module ).assemble( indexModule );
new DefaultUnitOfWorkAssembler().assemble( indexModule );
- new JacksonValueSerializationAssembler().assemble( indexModule );
LayerAssembly configLayer = module.layer().application().layer( "config" );
module.layer().uses( configLayer );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/qi66/Qi66IssueTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/qi66/Qi66IssueTest.java b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/qi66/Qi66IssueTest.java
index 372e9d8..d5a385c 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/qi66/Qi66IssueTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/qi66/Qi66IssueTest.java
@@ -19,12 +19,10 @@
*/
package org.apache.polygene.index.rdf.qi66;
-import org.apache.polygene.api.identity.Identity;
-import org.junit.Test;
import org.apache.polygene.api.entity.EntityBuilder;
+import org.apache.polygene.api.identity.Identity;
import org.apache.polygene.api.unitofwork.UnitOfWork;
import org.apache.polygene.api.unitofwork.UnitOfWorkCompletionException;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.index.rdf.query.RdfQueryParserFactory;
@@ -34,7 +32,7 @@ import org.apache.polygene.library.rdf.entity.EntityTypeSerializer;
import org.apache.polygene.library.rdf.repository.MemoryRepositoryService;
import org.apache.polygene.test.AbstractPolygeneTest;
import org.apache.polygene.test.EntityTestAssembler;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
+import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
@@ -97,7 +95,6 @@ public class Qi66IssueTest
module.services( RdfQueryService.class,
RdfQueryParserFactory.class,
MemoryRepositoryService.class );
- module.services( OrgJsonValueSerializationService.class ).taggedWith( ValueSerialization.Formats.JSON );
module.objects( EntityStateSerializer.class, EntityTypeSerializer.class );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/qi95/Qi95IssueTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/qi95/Qi95IssueTest.java b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/qi95/Qi95IssueTest.java
index 9dd94b7..2694153 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/qi95/Qi95IssueTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/qi95/Qi95IssueTest.java
@@ -23,10 +23,6 @@ import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
-import org.apache.polygene.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
-import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
-import org.junit.Rule;
-import org.junit.Test;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.api.entity.EntityBuilder;
import org.apache.polygene.api.entity.EntityComposite;
@@ -37,13 +33,22 @@ import org.apache.polygene.api.structure.Application;
import org.apache.polygene.api.structure.Module;
import org.apache.polygene.api.unitofwork.UnitOfWork;
import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
-import org.apache.polygene.bootstrap.*;
+import org.apache.polygene.bootstrap.ApplicationAssembler;
+import org.apache.polygene.bootstrap.ApplicationAssembly;
+import org.apache.polygene.bootstrap.ApplicationAssemblyFactory;
+import org.apache.polygene.bootstrap.Assembler;
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.Energy4Java;
+import org.apache.polygene.bootstrap.LayerAssembly;
+import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.jdbm.JdbmConfiguration;
import org.apache.polygene.entitystore.jdbm.assembly.JdbmEntityStoreAssembler;
import org.apache.polygene.index.rdf.assembly.RdfMemoryStoreAssembler;
import org.apache.polygene.index.rdf.assembly.RdfNativeSesameStoreAssembler;
import org.apache.polygene.library.rdf.repository.NativeConfiguration;
import org.apache.polygene.test.EntityTestAssembler;
+import org.junit.Rule;
+import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static org.junit.Assert.assertTrue;
@@ -221,7 +226,6 @@ public class Qi95IssueTest
public ModuleAssembly buildModuleAssembly( LayerAssembly layer, String name )
throws AssemblyException
{
- addModule( layer, name, new JacksonValueSerializationAssembler() );
return addModule( layer, name, new RdfNativeSesameStoreAssembler() );
}
};
@@ -242,7 +246,6 @@ public class Qi95IssueTest
public ModuleAssembly buildModuleAssembly( LayerAssembly layer, String name )
throws AssemblyException
{
- addModule( layer, name, new JacksonValueSerializationAssembler() );
return addModule( layer, name, new RdfMemoryStoreAssembler() );
}
};
@@ -282,7 +285,6 @@ public class Qi95IssueTest
throws AssemblyException
{
module.entities( ItemTypeEntity.class );
- new DefaultUnitOfWorkAssembler().assemble( module );
}
} );
return domainLayer;
@@ -298,7 +300,6 @@ public class Qi95IssueTest
throws AssemblyException
{
new EntityTestAssembler().assemble( module );
- new DefaultUnitOfWorkAssembler().assemble( module );
module.entities( NativeConfiguration.class ).visibleIn( Visibility.application );
module.forMixin( NativeConfiguration.class )
@@ -324,9 +325,7 @@ public class Qi95IssueTest
public void assemble( ModuleAssembly module )
throws AssemblyException
{
- new JacksonValueSerializationAssembler().assemble( module );
new JdbmEntityStoreAssembler().visibleIn( Visibility.application ).assemble( module );
- new DefaultUnitOfWorkAssembler().assemble( module );
}
};
}
@@ -336,7 +335,6 @@ public class Qi95IssueTest
{
ModuleAssembly moduleAssembly = layerAssembly.module( name );
assembler.assemble( moduleAssembly );
- new DefaultUnitOfWorkAssembler().assemble( moduleAssembly );
return moduleAssembly;
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-solr/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/indexing-solr/build.gradle b/extensions/indexing-solr/build.gradle
index fd991f6..608bec3 100644
--- a/extensions/indexing-solr/build.gradle
+++ b/extensions/indexing-solr/build.gradle
@@ -34,7 +34,6 @@ dependencies {
runtimeOnly polygene.core.runtime
testImplementation polygene.core.testsupport
- testImplementation polygene.extension( 'valueserialization-jackson' )
testRuntimeOnly libraries.logback
testRuntimeOnly libraries.servlet_api
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-solr/src/main/java/org/apache/polygene/index/solr/assembly/SolrIndexingAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-solr/src/main/java/org/apache/polygene/index/solr/assembly/SolrIndexingAssembler.java b/extensions/indexing-solr/src/main/java/org/apache/polygene/index/solr/assembly/SolrIndexingAssembler.java
index fa6b59c..4932cdc 100644
--- a/extensions/indexing-solr/src/main/java/org/apache/polygene/index/solr/assembly/SolrIndexingAssembler.java
+++ b/extensions/indexing-solr/src/main/java/org/apache/polygene/index/solr/assembly/SolrIndexingAssembler.java
@@ -20,28 +20,23 @@
package org.apache.polygene.index.solr.assembly;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.Assemblers;
-import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.bootstrap.ServiceDeclaration;
import org.apache.polygene.index.solr.EmbeddedSolrService;
import org.apache.polygene.index.solr.SolrQueryService;
import org.apache.polygene.library.rdf.entity.EntityStateSerializer;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
public class SolrIndexingAssembler extends Assemblers.VisibilityIdentityConfig<SolrIndexingAssembler>
{
@Override
- public void assemble( ModuleAssembly module ) throws AssemblyException
- {
- module.services( EmbeddedSolrService.class ).identifiedBy( "solr" ).instantiateOnStartup();
- ServiceDeclaration queryService = module.services( SolrQueryService.class );
- queryService.
- taggedWith( "solr", "search", "indexing", "query" ).
- identifiedBy( identity() ).
- visibleIn( visibility() ).
- instantiateOnStartup();
- module.objects( EntityStateSerializer.class );
- }
+ public void assemble( ModuleAssembly module )
+ {
+ module.services( EmbeddedSolrService.class ).identifiedBy( "solr" ).instantiateOnStartup();
+ module.services( SolrQueryService.class )
+ .taggedWith( "solr", "search", "indexing", "query" )
+ .identifiedBy( identity() )
+ .visibleIn( visibility() )
+ .instantiateOnStartup();
+ module.objects( EntityStateSerializer.class );
+ }
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-solr/src/main/java/org/apache/polygene/index/solr/internal/SolrEntityIndexerMixin.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-solr/src/main/java/org/apache/polygene/index/solr/internal/SolrEntityIndexerMixin.java b/extensions/indexing-solr/src/main/java/org/apache/polygene/index/solr/internal/SolrEntityIndexerMixin.java
index 1301718..14335d0 100644
--- a/extensions/indexing-solr/src/main/java/org/apache/polygene/index/solr/internal/SolrEntityIndexerMixin.java
+++ b/extensions/indexing-solr/src/main/java/org/apache/polygene/index/solr/internal/SolrEntityIndexerMixin.java
@@ -21,15 +21,19 @@
package org.apache.polygene.index.solr.internal;
import java.io.IOException;
+import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import org.apache.solr.client.solrj.SolrServer;
-import org.apache.solr.client.solrj.SolrServerException;
-import org.apache.solr.common.SolrInputDocument;
-import org.apache.solr.core.SolrCore;
-import org.apache.solr.schema.SchemaField;
+import javax.json.Json;
+import javax.json.JsonArray;
+import javax.json.JsonNumber;
+import javax.json.JsonObject;
+import javax.json.JsonReader;
+import javax.json.JsonString;
+import javax.json.JsonValue;
+import javax.json.stream.JsonParser;
import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.injection.scope.Uses;
import org.apache.polygene.index.solr.EmbeddedSolrService;
@@ -37,9 +41,11 @@ import org.apache.polygene.index.solr.SolrQueryService;
import org.apache.polygene.library.rdf.entity.EntityStateSerializer;
import org.apache.polygene.spi.entity.EntityState;
import org.apache.polygene.spi.entity.EntityStatus;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
+import org.apache.solr.client.solrj.SolrServer;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.common.SolrInputDocument;
+import org.apache.solr.core.SolrCore;
+import org.apache.solr.schema.SchemaField;
import org.openrdf.model.BNode;
import org.openrdf.model.Graph;
import org.openrdf.model.Literal;
@@ -151,7 +157,7 @@ public abstract class SolrEntityIndexerMixin
}
private SolrInputDocument indexEntityState( final EntityState entityState )
- throws IOException, SolrServerException, JSONException
+ throws IOException, SolrServerException
{
Graph graph = new GraphImpl();
stateSerializer.serialize( entityState, false, graph );
@@ -171,15 +177,24 @@ public abstract class SolrEntityIndexerMixin
String value = statement.getObject().stringValue();
if( field.getType().getTypeName().equals( "json" ) )
{
- if( value.charAt( 0 ) == '[' )
- {
- JSONArray array = new JSONArray( value );
- indexJson( input, array );
- }
- else if( value.charAt( 0 ) == '{' )
+ try( JsonParser parser = Json.createParser( new StringReader( value ) ) )
{
- JSONObject object = new JSONObject( value );
- indexJson( input, object );
+ JsonParser.Event event = parser.next();
+ switch( event )
+ {
+ case START_ARRAY:
+ try( JsonReader reader = Json.createReader( new StringReader( value ) ) )
+ {
+ indexJson( input, reader.readArray() );
+ }
+ break;
+ case START_OBJECT:
+ try( JsonReader reader = Json.createReader( new StringReader( value ) ) )
+ {
+ indexJson( input, reader.readObject() );
+ }
+ break;
+ }
}
}
else
@@ -215,34 +230,54 @@ public abstract class SolrEntityIndexerMixin
}
private void indexJson( SolrInputDocument input, Object object )
- throws JSONException
{
- if( object instanceof JSONArray )
+ if( object instanceof JsonArray )
{
- JSONArray array = (JSONArray) object;
- for( int i = 0; i < array.length(); i++ )
+ JsonArray array = (JsonArray) object;
+ for( int i = 0; i < array.size(); i++ )
{
indexJson( input, array.get( i ) );
}
}
else
{
- JSONObject jsonObject = (JSONObject) object;
- Iterator keys = jsonObject.keys();
- while( keys.hasNext() )
+ JsonObject jsonObject = (JsonObject) object;
+ for( String name : jsonObject.keySet() )
{
- Object name = keys.next();
- Object value = jsonObject.get( name.toString() );
- if( value instanceof JSONObject || value instanceof JSONArray )
+ JsonValue jsonValue = jsonObject.get( name );
+ if( jsonValue.getValueType() == JsonValue.ValueType.OBJECT
+ || jsonValue.getValueType() == JsonValue.ValueType.ARRAY )
{
- indexJson( input, value );
+ indexJson( input, jsonValue );
}
else
{
- SchemaField field = indexedFields.get( name.toString() );
+ SchemaField field = indexedFields.get( name );
if( field != null )
{
- input.addField( name.toString(), jsonObject.get( name.toString() ) );
+ Object value;
+ switch( jsonValue.getValueType() )
+ {
+ case NULL:
+ value = null;
+ break;
+ case STRING:
+ value = ( (JsonString) jsonValue ).getString();
+ break;
+ case NUMBER:
+ JsonNumber jsonNumber = (JsonNumber) jsonValue;
+ value = jsonNumber.isIntegral() ? jsonNumber.longValue() : jsonNumber.doubleValue();
+ break;
+ case TRUE:
+ value = Boolean.TRUE;
+ break;
+ case FALSE:
+ value = Boolean.FALSE;
+ break;
+ default:
+ value = jsonValue.toString();
+ }
+ input.addField( name, value );
}
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-sql/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/indexing-sql/build.gradle b/extensions/indexing-sql/build.gradle
index 0c8a21e..e0e50e8 100644
--- a/extensions/indexing-sql/build.gradle
+++ b/extensions/indexing-sql/build.gradle
@@ -38,7 +38,6 @@ dependencies {
testImplementation polygene.internals.testsupport
testImplementation polygene.library( 'sql-dbcp' )
- testImplementation polygene.extension( 'valueserialization-jackson' )
testRuntimeOnly libraries.logback
testRuntimeOnly libraries.derby
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/support/skeletons/SQLCompatEntityStateWrapper.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/support/skeletons/SQLCompatEntityStateWrapper.java b/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/support/skeletons/SQLCompatEntityStateWrapper.java
index 6648590..ed1bc47 100644
--- a/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/support/skeletons/SQLCompatEntityStateWrapper.java
+++ b/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/support/skeletons/SQLCompatEntityStateWrapper.java
@@ -83,6 +83,7 @@ class SQLCompatEntityStateWrapper
|| Enum.class.isAssignableFrom( primaryType )
|| String.class.isAssignableFrom( primaryType )
|| Identity.class.isAssignableFrom( primaryType )
+ // TODO javax.time support in indexing-sql
// || Date.class.isAssignableFrom( primaryType )
// || DateTime.class.isAssignableFrom( primaryType )
// || LocalDateTime.class.isAssignableFrom( primaryType )
[44/50] [abbrv] polygene-java git commit: POLYGENE-191 Documentation
Posted by pa...@apache.org.
POLYGENE-191 Documentation
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/a93e2621
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/a93e2621
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/a93e2621
Branch: refs/heads/serialization-3.0
Commit: a93e262127cfc1cecbcd5f7f6668788ffc6813c9
Parents: d7cd08d
Author: Paul Merlin <pa...@apache.org>
Authored: Mon Feb 27 15:27:24 2017 +0100
Committer: Paul Merlin <pa...@apache.org>
Committed: Mon Mar 13 11:24:42 2017 +0100
----------------------------------------------------------------------
core/api/src/docs/serialization.txt | 16 +--
.../api/value/DocumentationSupport.java | 58 +---------
core/spi/src/docs/serialization.txt | 108 ++++++++++++-------
.../AbstractBinaryDeserializer.java | 7 ++
.../serialization/AbstractBinarySerializer.java | 2 +
.../serialization/AbstractTextDeserializer.java | 7 ++
.../serialization/AbstractTextSerializer.java | 2 +
.../src/docs/serialization-javaxjson.txt | 24 ++++-
...avaxJsonValueCompositeSerializationTest.java | 22 +++-
.../src/docs/serialization-javaxxml.txt | 20 +++-
...JavaxXmlValueCompositeSerializationTest.java | 4 +
.../src/docs/serialization-msgpack.txt | 17 ++-
...sagePackValueCompositeSerializationTest.java | 4 +
13 files changed, 175 insertions(+), 116 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a93e2621/core/api/src/docs/serialization.txt
----------------------------------------------------------------------
diff --git a/core/api/src/docs/serialization.txt b/core/api/src/docs/serialization.txt
index e789125..68939f9 100644
--- a/core/api/src/docs/serialization.txt
+++ b/core/api/src/docs/serialization.txt
@@ -14,10 +14,6 @@
[[core-api-serialization,Serialization]]
= Serialization =
-// TODO Reword with the following outline
-// Preamble - What is it for? What can I use it with?, see <<extensions>>
-// Use cases - Value, collections/streams & arrays of values
-
State can be serialized and deserialized using the Serialization API which is a Service API implemented
by SPI and extensions.
@@ -29,7 +25,7 @@ The Serialization mechanism apply to the following object types :
* EntityReference,
* Iterable & Stream,
* Map,
- * Plain Value.
+ * Plain Values.
Nested Plain Values, EntityReferences, Iterables, Streams, Maps, ValueComposites are supported.
EntityComposites and EntityReferences are serialized as their identity string.
@@ -47,10 +43,7 @@ Plain Values can be one of :
* Double or double,
* BigInteger,
* BigDecimal,
- * Date,
- * DateTime (JodaTime),
- * LocalDateTime (JodaTime),
- * LocalDate (JodaTime).
+ * java.time types.
TIP: Serialization behaviour can be tuned with options.
Every +Serializer+ methods can take a +Serializer.Options+ object that contains flags to change how some
@@ -64,8 +57,7 @@ Methods of +Serializer+ allow to specify if the serialized state should contain
serialized value. Having type information in the serialized payload allows to keep actual ValueComposite types and by so
circumvent +AmbiguousTypeException+ when deserializing.
-Core Runtime provides a default Serialization system based on the
-https://github.com/douglascrockford/JSON-java[org.json] Java library producing and consuming JSON.
+Core Runtime provides a default Serialization system based on `javax.json` types.
Let's see how it works in practice.
@@ -103,7 +95,7 @@ In this second example, we ;
. declare a ValueComposite,
. assemble it,
- . assemble a Serialization Service backed by the +org.json+ package,
+ . assemble a Serialization Service backed by the +javax.json+ types,
. get the +Serializer+ and +Deserializer+ Services injected,
. create a new Value instance,
. use the +Serializer#serialize()+ method to get a JSON representation of the Value,
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a93e2621/core/api/src/test/java/org/apache/polygene/api/value/DocumentationSupport.java
----------------------------------------------------------------------
diff --git a/core/api/src/test/java/org/apache/polygene/api/value/DocumentationSupport.java b/core/api/src/test/java/org/apache/polygene/api/value/DocumentationSupport.java
index 4de963b..2f55c83 100644
--- a/core/api/src/test/java/org/apache/polygene/api/value/DocumentationSupport.java
+++ b/core/api/src/test/java/org/apache/polygene/api/value/DocumentationSupport.java
@@ -29,13 +29,8 @@ import java.util.stream.Stream;
import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.property.Property;
import org.apache.polygene.api.serialization.Deserializer;
-import org.apache.polygene.api.serialization.Serialization;
import org.apache.polygene.api.serialization.Serializer;
-import org.apache.polygene.api.structure.Application;
-import org.apache.polygene.api.structure.Module;
-import org.apache.polygene.bootstrap.Assembler;
import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.Energy4Java;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.test.AbstractPolygeneTest;
import org.junit.Test;
@@ -46,8 +41,8 @@ import static org.junit.Assert.assertThat;
/**
* Snippets:
- * - default : default ValueSerialization
- * - service : assembled service ValueSerialization
+ * - default : default Serialization
+ * - service : assembled service Serialization
* - io : i/o usage
*/
public class DocumentationSupport extends AbstractPolygeneTest
@@ -61,7 +56,6 @@ public class DocumentationSupport extends AbstractPolygeneTest
@Override
public void assemble( ModuleAssembly module )
- throws AssemblyException
{
module.values( SomeValue.class ); // (2)
}
@@ -161,54 +155,6 @@ public class DocumentationSupport extends AbstractPolygeneTest
}
// END SNIPPET: io
- @Test
- // TODO Move to SPI !
- // TODO Include in each Serialization extensions documentation
- public void assembledWithValuesModuleSerialization()
- throws Exception
- {
- Application app = new Energy4Java().newApplication(
- applicationFactory ->
- {
- Assembler[][][] pancakes = new Assembler[][][]
- {
- {
- {
- valuesModule ->
- {
- valuesModule.layer().setName( "SINGLE-Layer" );
- valuesModule.setName( "VALUES-Module" );
-
- valuesModule.values( SomeValue.class );
- }
- },
- {
- servicesModule -> servicesModule.setName( "SERVICES-Module" )
- }
- }
- };
- return applicationFactory.newApplicationAssembly( pancakes );
- } );
- app.activate();
- try
- {
- SomeValue someValue = someNewValueInstance();
-
- Module servicesModule = app.findModule( "SINGLE-Layer", "SERVICES-Module" );
- Serialization stateSerialization = servicesModule.findService( Serialization.class ).get();
-
- String json = stateSerialization.serialize( someValue );
- assertThat( json, equalTo( "{\"foo\":\"bar\"}" ) );
-
- SomeValue someNewValue = stateSerialization.deserialize( module, SomeValue.class, json );
- assertThat( someNewValue, equalTo( someValue ) );
- }
- finally
- {
- app.passivate();
- }
- }
-
private SomeValue someNewValueInstance()
{
ValueBuilder<SomeValue> builder = valueBuilderFactory.newValueBuilder( SomeValue.class );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a93e2621/core/spi/src/docs/serialization.txt
----------------------------------------------------------------------
diff --git a/core/spi/src/docs/serialization.txt b/core/spi/src/docs/serialization.txt
index dca8955..d2d2580 100644
--- a/core/spi/src/docs/serialization.txt
+++ b/core/spi/src/docs/serialization.txt
@@ -20,64 +20,96 @@
[[core-spi-serialization,Serialization SPI]]
= Serialization SPI =
+TIP: Find Serialization extensions in the <<extensions>> list.
+
== Overview ==
The Polygene\u2122 Core Runtime use Serialization to provide string representation of ValueComposites via their `toString()`
method, and, their instantiation from the very same representation via the `newValueFromSerializedState(..)` method of
the ValueBuilderFactory API.
+[snippet,java]
+--------------
+source=core/api/src/test/java/org/apache/polygene/api/value/DocumentationSupport.java
+tag=default
+--------------
+
In each Module, if no Serialization service is assembled, a default one supporting the JSON format is used.
-// TODO Add sample usage of the Serialization service
+[snippet,java]
+--------------
+source=core/api/src/test/java/org/apache/polygene/api/value/DocumentationSupport.java
+tag=service
+--------------
-== Implementation notes ==
+== Text or Binary?
-Simply implement Serialization to create an extension for the Serialization SPI.
-The Core SPI module provides adapters to create pull-parsing capable Serializers and pull-parsing and tree-parsing
-capable Deserializers.
+The Core SPI provides adapters for text or bytes based serialization, extends the following types to implement a custom
+serialization.
-The behaviour described here apply to all Serialization services implemented using the Core SPI adapters. Note that
-nothing stops you from implementing an extension for the Serialization SPI without relying on theses adapters.
+For text based serialization:
-Theses adapters are tailored for serialization mechanisms that support the following two structures that can be nested:
+[snippet,java]
+--------------
+source=core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextSerializer.java
+tag=text
+--------------
- * a collection of name/value pairs. In various languages, this is realized as an object, record, struct,
- dictionary, hash table, keyed list, or associative array,
- * an ordered list of values. In most languages, this is realized as an array, vector, list, or sequence ;
+[snippet,java]
+--------------
+source=core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextDeserializer.java
+tag=text
+--------------
-in other words, a JSON-like structure.
+For bytes based serialization:
+
+[snippet,java]
+--------------
+source=core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinarySerializer.java
+tag=binary
+--------------
+
+[snippet,java]
+--------------
+source=core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinaryDeserializer.java
+tag=binary
+--------------
-Special attention is taken when dealing with Maps. They are serialized as an ordered list of collections of
-name/value pairs to keep the Map order for least surprise. That way, even when the underlying serialization mechanism
-do not keep the collection of name/value pairs order we can rely on it being kept.
+== JSON or XML?
-Here is a sample Map with two entries in JSON notation to make things clear:
+The Core SPI provides JSON and XML serialization respectively based on `javax.json` and `javax.xml` types and APIs to
+work directly with these types so you can work with the actual object representations without serializing to text or
+bytes. They both rely on the text serialization adapters shown above.
-[source,javascript]
-----
-[
- { "key": "foo", "value": "bar" },
- { "key": "cathedral", "value": "bazar" }
-]
-----
+Here is an example using the `JsonSerialization` service:
-Among Plain Values (see the <<core-api-value,Serialization API>> section) some are considered primitives to
-underlying serialization mechanisms and by so handed/come without conversion to/from implementations.
+[snippet,java]
+--------------
+source=extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonValueCompositeSerializationTest.java
+tag=json-serialization
+--------------
-Primitive values can be one of:
+And another using the `XmlSerialization` service:
- * String,
- * Boolean or boolean,
- * Integer or int,
- * Long or long,
- * Short or short,
- * Byte or byte,
- * Float or float,
- * Double or double.
+[snippet,java]
+--------------
+source=extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeSerializationTest.java
+tag=xml-serialization
+--------------
-Serialization is always done in a streaming manner using a pull-parsing based approach.
-Deserialization is done in a streaming manner using a pull-parsing based approach except when encountering a
-ValueComposite. ValueComposite types are deserialized using a tree-parsing based approach.
+== Implementation notes ==
+
+Simply implement Serialization to create an extension for the Serialization SPI.
+The Core SPI module provides adapters to create Serializers and Deserializers.
-All this means that you can serialize and deserialize large collections of values without filling the heap.
+The behaviour described here apply to all Serialization services implemented using the Core SPI adapters. Note that
+nothing stops you from implementing an extension for the Serialization SPI without relying on theses adapters.
+
+Theses adapters are tailored for serialization mechanisms that support the following two structures that can be nested:
+
+ * a collection of name/value pairs. In various languages, this is realized as an object, record, struct,
+ dictionary, hash table, keyed list, or associative array,
+ * an ordered list of values. In most languages, this is realized as an array, vector, list, or sequence ;
+
+in other words, a JSON-like structure.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a93e2621/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinaryDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinaryDeserializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinaryDeserializer.java
index a8f2c2c..7e2d19a 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinaryDeserializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinaryDeserializer.java
@@ -28,7 +28,14 @@ import org.apache.polygene.api.type.ValueType;
import static java.util.stream.Collectors.joining;
+// START SNIPPET: binary
+/**
+ * Base Binary Deserializer.
+ *
+ * Implementations work on bytes, this base deserializer decode Strings from Base64 to produce bytes.
+ */
public abstract class AbstractBinaryDeserializer extends AbstractDeserializer
+// END SNIPPET: binary
{
@Override
public <T> T deserialize( ModuleDescriptor module, ValueType valueType, Reader state )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a93e2621/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinarySerializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinarySerializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinarySerializer.java
index e673ad7..0cf17eb 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinarySerializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinarySerializer.java
@@ -26,12 +26,14 @@ import org.apache.polygene.api.common.Optional;
import static java.nio.charset.StandardCharsets.UTF_8;
+// START SNIPPET: binary
/**
* Base Binary Serializer.
*
* Implementations work on bytes, this base serializer encode these bytes in Base64 to produce Strings.
*/
public abstract class AbstractBinarySerializer extends AbstractSerializer
+// END SNIPPET: binary
{
@Override
public void serialize( Options options, Writer writer, @Optional Object object )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a93e2621/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextDeserializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextDeserializer.java
index 0575489..d87dd6d 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextDeserializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextDeserializer.java
@@ -24,7 +24,14 @@ import org.apache.polygene.api.type.ValueType;
import static java.nio.charset.StandardCharsets.UTF_8;
+// START SNIPPET: text
+/**
+ * Base Text Deserializer.
+ *
+ * Implementations work on Strings, this base deserializer decode bytes in UTF-8 to produce strings.
+ */
public abstract class AbstractTextDeserializer extends AbstractDeserializer
+// END SNIPPET: text
{
@Override
public <T> T deserialize( ModuleDescriptor module, ValueType valueType, InputStream state )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a93e2621/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextSerializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextSerializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextSerializer.java
index 3d8bb16..2c2b83c 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextSerializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextSerializer.java
@@ -25,12 +25,14 @@ import org.apache.polygene.api.common.Optional;
import static java.nio.charset.StandardCharsets.UTF_8;
+// START SNIPPET: text
/**
* Base Text Serializer.
*
* Implementations work on Strings, this base serializer encode these strings in UTF-8 to produce bytes.
*/
public abstract class AbstractTextSerializer extends AbstractSerializer
+// END SNIPPET: text
{
public void serialize( Options options, OutputStream output, @Optional Object object )
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a93e2621/extensions/serialization-javaxjson/src/docs/serialization-javaxjson.txt
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxjson/src/docs/serialization-javaxjson.txt b/extensions/serialization-javaxjson/src/docs/serialization-javaxjson.txt
index f9aee3f..60cfa30 100644
--- a/extensions/serialization-javaxjson/src/docs/serialization-javaxjson.txt
+++ b/extensions/serialization-javaxjson/src/docs/serialization-javaxjson.txt
@@ -25,7 +25,25 @@
source=extensions/serialization-javaxjson/dev-status.xml
--------------
-// TODO Preamble - link to <<core-api-serialization>> and <<core-spi-serialization>>
-// TODO Document usage of JsonSerialization
+`Serialization` service backed by `javax.json` types.
+See <<core-api-serialization>> and <<core-spi-serialization>>.
+
+include::../../build/docs/buildinfo/artifact.txt[]
+
+This extension comes with https://johnzon.apache.org/[Apache Johnzon] as a default `javax.json` provider.
+You can exclude its dependency and replace it by the one of your choice.
+
// TODO Include sample model and its output from test code & resources
-// TODO Assembly - Serialization extension or sole Service, settings & adapters
+
+== Assembly ==
+
+Assembly is done using the provided Assembler:
+
+[snippet,java]
+----
+source=extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonValueCompositeSerializationTest.java
+tag=assembly
+----
+
+Note that this assembler is optional as Polygene assemble this service by default if no Serialization service is declared.
+
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a93e2621/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonValueCompositeSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonValueCompositeSerializationTest.java b/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonValueCompositeSerializationTest.java
index 5fe4f5f..404a143 100644
--- a/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonValueCompositeSerializationTest.java
+++ b/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonValueCompositeSerializationTest.java
@@ -23,6 +23,7 @@ import javax.json.JsonObject;
import javax.json.JsonValue;
import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.unitofwork.UnitOfWork;
+import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.spi.serialization.JsonSerialization;
import org.apache.polygene.test.serialization.AbstractValueCompositeSerializationTest;
import org.junit.Test;
@@ -32,12 +33,26 @@ import static org.junit.Assert.assertThat;
public class JavaxJsonValueCompositeSerializationTest extends AbstractValueCompositeSerializationTest
{
+ // START SNIPPET: assembly
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ new JavaxJsonSerializationAssembler().assemble( module );
+ // END SNIPPET: assembly
+ super.assemble( module );
+ // START SNIPPET: assembly
+ }
+ // END SNIPPET: assembly
+
+ // START SNIPPET: json-serialization
@Service
- private JsonSerialization jsonSerialization;
+ JsonSerialization jsonSerialization;
+ // END SNIPPET: json-serialization
@Test
public void valueCompositeJsonEquality()
{
+ // START SNIPPET: json-serialization
try( UnitOfWork uow = unitOfWorkFactory.newUnitOfWork() )
{
Some some = buildSomeValue( moduleInstance, uow, "42" );
@@ -50,11 +65,12 @@ public class JavaxJsonValueCompositeSerializationTest extends AbstractValueCompo
// Deserialize using Module API
Some some2 = moduleInstance.newValueFromSerializedState( Some.class, stateString );
- assertThat( "Value equality", some, equalTo( some2 ) );
+ assertThat( "Deserialized Value equality", some, equalTo( some2 ) );
JsonObject jsonState2 = Json.createReader( new StringReader( some2.toString() ) ).readObject();
- assertThat( "JSON equality", jsonState, equalTo( jsonState2 ) );
+ assertThat( "value.toString() JSON equality", jsonState, equalTo( jsonState2 ) );
}
+ // END SNIPPET: json-serialization
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a93e2621/extensions/serialization-javaxxml/src/docs/serialization-javaxxml.txt
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/docs/serialization-javaxxml.txt b/extensions/serialization-javaxxml/src/docs/serialization-javaxxml.txt
index 6fe6d75..aef6392 100644
--- a/extensions/serialization-javaxxml/src/docs/serialization-javaxxml.txt
+++ b/extensions/serialization-javaxxml/src/docs/serialization-javaxxml.txt
@@ -25,6 +25,22 @@
source=extensions/serialization-javaxxml/dev-status.xml
--------------
-// TODO Document usage of XmlSerialization
+`Serialization` service backed by `javax.xml` types.
+See <<core-api-serialization>> and <<core-spi-serialization>>.
+
+include::../../build/docs/buildinfo/artifact.txt[]
+
+This extension make use of the Java runtime default `javax.xml` provider.
+You can add dependencies to replace it by the one of your choice.
+
// TODO Include sample model and its output from test code & resources
-// TODO Assembly - Serialization extension or sole Service, settings & adapters
+
+== Assembly ==
+
+Assembly is done using the provided Assembler:
+
+[snippet,java]
+----
+source=extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeSerializationTest.java
+tag=assembly
+----
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a93e2621/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeSerializationTest.java b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeSerializationTest.java
index 27bebc2..b86a2dc 100644
--- a/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeSerializationTest.java
+++ b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeSerializationTest.java
@@ -33,12 +33,16 @@ import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
// TODO Assert deserialization from formatted XML, whitespaces are a problem ATM
public class JavaxXmlValueCompositeSerializationTest extends AbstractValueCompositeSerializationTest
{
+ // START SNIPPET: assembly
@Override
public void assemble( ModuleAssembly module )
{
new JavaxXmlSerializationAssembler().assemble( module );
+ // END SNIPPET: assembly
super.assemble( module );
+ // START SNIPPET: assembly
}
+ // END SNIPPET: assembly
// START SNIPPET: xml-serialization
@Service
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a93e2621/extensions/serialization-msgpack/src/docs/serialization-msgpack.txt
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/docs/serialization-msgpack.txt b/extensions/serialization-msgpack/src/docs/serialization-msgpack.txt
index ad50c08..3ae0fa4 100644
--- a/extensions/serialization-msgpack/src/docs/serialization-msgpack.txt
+++ b/extensions/serialization-msgpack/src/docs/serialization-msgpack.txt
@@ -25,6 +25,19 @@
source=extensions/serialization-msgpack/dev-status.xml
--------------
-// TODO Document usage of MessagePackSerialization
+`Serialization` service backed by http://msgpack.org/[MessagePack] that produce and consume binary payloads.
+See <<core-api-serialization>> and <<core-spi-serialization>>.
+
+include::../../build/docs/buildinfo/artifact.txt[]
+
// TODO Include sample model and its output from test code & resources
-// TODO Assembly - Serialization extension or sole Service, settings & adapters
+
+== Assembly ==
+
+Assembly is done using the provided Assembler:
+
+[snippet,java]
+----
+source=extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackValueCompositeSerializationTest.java
+tag=assembly
+----
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a93e2621/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackValueCompositeSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackValueCompositeSerializationTest.java b/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackValueCompositeSerializationTest.java
index 204f991..dd9291e 100644
--- a/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackValueCompositeSerializationTest.java
+++ b/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackValueCompositeSerializationTest.java
@@ -22,10 +22,14 @@ import org.apache.polygene.test.serialization.AbstractValueCompositeSerializatio
public class MessagePackValueCompositeSerializationTest extends AbstractValueCompositeSerializationTest
{
+ // START SNIPPET: assembly
@Override
public void assemble( ModuleAssembly module )
{
new MessagePackSerializationAssembler().assemble( module );
+ // END SNIPPET: assembly
super.assemble( module );
+ // START SNIPPET: assembly
}
+ // END SNIPPET: assembly
}
[22/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxjson/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializationAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxjson/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializationAssembler.java b/extensions/serialization-javaxjson/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializationAssembler.java
new file mode 100644
index 0000000..36b84d6
--- /dev/null
+++ b/extensions/serialization-javaxjson/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializationAssembler.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxjson;
+
+import org.apache.polygene.api.serialization.Deserializer;
+import org.apache.polygene.api.serialization.Serialization;
+import org.apache.polygene.api.serialization.Serializer;
+import org.apache.polygene.bootstrap.Assemblers;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.bootstrap.ServiceDeclaration;
+import org.apache.polygene.spi.serialization.JsonDeserializer;
+import org.apache.polygene.spi.serialization.JsonSerialization;
+import org.apache.polygene.spi.serialization.JsonSerializer;
+
+public class JavaxJsonSerializationAssembler extends Assemblers.VisibilityIdentity<JavaxJsonSerializationAssembler>
+{
+ private JavaxJsonSettings settings;
+
+ public JavaxJsonSerializationAssembler withJsonSettings( JavaxJsonSettings settings )
+ {
+ this.settings = settings;
+ return this;
+ }
+
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ ServiceDeclaration declaration = module.services( JavaxJsonSerializationService.class )
+ .withTypes( Serialization.class,
+ Serializer.class, Deserializer.class,
+ JsonSerialization.class,
+ JsonSerializer.class, JsonDeserializer.class )
+ .visibleIn( visibility() );
+ if( hasIdentity() )
+ {
+ declaration.identifiedBy( identity() );
+ }
+ if( settings != null )
+ {
+ declaration.setMetaInfo( settings );
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxjson/src/main/java/org/apache/polygene/serialization/javaxjson/package.html
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxjson/src/main/java/org/apache/polygene/serialization/javaxjson/package.html b/extensions/serialization-javaxjson/src/main/java/org/apache/polygene/serialization/javaxjson/package.html
new file mode 100644
index 0000000..43db1d9
--- /dev/null
+++ b/extensions/serialization-javaxjson/src/main/java/org/apache/polygene/serialization/javaxjson/package.html
@@ -0,0 +1,24 @@
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ ~
+ ~
+ -->
+<html>
+ <body>
+ <h2>javax.json Serialization.</h2>
+ </body>
+</html>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/CustomJsonAdapterTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/CustomJsonAdapterTest.java b/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/CustomJsonAdapterTest.java
new file mode 100644
index 0000000..bed0492
--- /dev/null
+++ b/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/CustomJsonAdapterTest.java
@@ -0,0 +1,180 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxjson;
+
+import java.time.LocalDate;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import javax.json.Json;
+import javax.json.JsonObject;
+import javax.json.JsonString;
+import javax.json.JsonValue;
+import org.apache.polygene.api.injection.scope.Service;
+import org.apache.polygene.api.property.Property;
+import org.apache.polygene.api.serialization.SerializationException;
+import org.apache.polygene.api.type.ValueCompositeType;
+import org.apache.polygene.api.type.ValueType;
+import org.apache.polygene.api.value.ValueBuilder;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.test.AbstractPolygeneTest;
+import org.junit.Test;
+
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+
+public class CustomJsonAdapterTest extends AbstractPolygeneTest
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ new JavaxJsonSerializationAssembler()
+ .withJsonSettings( new JavaxJsonSettings().withJsonAdapter( new CustomValueAdapter() )
+ .withJsonAdapter( new CustomStructureAdapter() ) )
+ .assemble( module );
+ module.values( SomeValue.class );
+ }
+
+ interface SomeValue
+ {
+ Property<CustomValue> customValue();
+
+ Property<CustomStructure> customStructure();
+ }
+
+ static class CustomValue
+ {
+ String state;
+
+ CustomValue( String state )
+ {
+ this.state = state;
+ }
+ }
+
+ static class CustomStructure
+ {
+ String foo;
+ LocalDate bar;
+
+ CustomStructure( String foo, LocalDate bar )
+ {
+ this.foo = foo;
+ this.bar = bar;
+ }
+ }
+
+ static class CustomValueAdapter implements JavaxJsonAdapter<CustomValue>
+ {
+ @Override
+ public Class<CustomValue> type() { return CustomValue.class; }
+
+ @Override
+ public JsonValue serialize( Object object, Function<Object, JsonValue> serializeFunction )
+ {
+ return JavaxJson.toJsonString( type().cast( object ).state );
+ }
+
+ @Override
+ public CustomValue deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ switch( json.getValueType() )
+ {
+ case STRING:
+ return new CustomValue( ( (JsonString) json ).getString() );
+ default:
+ throw new SerializationException( "Don't know how to deserialize CustomValue from " + json );
+ }
+ }
+ }
+
+ static class CustomStructureAdapter implements JavaxJsonAdapter<CustomStructure>
+ {
+ @Override
+ public Class<CustomStructure> type() { return CustomStructure.class; }
+
+ @Override
+ public JsonValue serialize( Object object, Function<Object, JsonValue> serializeFunction )
+ {
+ CustomStructure customStructure = type().cast( object );
+ return Json.createObjectBuilder()
+ .add( "foo", customStructure.foo )
+ .add( "bar", serializeFunction.apply( customStructure.bar ) )
+ .build();
+ }
+
+ @Override
+ public CustomStructure deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ if( json.getValueType() != JsonValue.ValueType.OBJECT )
+ {
+ throw new SerializationException( "Don't know how to deserialize CustomStructure from " + json );
+ }
+ JsonObject jsonObject = (JsonObject) json;
+ String foo = jsonObject.getString( "foo" );
+ LocalDate bar = (LocalDate) deserializeFunction.apply( jsonObject.get( "bar" ), ValueType.of( LocalDate.class ) );
+ return new CustomStructure( foo, bar );
+ }
+ }
+
+ @Service
+ private JavaxJsonSerialization serialization;
+
+ @Test
+ public void customJsonAdapterForPropertyValue()
+ {
+ ValueBuilder<SomeValue> builder = valueBuilderFactory.newValueBuilder( SomeValue.class );
+ builder.prototype().customValue().set( new CustomValue( "custom-value-state" ) );
+ builder.prototype().customStructure().set( new CustomStructure( "foo", LocalDate.of( 2017, 1, 1 ) ) );
+ SomeValue someValue = builder.newInstance();
+
+ System.out.println( someValue.toString() );
+
+ JsonValue serialized = serialization.toJson( someValue );
+ assertThat( serialized.getValueType(), is( JsonValue.ValueType.OBJECT ) );
+
+ JsonObject jsonObject = (JsonObject) serialized;
+ assertThat( jsonObject.getString( "customValue" ), equalTo( "custom-value-state" ) );
+ JsonObject structure = jsonObject.getJsonObject( "customStructure" );
+ assertThat( structure.getString( "foo" ), equalTo( "foo" ) );
+ assertThat( structure.getString( "bar" ), equalTo( "2017-01-01" ) );
+
+ SomeValue deserialized = serialization.fromJson( module, ValueCompositeType.of( SomeValue.class ), serialized );
+
+ assertThat( deserialized.customValue().get().state, equalTo( "custom-value-state" ) );
+ assertThat( deserialized.customStructure().get().foo, equalTo( "foo" ) );
+ assertThat( deserialized.customStructure().get().bar, equalTo( LocalDate.of( 2017, 1, 1 ) ) );
+ }
+
+ @Test
+ public void customJsonAdapterForDirectObject()
+ {
+ CustomValue customValueObject = new CustomValue( "custom-value-state" );
+ JsonValue serialized = serialization.toJson( customValueObject );
+ assertThat( serialized.getValueType(), is( JsonValue.ValueType.STRING ) );
+ JsonString jsonString = (JsonString) serialized;
+ assertThat( jsonString.getString(), equalTo( "custom-value-state" ) );
+
+ CustomStructure customStructureObject = new CustomStructure( "foo", LocalDate.of( 2017, 1, 1 ) );
+ serialized = serialization.toJson( customStructureObject );
+ assertThat( serialized.getValueType(), is( JsonValue.ValueType.OBJECT ) );
+ JsonObject jsonObject = (JsonObject) serialized;
+ assertThat( jsonObject.getString( "foo" ), equalTo( "foo" ) );
+ assertThat( jsonObject.getString( "bar" ), equalTo( "2017-01-01" ) );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonCollectionSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonCollectionSerializationTest.java b/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonCollectionSerializationTest.java
new file mode 100644
index 0000000..517b630
--- /dev/null
+++ b/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonCollectionSerializationTest.java
@@ -0,0 +1,24 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxjson;
+
+import org.apache.polygene.test.serialization.AbstractCollectionSerializationTest;
+
+public class JavaxJsonCollectionSerializationTest extends AbstractCollectionSerializationTest
+{
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonConfigurationDeserializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonConfigurationDeserializationTest.java b/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonConfigurationDeserializationTest.java
new file mode 100644
index 0000000..f054561
--- /dev/null
+++ b/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonConfigurationDeserializationTest.java
@@ -0,0 +1,24 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxjson;
+
+import org.apache.polygene.test.entity.AbstractConfigurationDeserializationTest;
+
+public class JavaxJsonConfigurationDeserializationTest extends AbstractConfigurationDeserializationTest
+{
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDateFormatSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDateFormatSerializationTest.java b/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDateFormatSerializationTest.java
new file mode 100644
index 0000000..7c0f510
--- /dev/null
+++ b/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDateFormatSerializationTest.java
@@ -0,0 +1,24 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxjson;
+
+import org.apache.polygene.test.serialization.AbstractDateFormatSerializationTest;
+
+public class JavaxJsonDateFormatSerializationTest extends AbstractDateFormatSerializationTest
+{
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonPlainValueSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonPlainValueSerializationTest.java b/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonPlainValueSerializationTest.java
new file mode 100644
index 0000000..00391e7
--- /dev/null
+++ b/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonPlainValueSerializationTest.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.serialization.javaxjson;
+
+import org.apache.polygene.test.serialization.AbstractPlainValueSerializationTest;
+
+public class JavaxJsonPlainValueSerializationTest extends AbstractPlainValueSerializationTest
+{
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonValueCompositeSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonValueCompositeSerializationTest.java b/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonValueCompositeSerializationTest.java
new file mode 100644
index 0000000..5fe4f5f
--- /dev/null
+++ b/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonValueCompositeSerializationTest.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxjson;
+
+import java.io.StringReader;
+import javax.json.Json;
+import javax.json.JsonObject;
+import javax.json.JsonValue;
+import org.apache.polygene.api.injection.scope.Service;
+import org.apache.polygene.api.unitofwork.UnitOfWork;
+import org.apache.polygene.spi.serialization.JsonSerialization;
+import org.apache.polygene.test.serialization.AbstractValueCompositeSerializationTest;
+import org.junit.Test;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.junit.Assert.assertThat;
+
+public class JavaxJsonValueCompositeSerializationTest extends AbstractValueCompositeSerializationTest
+{
+ @Service
+ private JsonSerialization jsonSerialization;
+
+ @Test
+ public void valueCompositeJsonEquality()
+ {
+ try( UnitOfWork uow = unitOfWorkFactory.newUnitOfWork() )
+ {
+ Some some = buildSomeValue( moduleInstance, uow, "42" );
+
+ // Serialize using injected service
+ JsonValue jsonState = jsonSerialization.toJson( some );
+ String stateString = jsonState.toString();
+ System.out.println( jsonState.toString() );
+
+ // Deserialize using Module API
+ Some some2 = moduleInstance.newValueFromSerializedState( Some.class, stateString );
+
+ assertThat( "Value equality", some, equalTo( some2 ) );
+
+ JsonObject jsonState2 = Json.createReader( new StringReader( some2.toString() ) ).readObject();
+
+ assertThat( "JSON equality", jsonState, equalTo( jsonState2 ) );
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxjson/src/test/resources/configtest.json
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxjson/src/test/resources/configtest.json b/extensions/serialization-javaxjson/src/test/resources/configtest.json
new file mode 100644
index 0000000..4c5600b
--- /dev/null
+++ b/extensions/serialization-javaxjson/src/test/resources/configtest.json
@@ -0,0 +1,8 @@
+{
+ "identity": "configtest",
+ "host": {
+ "ip": "12.23.34.45",
+ "port": 1234
+ },
+ "name": "main"
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxxml/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/build.gradle b/extensions/serialization-javaxxml/build.gradle
new file mode 100644
index 0000000..4c095f9
--- /dev/null
+++ b/extensions/serialization-javaxxml/build.gradle
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+apply plugin: 'polygene-extension'
+
+description = "Apache Polygene\u2122 javax.xml Serialization Extension"
+
+jar { manifest { name = "Apache Polygene\u2122 Extension - Serialization - javax.xml" } }
+
+dependencies {
+ api polygene.core.bootstrap
+
+ runtimeOnly polygene.core.runtime
+
+ testImplementation polygene.core.testsupport
+ testImplementation libraries.xmlunit
+
+ testRuntimeOnly libraries.logback
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxxml/dev-status.xml
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/dev-status.xml b/extensions/serialization-javaxxml/dev-status.xml
new file mode 100644
index 0000000..81841be
--- /dev/null
+++ b/extensions/serialization-javaxxml/dev-status.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ ~
+ ~
+ -->
+<module xmlns="http://polygene.apache.org/schemas/2008/dev-status/1"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://polygene.apache.org/schemas/2008/dev-status/1
+ http://polygene.apache.org/schemas/2008/dev-status/1/dev-status.xsd">
+ <status>
+ <!--none,early,beta,stable,mature-->
+ <codebase>early</codebase>
+
+ <!-- none, brief, good, complete -->
+ <documentation>none</documentation>
+
+ <!-- none, some, good, complete -->
+ <unittests>good</unittests>
+ </status>
+ <licenses>
+ <license>ALv2</license>
+ </licenses>
+</module>
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxxml/src/docs/serialization-javaxxml.txt
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/docs/serialization-javaxxml.txt b/extensions/serialization-javaxxml/src/docs/serialization-javaxxml.txt
new file mode 100644
index 0000000..6fe6d75
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/docs/serialization-javaxxml.txt
@@ -0,0 +1,30 @@
+///////////////////////////////////////////////////////////////
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+///////////////////////////////////////////////////////////////
+
+[[extension-serialization-javaxxml,javax.xml serialization]]
+= javax.xml serialization =
+
+[devstatus]
+--------------
+source=extensions/serialization-javaxxml/dev-status.xml
+--------------
+
+// TODO Document usage of XmlSerialization
+// TODO Include sample model and its output from test code & resources
+// TODO Assembly - Serialization extension or sole Service, settings & adapters
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXml.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXml.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXml.java
new file mode 100644
index 0000000..3289d30
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXml.java
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxxml;
+
+import java.util.Optional;
+import java.util.Spliterator;
+import java.util.Spliterators;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * javax.xml utilities.
+ */
+public class JavaxXml
+{
+ /**
+ * Find child elements.
+ *
+ * @param parent the parent node
+ * @return a stream of elements
+ */
+ public static Stream<Element> childElements( Node parent )
+ {
+ return toStream( parent.getChildNodes() ).filter( JavaxXml::isElement )
+ .map( JavaxXml::castToElement );
+ }
+
+ /**
+ * Find the first child element.
+ *
+ * @param parent the parent node
+ * @return an optional element
+ */
+ public static Optional<Element> firstChildElement( Node parent )
+ {
+ return childElements( parent ).findFirst();
+ }
+
+ /**
+ * Find child elements named {@literal tagName}.
+ *
+ * @param parent the parent node
+ * @param tagName the tag name
+ * @return a stream of elements named {@literal tagName}
+ */
+ public static Stream<Element> childElementsNamed( Node parent, String tagName )
+ {
+ return childElements( parent ).filter( element -> tagName.equals( element.getTagName() ) );
+ }
+
+ /**
+ * Find the first child element named {@literal tagName}.
+ *
+ * @param parent the parent node
+ * @param tagName the tag name
+ * @return an optional element named {@literal tagName}
+ */
+ public static Optional<Element> firstChildElementNamed( Node parent, String tagName )
+ {
+ return childElementsNamed( parent, tagName ).findFirst();
+ }
+
+ /**
+ * Find child nodes holding state.
+ *
+ * @param parent the parent node
+ * @return a stream or child state nodes
+ */
+ public static Stream<Node> stateChildNodes( Node parent )
+ {
+ return toStream( parent.getChildNodes() ).filter( JavaxXml::isStateNode );
+ }
+
+ /**
+ * Find the first child node holding state.
+ *
+ * @param parent the parent node
+ * @return an optional child state node
+ */
+ public static Optional<Node> firstStateChildNode( Node parent )
+ {
+ return stateChildNodes( parent ).findFirst();
+ }
+
+ /**
+ * Test if a node holds state.
+ *
+ * Types of nodes holding state:
+ * <ul>
+ * <li>{@link Node#ELEMENT_NODE}</li>
+ * <li>{@link Node#CDATA_SECTION_NODE}</li>
+ * <li>{@link Node#TEXT_NODE}</li>
+ * </ul>
+ *
+ * @param node the node
+ * @return {@literal true} if {@literal node} holds state
+ */
+ public static boolean isStateNode( Node node )
+ {
+ switch( node.getNodeType() )
+ {
+ case Node.ELEMENT_NODE:
+ case Node.CDATA_SECTION_NODE:
+ case Node.TEXT_NODE:
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ private static boolean isElement( Node node )
+ {
+ return node.getNodeType() == Node.ELEMENT_NODE;
+ }
+
+ private static Element castToElement( Node node )
+ {
+ return (Element) node;
+ }
+
+ private static Stream<Node> toStream( NodeList nodeList )
+ {
+ return StreamSupport.stream( new Spliterators.AbstractSpliterator<Node>( Long.MAX_VALUE, Spliterator.ORDERED )
+ {
+ private int nextIndex = 0;
+
+ @Override
+ public boolean tryAdvance( Consumer<? super Node> action )
+ {
+ if( nextIndex >= nodeList.getLength() )
+ {
+ return false;
+ }
+ action.accept( nodeList.item( nextIndex ) );
+ nextIndex++;
+ return true;
+ }
+ }, false );
+ }
+
+ private JavaxXml() {}
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlAdapter.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlAdapter.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlAdapter.java
new file mode 100644
index 0000000..3761198
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlAdapter.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxxml;
+
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import org.apache.polygene.api.type.ValueType;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+
+/**
+ * Adapter for XML (de)serialization.
+ *
+ * @param <T> the adapted type
+ */
+public interface JavaxXmlAdapter<T>
+{
+ /**
+ * @return the adapted type
+ */
+ Class<T> type();
+
+ /**
+ * Serialize.
+ *
+ * @param document the Document to use as a Node factory
+ * @param object Object to serialize, never null
+ * @param serializationFunction Serialization function for nested structure serialization
+ * @return Serialized XML representation
+ */
+ Node serialize( Document document, Object object, Function<Object, Node> serializationFunction );
+
+ /**
+ * Deserialize.
+ *
+ * @param node XML to deserialize from, never null
+ * @param deserializationFunction Deserialization function for nested structure deserialization
+ * @return Deserialized object
+ */
+ T deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction );
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlAdapters.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlAdapters.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlAdapters.java
new file mode 100644
index 0000000..273789d
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlAdapters.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxxml;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.type.ValueType;
+
+import static org.apache.polygene.api.type.HasTypesCollectors.closestType;
+
+@Mixins( JavaxXmlAdapters.Mixin.class )
+public interface JavaxXmlAdapters
+{
+ void registerAdapter( ValueType valueType, JavaxXmlAdapter<?> adapter );
+
+ <T> JavaxXmlAdapter<T> adapterFor( ValueType valueType );
+
+ default <T> JavaxXmlAdapter<T> adapterFor( Class<T> type )
+ {
+ return adapterFor( ValueType.of( type ) );
+ }
+
+ class Mixin implements JavaxXmlAdapters
+ {
+ private Map<ValueType, JavaxXmlAdapter<?>> adapters = new LinkedHashMap<>();
+
+ @Override
+ public void registerAdapter( final ValueType valueType, final JavaxXmlAdapter<?> adapter )
+ {
+ adapters.put( valueType, adapter );
+ }
+
+ @Override
+ public <T> JavaxXmlAdapter<T> adapterFor( final ValueType valueType )
+ {
+ return castAdapter( adapters.keySet().stream()
+ .collect( closestType( valueType ) )
+ .map( adapters::get )
+ .orElse( null ) );
+ }
+
+ @SuppressWarnings( "unchecked" )
+ private <T> JavaxXmlAdapter<T> castAdapter( JavaxXmlAdapter<?> adapter )
+ {
+ return (JavaxXmlAdapter<T>) adapter;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
new file mode 100644
index 0000000..992e000
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
@@ -0,0 +1,325 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxxml;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.function.Predicate;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.apache.polygene.api.association.AssociationDescriptor;
+import org.apache.polygene.api.entity.EntityReference;
+import org.apache.polygene.api.injection.scope.This;
+import org.apache.polygene.api.injection.scope.Uses;
+import org.apache.polygene.api.property.PropertyDescriptor;
+import org.apache.polygene.api.serialization.SerializationException;
+import org.apache.polygene.api.service.ServiceDescriptor;
+import org.apache.polygene.api.structure.ModuleDescriptor;
+import org.apache.polygene.api.type.CollectionType;
+import org.apache.polygene.api.type.EnumType;
+import org.apache.polygene.api.type.MapType;
+import org.apache.polygene.api.type.ValueCompositeType;
+import org.apache.polygene.api.type.ValueType;
+import org.apache.polygene.api.value.ValueBuilder;
+import org.apache.polygene.api.value.ValueDescriptor;
+import org.apache.polygene.spi.serialization.AbstractTextDeserializer;
+import org.apache.polygene.spi.serialization.XmlDeserializer;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static java.util.Collections.unmodifiableList;
+import static java.util.Collections.unmodifiableMap;
+import static java.util.Collections.unmodifiableSet;
+import static org.apache.polygene.api.util.Collectors.toMapWithNullValues;
+
+public class JavaxXmlDeserializer extends AbstractTextDeserializer implements XmlDeserializer
+{
+ private static final String NULL_ELEMENT_NAME = "null";
+
+ @This
+ private JavaxXmlAdapters adapters;
+
+ @Uses
+ private ServiceDescriptor descriptor;
+
+ @Override
+ public <T> T fromXml( ModuleDescriptor module, ValueType valueType, Document state )
+ {
+ Optional<Element> stateElement = JavaxXml.firstChildElementNamed( state, getSettings().getRootTagName() );
+ if( stateElement.isPresent() )
+ {
+ Optional<Node> stateNode = JavaxXml.firstStateChildNode( stateElement.get() );
+ if( stateNode.isPresent() )
+ {
+ return doDeserialize( module, valueType, stateNode.get() );
+ }
+ }
+ return null;
+ }
+
+ @SuppressWarnings( "unchecked" )
+ private <T> T doDeserialize( ModuleDescriptor module, ValueType valueType, Node xml )
+ {
+ if( xml == null )
+ {
+ return valueType.hasType( String.class ) ? (T) "" : null;
+ }
+ if( xml.getNodeType() == Node.ELEMENT_NODE && NULL_ELEMENT_NAME.equals( ( (Element) xml ).getTagName() ) )
+ {
+ return null;
+ }
+ JavaxXmlAdapter<?> adapter = adapters.adapterFor( valueType );
+ if( adapter != null )
+ {
+ return (T) adapter.deserialize( xml, ( element, type ) -> doDeserialize( module, type, element ) );
+ }
+ if( EnumType.class.isAssignableFrom( valueType.getClass() ) )
+ {
+ return (T) Enum.valueOf( (Class) valueType.primaryType(), xml.getNodeValue() );
+ }
+ if( CollectionType.class.isAssignableFrom( valueType.getClass() ) )
+ {
+ return (T) deserializeCollection( module, (CollectionType) valueType, xml );
+ }
+ if( MapType.class.isAssignableFrom( valueType.getClass() ) )
+ {
+ return (T) deserializeMap( module, (MapType) valueType, xml );
+ }
+ if( ValueCompositeType.class.isAssignableFrom( valueType.getClass() ) )
+ {
+ return (T) deserializeValueComposite( module, (ValueCompositeType) valueType, xml );
+ }
+ return (T) doGuessDeserialize( module, valueType, xml );
+ }
+
+ private Object deserializeValueComposite( ModuleDescriptor module, ValueCompositeType valueType, Node xml )
+ {
+ Optional<String> typeInfo = getTypeInfo( xml );
+ if( typeInfo.isPresent() )
+ {
+ ValueDescriptor descriptor = module.valueDescriptor( typeInfo.get() );
+ if( descriptor == null )
+ {
+ String typeInfoName = getSettings().getTypeInfoTagName();
+ throw new SerializationException(
+ typeInfoName + ": " + typeInfo.get() + " could not be resolved while deserializing " + xml );
+ }
+ valueType = descriptor.valueType();
+ }
+ ValueBuilder builder = module.instance().newValueBuilderWithState(
+ valueType.primaryType(),
+ propertyFunction( module, xml ),
+ associationFunction( module, xml ),
+ manyAssociationFunction( module, xml ),
+ namedAssociationFunction( module, xml ) );
+ return builder.newInstance();
+ }
+
+ private Function<PropertyDescriptor, Object> propertyFunction( ModuleDescriptor module, Node xml )
+ {
+ return property ->
+ {
+ Optional<Element> element = JavaxXml.firstChildElementNamed( xml, property.qualifiedName().name() );
+ if( element.isPresent() )
+ {
+ Node valueNode = JavaxXml.firstStateChildNode( element.get() ).orElse( null );
+ Object value = doDeserialize( module, property.valueType(), valueNode );
+ if( property.isImmutable() )
+ {
+ if( value instanceof Set )
+ {
+ return unmodifiableSet( (Set<?>) value );
+ }
+ else if( value instanceof List )
+ {
+ return unmodifiableList( (List<?>) value );
+ }
+ else if( value instanceof Map )
+ {
+ return unmodifiableMap( (Map<?, ?>) value );
+ }
+ }
+ return value;
+ }
+ return property.resolveInitialValue( module );
+ };
+ }
+
+ private Function<AssociationDescriptor, EntityReference> associationFunction( ModuleDescriptor module, Node xml )
+ {
+ return association ->
+ (EntityReference) JavaxXml.firstChildElementNamed( xml, association.qualifiedName().name() )
+ .map( element -> doDeserialize( module,
+ ValueType.ENTITY_REFERENCE,
+ JavaxXml.firstStateChildNode( element )
+ .orElse( null ) ) )
+ .orElse( null );
+ }
+
+ private Function<AssociationDescriptor, Stream<EntityReference>> manyAssociationFunction( ModuleDescriptor module,
+ Node xml )
+ {
+ return association ->
+ JavaxXml.firstChildElementNamed( xml, association.qualifiedName().name() )
+ .map( element -> (List) doDeserialize( module,
+ ENTITY_REF_LIST_VALUE_TYPE,
+ JavaxXml.firstStateChildNode( element )
+ .orElse( null ) ) )
+ .map( List::stream )
+ .orElse( Stream.empty() );
+ }
+
+ private Function<AssociationDescriptor, Stream<Map.Entry<String, EntityReference>>> namedAssociationFunction(
+ ModuleDescriptor module, Node xml )
+ {
+ return association ->
+ (Stream) JavaxXml.firstChildElementNamed( xml, association.qualifiedName().name() )
+ .map( element -> (Map) doDeserialize( module,
+ ENTITY_REF_MAP_VALUE_TYPE,
+ JavaxXml.firstStateChildNode( element )
+ .orElse( null ) ) )
+ .map( Map::entrySet ).map( Set::stream )
+ .orElse( Stream.empty() );
+ }
+
+ @SuppressWarnings( "unchecked" )
+ private Collection deserializeCollection( ModuleDescriptor module, CollectionType collectionType, Node xml )
+ {
+ Supplier<Collection> collectionSupplier = () -> collectionType.isSet()
+ ? new LinkedHashSet<>()
+ : new ArrayList<>();
+ if( !xml.hasChildNodes() )
+ {
+ return collectionSupplier.get();
+ }
+ return JavaxXml
+ .childElements( xml )
+ .map( element ->
+ {
+ if( getSettings().getCollectionElementTagName().equals( element.getTagName() ) )
+ {
+ return doDeserialize( module, collectionType.collectedType(),
+ JavaxXml.firstStateChildNode( element ).get() );
+ }
+ return doDeserialize( module, collectionType.collectedType(), element );
+ } )
+ .collect( Collectors.toCollection( collectionSupplier ) );
+ }
+
+ @SuppressWarnings( "unchecked" )
+ private Map deserializeMap( ModuleDescriptor module, MapType mapType, Node xml )
+ {
+ if( !xml.hasChildNodes() )
+ {
+ return new LinkedHashMap<>();
+ }
+ Predicate<Element> complexMapping = element -> getSettings().getMapEntryTagName().equals( element.getTagName() )
+ && JavaxXml.firstChildElementNamed( element, "key" )
+ .isPresent();
+ // This allows deserializing mixed simple/complex mappings for a given map
+ return JavaxXml.childElements( xml ).map(
+ element ->
+ {
+ if( complexMapping.test( element ) )
+ {
+ Node keyNode = JavaxXml.firstChildElementNamed( element, "key" )
+ .flatMap( JavaxXml::firstStateChildNode )
+ .get();
+ Optional<Node> valueNode = JavaxXml.firstChildElementNamed( element, "value" )
+ .flatMap( JavaxXml::firstStateChildNode );
+ Object key = doDeserialize( module, mapType.keyType(), keyNode );
+ Object value = valueNode.map( node -> doDeserialize( module, mapType.valueType(), node ) )
+ .orElse( null );
+ return new HashMap.SimpleImmutableEntry<>( key, value );
+ }
+ String key = element.getTagName();
+ Object value = JavaxXml.firstStateChildNode( element )
+ .map( node -> doDeserialize( module, mapType.valueType(), node ) )
+ .orElse( null );
+ return (Map.Entry) new HashMap.SimpleImmutableEntry<>( key, value );
+ }
+ ).collect( toMapWithNullValues( LinkedHashMap::new ) );
+ }
+
+ private Object doGuessDeserialize( ModuleDescriptor module, ValueType valueType, Node xml )
+ {
+ // TODO Could do better by detecting <collection/>, <map/> and <value/>
+ Optional<String> typeInfo = getTypeInfo( xml );
+ if( typeInfo.isPresent() )
+ {
+ ValueDescriptor valueDescriptor = module.valueDescriptor( typeInfo.get() );
+ if( valueDescriptor != null )
+ {
+ return deserializeValueComposite( module, valueDescriptor.valueType(), xml );
+ }
+ }
+ if( xml.getNodeType() == Node.CDATA_SECTION_NODE )
+ {
+ return deserializeBase64( xml.getNodeValue() );
+ }
+ throw new SerializationException( "Don't know how to deserialize " + valueType + " from " + xml );
+ }
+
+ private Object deserializeBase64( String inputString )
+ {
+ byte[] bytes = inputString.getBytes( UTF_8 );
+ bytes = Base64.getDecoder().decode( bytes );
+ try( ObjectInputStream oin = new ObjectInputStream( new ByteArrayInputStream( bytes ) ) )
+ {
+ return oin.readObject();
+ }
+ catch( IOException | ClassNotFoundException ex )
+ {
+ throw new SerializationException( "Unable to deserialize Base64 serialized " + inputString, ex );
+ }
+ }
+
+ private Optional<String> getTypeInfo( Node xml )
+ {
+ if( xml.getNodeType() != Node.ELEMENT_NODE )
+ {
+ return Optional.empty();
+ }
+ String typeInfo = ( (Element) xml ).getAttribute( getSettings().getTypeInfoTagName() );
+ if( typeInfo.isEmpty() )
+ {
+ return Optional.empty();
+ }
+ return Optional.of( typeInfo );
+ }
+
+ private JavaxXmlSettings getSettings()
+ {
+ return JavaxXmlSettings.orDefault( descriptor.metaInfo( JavaxXmlSettings.class ) );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerialization.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerialization.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerialization.java
new file mode 100644
index 0000000..529bdee
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerialization.java
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxxml;
+
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.spi.serialization.XmlSerialization;
+
+/**
+ * javax.xml state serialization.
+ *
+ * The XML representations consumed and produced by this service are, by default, verbose, and safe to deserialize.
+ * This is because the default mapping is purely structural.
+ * You can customize the XML representations using {@link JavaxXmlSettings} and {@link JavaxXmlAdapters}.
+ *
+ * The following describe how state is represented by default.
+ *
+ * Because a valid XML document can only contain a single node and it must be an element, all
+ * {@link org.w3c.dom.Document}s have a root element {@literal <state/>}. This serialization implementation
+ * also impose that the root element can only contain a single node, of any type.
+ *
+ * {@literal null} is represented as {@literal <null/>}.
+ * Plain values are represented as {@link org.w3c.dom.Text} nodes.
+ * Iterables and Streams are represented as {@literal <collection/>} {@link org.w3c.dom.Element}s.
+ * Maps are represented as {@literal <dictionary/>} {@link org.w3c.dom.Element}s.
+ *
+ * This is how a {@literal null} plain value is represented: {@literal <state><null/></state>}.
+ * And a plain {@literal LocalDate}: {@literal <state>2017-01-01</state>}
+ *
+ * This is how a fictional value including a collection and a map is represented:
+ * <code>
+ * <state>
+ * <stringProperty>and it's value</stringProperty>
+ * <bigDecimalProperty>4.22376931348623157E+310</bigDecimalProperty>
+ * <nullProperty><null/></nullProperty>
+ * <booleanProperty>false</booleanProperty>
+ * <stringCollectionProperty>
+ * <collection>
+ * item1
+ * item2 <!-- As multiple text nodes -->
+ * </collection>
+ * </stringCollectionProperty>
+ * <mapProperty>
+ * <map>
+ * <foo>bar</foo>
+ * <bazar>cathedral</bazar>
+ * </map>
+ * </mapProperty>
+ * <complexKeyMapProperty>
+ * <map>
+ * <entry>
+ * <key>
+ * <foo>bar</foo>
+ * <bazar>cathedral</bazar>
+ * </key>
+ * <value>23</value>
+ * </entry>
+ * <entry>
+ * <key>
+ * <foo>baz</foo>
+ * <bazar>bar</bazar>
+ * </key>
+ * <value>42</value>
+ * </entry>
+ * </map>
+ * </complexKeyMapProperty>
+ * </state>
+ * </code>
+ *
+ */
+@Mixins( { JavaxXmlSerializer.class, JavaxXmlDeserializer.class } )
+public interface JavaxXmlSerialization extends XmlSerialization
+{
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializationAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializationAssembler.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializationAssembler.java
new file mode 100644
index 0000000..b97bf12
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializationAssembler.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxxml;
+
+import org.apache.polygene.api.serialization.Deserializer;
+import org.apache.polygene.api.serialization.Serialization;
+import org.apache.polygene.api.serialization.Serializer;
+import org.apache.polygene.bootstrap.Assemblers;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.bootstrap.ServiceDeclaration;
+import org.apache.polygene.spi.serialization.XmlDeserializer;
+import org.apache.polygene.spi.serialization.XmlSerialization;
+import org.apache.polygene.spi.serialization.XmlSerializer;
+
+public class JavaxXmlSerializationAssembler extends Assemblers.VisibilityIdentity<JavaxXmlSerializationAssembler>
+{
+ private JavaxXmlSettings settings;
+
+ public JavaxXmlSerializationAssembler withXmlSettings( JavaxXmlSettings settings )
+ {
+ this.settings = settings;
+ return this;
+ }
+
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ ServiceDeclaration declaration = module.services( JavaxXmlSerializationService.class )
+ .withTypes( Serialization.class,
+ Serializer.class, Deserializer.class,
+ XmlSerialization.class,
+ XmlSerializer.class, XmlDeserializer.class )
+ .visibleIn( visibility() );
+ if( hasIdentity() )
+ {
+ declaration.identifiedBy( identity() );
+ }
+ if( settings != null )
+ {
+ declaration.setMetaInfo( settings );
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializationService.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializationService.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializationService.java
new file mode 100644
index 0000000..3917340
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializationService.java
@@ -0,0 +1,372 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxxml;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.OffsetDateTime;
+import java.time.Period;
+import java.time.ZonedDateTime;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import org.apache.polygene.api.entity.EntityReference;
+import org.apache.polygene.api.identity.Identity;
+import org.apache.polygene.api.identity.StringIdentity;
+import org.apache.polygene.api.injection.scope.This;
+import org.apache.polygene.api.injection.scope.Uses;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.service.ServiceActivation;
+import org.apache.polygene.api.service.ServiceDescriptor;
+import org.apache.polygene.api.type.ValueType;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+
+@Mixins( JavaxXmlSerializationService.Activation.class )
+public interface JavaxXmlSerializationService extends JavaxXmlSerialization, ServiceActivation
+{
+ class Activation implements ServiceActivation
+ {
+ @Uses
+ private ServiceDescriptor descriptor;
+
+ @This
+ private JavaxXmlAdapters adapters;
+
+ private boolean registrationDone = false;
+
+ @Override
+ public void activateService()
+ {
+ if( !registrationDone )
+ {
+ registerCustomAdapters();
+ registerBaseAdapters();
+ registrationDone = true;
+ }
+ }
+
+ @Override
+ public void passivateService() {}
+
+ private void registerCustomAdapters()
+ {
+ JavaxXmlSettings.orDefault( descriptor.metaInfo( JavaxXmlSettings.class ) )
+ .getAdapters()
+ .forEach( ( valueType, adapter ) -> adapters.registerAdapter( valueType, adapter ) );
+ }
+
+ private void registerBaseAdapters()
+ {
+ // Primitive Value types
+ adapters.registerAdapter( ValueType.STRING, new StringAdapter() );
+ adapters.registerAdapter( ValueType.CHARACTER, new CharacterAdapter() );
+ adapters.registerAdapter( ValueType.BOOLEAN, new BooleanAdapter() );
+ adapters.registerAdapter( ValueType.INTEGER, new IntegerAdapter() );
+ adapters.registerAdapter( ValueType.LONG, new LongAdapter() );
+ adapters.registerAdapter( ValueType.SHORT, new ShortAdapter() );
+ adapters.registerAdapter( ValueType.BYTE, new ByteAdapter() );
+ adapters.registerAdapter( ValueType.FLOAT, new FloatAdapter() );
+ adapters.registerAdapter( ValueType.DOUBLE, new DoubleAdapter() );
+
+ // Number types
+ adapters.registerAdapter( ValueType.BIG_DECIMAL, new BigDecimalAdapter() );
+ adapters.registerAdapter( ValueType.BIG_INTEGER, new BigIntegerAdapter() );
+
+ // Date types
+ adapters.registerAdapter( ValueType.INSTANT, new InstantAdapter() );
+ adapters.registerAdapter( ValueType.ZONED_DATE_TIME, new ZonedDateTimeAdapter() );
+ adapters.registerAdapter( ValueType.OFFSET_DATE_TIME, new OffsetDateTimeAdapter() );
+ adapters.registerAdapter( ValueType.LOCAL_DATE_TIME, new LocalDateTimeAdapter() );
+ adapters.registerAdapter( ValueType.LOCAL_DATE, new LocalDateAdapter() );
+ adapters.registerAdapter( ValueType.LOCAL_TIME, new LocalTimeAdapter() );
+ adapters.registerAdapter( ValueType.DURATION, new DurationAdapter() );
+ adapters.registerAdapter( ValueType.PERIOD, new PeriodAdapter() );
+
+ // Other supported types
+ adapters.registerAdapter( ValueType.IDENTITY, new IdentityAdapter() );
+ adapters.registerAdapter( ValueType.ENTITY_REFERENCE, new EntityReferenceAdapter() );
+ }
+
+ private static abstract class ToStringTextNodeAdapter<T> implements JavaxXmlAdapter<T>
+ {
+ @Override
+ public Node serialize( Document document, Object object, Function<Object, Node> serializationFunction )
+ {
+ return document.createTextNode( object.toString() );
+ }
+ }
+
+ private static class StringAdapter extends ToStringTextNodeAdapter<String>
+ {
+ @Override
+ public Class<String> type() { return String.class; }
+
+ @Override
+ public String deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return node.getNodeValue();
+ }
+ }
+
+ private static class CharacterAdapter extends ToStringTextNodeAdapter<Character>
+ {
+ @Override
+ public Class<Character> type() { return Character.class; }
+
+ @Override
+ public Character deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ String string = node.getNodeValue();
+ return string.isEmpty() ? null : string.charAt( 0 );
+ }
+ }
+
+ private static class BooleanAdapter extends ToStringTextNodeAdapter<Boolean>
+ {
+ @Override
+ public Class<Boolean> type() { return Boolean.class; }
+
+ @Override
+ public Boolean deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return Boolean.valueOf( node.getNodeValue() );
+ }
+ }
+
+ private static class IntegerAdapter extends ToStringTextNodeAdapter<Integer>
+ {
+ @Override
+ public Class<Integer> type() { return Integer.class; }
+
+ @Override
+ public Integer deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return Integer.valueOf( node.getNodeValue() );
+ }
+ }
+
+ private static class LongAdapter extends ToStringTextNodeAdapter<Long>
+ {
+ @Override
+ public Class<Long> type() { return Long.class; }
+
+ @Override
+ public Long deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return Long.valueOf( node.getNodeValue() );
+ }
+ }
+
+ private static class ShortAdapter extends ToStringTextNodeAdapter<Short>
+ {
+ @Override
+ public Class<Short> type() { return Short.class; }
+
+ @Override
+ public Short deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return Short.valueOf( node.getNodeValue() );
+ }
+ }
+
+ private static class ByteAdapter extends ToStringTextNodeAdapter<Byte>
+ {
+ @Override
+ public Class<Byte> type() { return Byte.class; }
+
+ @Override
+ public Byte deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return Byte.valueOf( node.getNodeValue() );
+ }
+ }
+
+ private static class FloatAdapter extends ToStringTextNodeAdapter<Float>
+ {
+ @Override
+ public Class<Float> type() { return Float.class; }
+
+ @Override
+ public Float deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return Float.valueOf( node.getNodeValue() );
+ }
+ }
+
+ private static class DoubleAdapter extends ToStringTextNodeAdapter<Double>
+ {
+ @Override
+ public Class<Double> type() { return Double.class; }
+
+ @Override
+ public Double deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return Double.valueOf( node.getNodeValue() );
+ }
+ }
+
+ private static class BigDecimalAdapter extends ToStringTextNodeAdapter<BigDecimal>
+ {
+ @Override
+ public Class<BigDecimal> type() { return BigDecimal.class; }
+
+ @Override
+ public BigDecimal deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return new BigDecimal( node.getNodeValue() );
+ }
+ }
+
+ private static class BigIntegerAdapter extends ToStringTextNodeAdapter<BigInteger>
+ {
+ @Override
+ public Class<BigInteger> type() { return BigInteger.class; }
+
+ @Override
+ public BigInteger deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return new BigInteger( node.getNodeValue() );
+ }
+ }
+
+ private static class InstantAdapter extends ToStringTextNodeAdapter<Instant>
+ {
+ @Override
+ public Class<Instant> type() { return Instant.class; }
+
+ @Override
+ public Instant deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return Instant.parse( node.getNodeValue() );
+ }
+ }
+
+ private static class ZonedDateTimeAdapter extends ToStringTextNodeAdapter<ZonedDateTime>
+ {
+ @Override
+ public Class<ZonedDateTime> type() { return ZonedDateTime.class; }
+
+ @Override
+ public ZonedDateTime deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return ZonedDateTime.parse( node.getNodeValue() );
+ }
+ }
+
+ private static class OffsetDateTimeAdapter extends ToStringTextNodeAdapter<OffsetDateTime>
+ {
+ @Override
+ public Class<OffsetDateTime> type() { return OffsetDateTime.class; }
+
+ @Override
+ public OffsetDateTime deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return OffsetDateTime.parse( node.getNodeValue() );
+ }
+ }
+
+ private static class LocalDateTimeAdapter extends ToStringTextNodeAdapter<LocalDateTime>
+ {
+ @Override
+ public Class<LocalDateTime> type() { return LocalDateTime.class; }
+
+ @Override
+ public LocalDateTime deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return LocalDateTime.parse( node.getNodeValue() );
+ }
+ }
+
+ private static class LocalDateAdapter extends ToStringTextNodeAdapter<LocalDate>
+ {
+ @Override
+ public Class<LocalDate> type() { return LocalDate.class; }
+
+ @Override
+ public LocalDate deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return LocalDate.parse( node.getNodeValue() );
+ }
+ }
+
+ private static class LocalTimeAdapter extends ToStringTextNodeAdapter<LocalTime>
+ {
+ @Override
+ public Class<LocalTime> type() { return LocalTime.class; }
+
+ @Override
+ public LocalTime deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return LocalTime.parse( node.getNodeValue() );
+ }
+ }
+
+ private static class DurationAdapter extends ToStringTextNodeAdapter<Duration>
+ {
+ @Override
+ public Class<Duration> type() { return Duration.class; }
+
+ @Override
+ public Duration deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return Duration.parse( node.getNodeValue() );
+ }
+ }
+
+ private static class PeriodAdapter extends ToStringTextNodeAdapter<Period>
+ {
+ @Override
+ public Class<Period> type() { return Period.class; }
+
+ @Override
+ public Period deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return Period.parse( node.getNodeValue() );
+ }
+ }
+
+ private static class IdentityAdapter extends ToStringTextNodeAdapter<Identity>
+ {
+ @Override
+ public Class<Identity> type() { return Identity.class; }
+
+ @Override
+ public Identity deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return StringIdentity.fromString( node.getNodeValue() );
+ }
+ }
+
+ private static class EntityReferenceAdapter extends ToStringTextNodeAdapter<EntityReference>
+ {
+ @Override
+ public Class<EntityReference> type() { return EntityReference.class; }
+
+ @Override
+ public EntityReference deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
+ {
+ return EntityReference.parseEntityReference( node.getNodeValue() );
+ }
+ }
+ }
+}
[13/50] [abbrv] polygene-java git commit: Reindexer was also missing
ValueSerialization in tests.
Posted by pa...@apache.org.
Reindexer was also missing ValueSerialization in tests.
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/1ec0faa4
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/1ec0faa4
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/1ec0faa4
Branch: refs/heads/serialization-3.0
Commit: 1ec0faa4122c8ea0c0f3bf75865113334b7faddf
Parents: b8aea70
Author: niclas <ni...@spicter.com>
Authored: Sun Mar 12 00:03:57 2017 +0800
Committer: niclas <ni...@spicter.com>
Committed: Sun Mar 12 00:03:57 2017 +0800
----------------------------------------------------------------------
extensions/reindexer/build.gradle | 1 +
.../polygene/index/reindexer/ReindexerTest.java | 2 +
tools/generator-polygene/test/generator_test.js | 152 ++++++++++---------
3 files changed, 83 insertions(+), 72 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/1ec0faa4/extensions/reindexer/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/reindexer/build.gradle b/extensions/reindexer/build.gradle
index f956f60..1315db1 100644
--- a/extensions/reindexer/build.gradle
+++ b/extensions/reindexer/build.gradle
@@ -31,6 +31,7 @@ dependencies {
testImplementation polygene.core.testsupport
testImplementation polygene.extension( 'entitystore-jdbm' )
+ testImplementation polygene.extension( 'valueserialization-jackson' )
testImplementation polygene.extension( 'indexing-rdf' )
testRuntimeOnly libraries.logback
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/1ec0faa4/extensions/reindexer/src/test/java/org/apache/polygene/index/reindexer/ReindexerTest.java
----------------------------------------------------------------------
diff --git a/extensions/reindexer/src/test/java/org/apache/polygene/index/reindexer/ReindexerTest.java b/extensions/reindexer/src/test/java/org/apache/polygene/index/reindexer/ReindexerTest.java
index 38c91a8..f3cd992 100644
--- a/extensions/reindexer/src/test/java/org/apache/polygene/index/reindexer/ReindexerTest.java
+++ b/extensions/reindexer/src/test/java/org/apache/polygene/index/reindexer/ReindexerTest.java
@@ -40,6 +40,7 @@ import org.apache.polygene.index.rdf.assembly.RdfNativeSesameStoreAssembler;
import org.apache.polygene.library.rdf.repository.NativeConfiguration;
import org.apache.polygene.test.AbstractPolygeneTest;
import org.apache.polygene.test.EntityTestAssembler;
+import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
@@ -66,6 +67,7 @@ public class ReindexerTest
// Native Sesame EntityFinder
new RdfNativeSesameStoreAssembler().assemble( module );
+ new JacksonValueSerializationAssembler().assemble( module );
// Reindexer
// START SNIPPET: assembly
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/1ec0faa4/tools/generator-polygene/test/generator_test.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/test/generator_test.js b/tools/generator-polygene/test/generator_test.js
index e215d4c..07b9c84 100644
--- a/tools/generator-polygene/test/generator_test.js
+++ b/tools/generator-polygene/test/generator_test.js
@@ -17,7 +17,7 @@ describe('polygene-generator-defaults', function () {
});
});
-[
+var entityStores = [
'Cassandra',
'File',
'Geode',
@@ -31,97 +31,105 @@ describe('polygene-generator-defaults', function () {
'Riak',
'SQL',
'Memory' // Somehow the last EntityStore is used in subsequent test arrays. Pick the fastest.
-].forEach(function (entityStore) {
- describe('polygene-generator-default-and-' + entityStore.toLowerCase() + "-entitystore", function () {
- this.timeout(10000);
- it('generates a Gradle buildable Apache Polygene project with ' + entityStore + ' as the Entity Store', function () {
- return helpers.run(path.join(__dirname, '../app'))
- .withPrompts({
- name: 'test-project',
- packageName: 'org.apache.polygene.generator.test',
- entitystore: entityStore
- })
- .then(buildAndVerify);
- });
- });
-});
+];
-[
+var indexings = [
'Rdf',
'ElasticSearch',
'Solr',
'SQL'
-].forEach(function (indexing) {
- describe('polygene-generator-default-and-' + indexing.toLowerCase() + '-indexing', function () {
- this.timeout(10000);
- it('generates a Gradle buildable Apache Polygene project with '+ indexing + ' as the Indexing system', function () {
- return helpers.run(path.join(__dirname, '../app'))
- .withPrompts({
- name: 'test-project',
- packageName: 'org.apache.polygene.generator.test',
- indexing: indexing
- })
- .then(buildAndVerify);
- });
- });
-});
+];
-[
+var cachings = [
'None',
'Memcache',
'EhCache'
-].forEach(function (caching) {
- describe('polygene-generator-default-and-' + caching.toLowerCase() + '-caching', function () {
- this.timeout(10000);
- it('generates a Gradle buildable Apache Polygene project with '+caching+' as the Caching system', function () {
- return helpers.run(path.join(__dirname, '../app'))
- .withPrompts({
- name: 'test-project',
- packageName: 'org.apache.polygene.generator.test',
- caching: caching
- })
- .then(buildAndVerify);
- });
- });
-});
+];
-[
+var serializations = [
'Jackson',
// 'Johnzon',
'Stax'
-].forEach(function (serialization) {
- describe('polygene-generator-default-and-' + serialization.toLowerCase() + '-caching', function () {
- this.timeout(10000);
- it('generates a Gradle buildable Apache Polygene project with '+serialization+' as the Serialization system', function () {
- return helpers.run(path.join(__dirname, '../app'))
- .withPrompts({
- name: 'test-project',
- packageName: 'org.apache.polygene.generator.test',
- serialization: serialization
- })
- .then(buildAndVerify);
- });
- });
-});
+];
-[
+var metricses = [
'None',
'Codahale'
-].forEach(function (metrics) {
- describe('polygene-generator-default-and-' + metrics.toLowerCase() + '-caching', function () {
- this.timeout(10000);
- it('generates a Gradle buildable Apache Polygene project with '+metrics+' as the Metrics system', function () {
- return helpers.run(path.join(__dirname, '../app'))
- .withPrompts({
- name: 'test-project',
- packageName: 'org.apache.polygene.generator.test',
- metrics: metrics
- })
- .then(buildAndVerify);
+];
+
+var featuresset = [
+ [],
+ ['rest api'],
+ ['security'],
+ ['rest api, security']
+];
+
+entityStores.forEach(function (entityStore) {
+ test(entityStore, "Rdf", "Jackson", "Memcache", "Codahale", "[]");
+});
+
+indexings.forEach(function (indexing) {
+ test("Memory", indexing, "Jackson", "Memcache", "Codahale", "[]");
+});
+
+serializations.forEach(function (serialization) {
+ test("Memory", "Rdf", serialization, "Memcache", "Codahale", "[]");
+});
+
+cachings.forEach(function (caching) {
+ test("Memory", "Rdf", "Jackson", caching, "Codahale", "[]");
+});
+
+metricses.forEach(function (metrics) {
+ test("Memory", "Rdf", "Jackson", "Memcache", metrics, "[]");
+});
+
+featuresset.forEach(function (feature) {
+ test("Memory", "Rdf", "Jackson", "Memcache", "Codahale", feature);
+});
+
+// All Tests !!!!
+entityStores.forEach(function (entitystore) {
+ indexings.forEach(function (indexing) {
+ serializations.forEach(function (serialization) {
+ cachings.forEach(function (caching) {
+ metricses.forEach(function (metrics) {
+ featuresset.forEach(function (features) {
+ test(entitystore, indexing, serialization, caching, metrics, features)
+ });
+ });
+ });
});
});
});
+function test(entityStore, indexing, serialization, caching, metrics, features) {
+ describe('polygene-generator-default-and-' + entityStore.toLowerCase() + "-entitystore", function () {
+ this.timeout(10000);
+ it('generates a Gradle buildable Apache Polygene project with '
+ + entityStore + 'EntityStore, '
+ + indexing + 'Indexing, '
+ + serialization + 'Serialzation, '
+ + caching + 'Caching, '
+ + metrics + 'Metrics, '
+ + ' and ' + features + '.',
+ function () {
+ return helpers.run(path.join(__dirname, '../app'))
+ .withPrompts({
+ name: 'test-project',
+ packageName: 'org.apache.polygene.generator.test',
+
+ entitystore: entityStore,
+ serialization: serialization,
+ indexing: indexing,
+ caching: caching,
+ metrics: metrics,
+ features: features
+ })
+ .then(buildAndVerify);
+ });
+ });
+}
function buildAndVerify(dir) {
assert.file(['gradlew', 'settings.gradle', 'build.gradle']);
[34/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/type/HasTypesCollectors.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/type/HasTypesCollectors.java b/core/api/src/main/java/org/apache/polygene/api/type/HasTypesCollectors.java
new file mode 100644
index 0000000..ef6274e
--- /dev/null
+++ b/core/api/src/main/java/org/apache/polygene/api/type/HasTypesCollectors.java
@@ -0,0 +1,408 @@
+package org.apache.polygene.api.type;
+
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.BiConsumer;
+import java.util.function.BinaryOperator;
+import java.util.function.Function;
+import java.util.function.Predicate;
+import java.util.function.Supplier;
+import java.util.stream.Collector;
+
+/**
+ * Collectors for HasTypes.
+ */
+public class HasTypesCollectors
+{
+ private static final String EQUAL_KEY = "equal";
+ private static final String EQUAL_TYPE_KEY = "equalType";
+ private static final String ASSIGNABLE_TYPE_KEY = "assignableType";
+
+ public static <T extends HasTypes> Collector<T, ?, Optional<T>> matchingType( T hasTypes )
+ {
+ return hasTypesFindFirstCollector( hasTypes, new HasAssignableFromType<>( hasTypes ) );
+ }
+
+ public static <T extends HasTypes> Collector<T, ?, Optional<T>> closestType( T hasTypes )
+ {
+ return hasTypesFindFirstCollector( hasTypes, new HasAssignableToType<>( hasTypes ) );
+ }
+
+ private static <T extends HasTypes> Collector<T, ?, Optional<T>>
+ hasTypesFindFirstCollector( T hasTypes, Predicate<T> assignableTypePredicate )
+ {
+ Predicate<T> equalPredicate = o -> Objects.equals( o, hasTypes );
+ Predicate<T> equalTypePredicate = new HasEqualType<>( hasTypes );
+ return new Collector<T, Map<String, Set<T>>, Optional<T>>()
+ {
+ @Override
+ public Supplier<Map<String, Set<T>>> supplier()
+ {
+ return () -> new HashMap<String, Set<T>>( 3 )
+ {{
+ put( EQUAL_KEY, new LinkedHashSet<>( 1 ) );
+ put( EQUAL_TYPE_KEY, new LinkedHashSet<>( 1 ) );
+ put( ASSIGNABLE_TYPE_KEY, new LinkedHashSet<>() );
+ }};
+ }
+
+ @Override
+ public BiConsumer<Map<String, Set<T>>, T> accumulator()
+ {
+ return ( map, candidate ) ->
+ {
+ Set<T> equalObjects = map.get( EQUAL_KEY );
+ if( equalObjects.isEmpty() )
+ {
+ if( equalPredicate.test( candidate ) )
+ {
+ equalObjects.add( candidate );
+ }
+ else
+ {
+ Set<T> equalTypes = map.get( EQUAL_TYPE_KEY );
+ if( equalTypes.isEmpty() )
+ {
+ if( equalTypePredicate.test( candidate ) )
+ {
+ equalTypes.add( candidate );
+ }
+ else if( assignableTypePredicate.test( candidate ) )
+ {
+ map.get( ASSIGNABLE_TYPE_KEY ).add( candidate );
+ }
+ }
+ }
+ }
+ };
+ }
+
+ @Override
+ public BinaryOperator<Map<String, Set<T>>> combiner()
+ {
+ return ( left, right ) ->
+ {
+ left.get( EQUAL_KEY ).addAll( right.get( EQUAL_KEY ) );
+ left.get( EQUAL_TYPE_KEY ).addAll( right.get( EQUAL_TYPE_KEY ) );
+ left.get( ASSIGNABLE_TYPE_KEY ).addAll( right.get( ASSIGNABLE_TYPE_KEY ) );
+ return left;
+ };
+ }
+
+ @Override
+ public Function<Map<String, Set<T>>, Optional<T>> finisher()
+ {
+ return map ->
+ {
+ Set<T> equalObjects = map.get( EQUAL_KEY );
+ if( !equalObjects.isEmpty() )
+ {
+ return Optional.of( equalObjects.iterator().next() );
+ }
+ Set<T> equalTypes = map.get( EQUAL_TYPE_KEY );
+ if( !equalTypes.isEmpty() )
+ {
+ return Optional.of( equalTypes.iterator().next() );
+ }
+ Set<T> assignableTypes = map.get( ASSIGNABLE_TYPE_KEY );
+ if( !assignableTypes.isEmpty() )
+ {
+ return Optional.of( assignableTypes.iterator().next() );
+ }
+ return Optional.empty();
+ };
+ }
+
+ @Override
+ public Set<Characteristics> characteristics()
+ {
+ return Collections.emptySet();
+ }
+ };
+ }
+
+
+ public static <T extends HasTypes> Collector<T, ?, List<T>> matchingTypes( T hasTypes )
+ {
+ return hasTypesToListCollector( hasTypes, new HasAssignableFromType<>( hasTypes ) );
+ }
+
+ public static <T extends HasTypes> Collector<T, ?, List<T>> closestTypes( T hasTypes )
+ {
+ return hasTypesToListCollector( hasTypes, new HasAssignableToType<>( hasTypes ) );
+ }
+
+ private static <T extends HasTypes> Collector<T, ?, List<T>>
+ hasTypesToListCollector( T hasTypes, Predicate<T> assignableTypePredicate )
+ {
+ Predicate<T> equalPredicate = o -> Objects.equals( o, hasTypes );
+ Predicate<T> equalTypePredicate = new HasEqualType<>( hasTypes );
+ return new Collector<T, Map<String, Set<T>>, List<T>>()
+ {
+ @Override
+ public Supplier<Map<String, Set<T>>> supplier()
+ {
+ return () -> new HashMap<String, Set<T>>( 3 )
+ {{
+ put( EQUAL_KEY, new LinkedHashSet<>() );
+ put( EQUAL_TYPE_KEY, new LinkedHashSet<>() );
+ put( ASSIGNABLE_TYPE_KEY, new LinkedHashSet<>() );
+ }};
+ }
+
+ @Override
+ public BiConsumer<Map<String, Set<T>>, T> accumulator()
+ {
+ return ( map, candidate ) ->
+ {
+ Set<T> equalObjects = map.get( EQUAL_KEY );
+ if( equalObjects.isEmpty() )
+ {
+ if( equalPredicate.test( candidate ) )
+ {
+ equalObjects.add( candidate );
+ }
+ else
+ {
+ Set<T> equalTypes = map.get( EQUAL_TYPE_KEY );
+ if( equalTypes.isEmpty() )
+ {
+ if( equalTypePredicate.test( candidate ) )
+ {
+ equalTypes.add( candidate );
+ }
+ else if( assignableTypePredicate.test( candidate ) )
+ {
+ map.get( ASSIGNABLE_TYPE_KEY ).add( candidate );
+ }
+ }
+ }
+ }
+ };
+ }
+
+ @Override
+ public BinaryOperator<Map<String, Set<T>>> combiner()
+ {
+ return ( left, right ) ->
+ {
+ left.get( EQUAL_KEY ).addAll( right.get( EQUAL_KEY ) );
+ left.get( EQUAL_TYPE_KEY ).addAll( right.get( EQUAL_TYPE_KEY ) );
+ left.get( ASSIGNABLE_TYPE_KEY ).addAll( right.get( ASSIGNABLE_TYPE_KEY ) );
+ return left;
+ };
+ }
+
+ @Override
+ public Function<Map<String, Set<T>>, List<T>> finisher()
+ {
+ return map ->
+ {
+ Set<T> equalObjects = map.get( EQUAL_KEY );
+ Set<T> equalSet = map.get( EQUAL_TYPE_KEY );
+ Set<T> assignableSet = map.get( ASSIGNABLE_TYPE_KEY );
+ List<T> list = new ArrayList<>( equalObjects.size() + equalSet.size() + assignableSet.size() );
+ list.addAll( equalObjects );
+ list.addAll( equalSet );
+ list.addAll( assignableSet );
+ return list;
+ };
+ }
+
+ @Override
+ public Set<Characteristics> characteristics()
+ {
+ return Collections.emptySet();
+ }
+ };
+ }
+
+
+ /**
+ * Collect a single matching HasTypes.
+ *
+ * TODO Detail
+ *
+ * @param type type to match
+ * @param <T> type of HasTypes
+ * @return an optional best matching HasTypes
+ */
+ public static <T extends HasTypes> Collector<T, ?, Optional<T>> matchingType( Type type )
+ {
+ return typeFindFirstCollector( type, new HasAssignableFromType<>( type ) );
+ }
+
+ public static <T extends HasTypes> Collector<T, ?, Optional<T>> closestType( Type type )
+ {
+ return typeFindFirstCollector( type, new HasAssignableToType<T>( type ) );
+ }
+
+ private static <T extends HasTypes> Collector<T, ?, Optional<T>>
+ typeFindFirstCollector( Type type, Predicate<T> assignableTypePredicate )
+ {
+ Predicate<T> equalTypePredicate = new HasEqualType<>( type );
+ return new Collector<T, Map<String, Set<T>>, Optional<T>>()
+ {
+ @Override
+ public Supplier<Map<String, Set<T>>> supplier()
+ {
+ return () -> new HashMap<String, Set<T>>( 2 )
+ {{
+ put( EQUAL_TYPE_KEY, new LinkedHashSet<>( 1 ) );
+ put( ASSIGNABLE_TYPE_KEY, new LinkedHashSet<>() );
+ }};
+ }
+
+ @Override
+ public BiConsumer<Map<String, Set<T>>, T> accumulator()
+ {
+ return ( map, candidate ) ->
+ {
+ Set<T> equalSet = map.get( EQUAL_TYPE_KEY );
+ if( equalSet.isEmpty() )
+ {
+ if( equalTypePredicate.test( candidate ) )
+ {
+ equalSet.add( candidate );
+ }
+ else if( assignableTypePredicate.test( candidate ) )
+ {
+ map.get( ASSIGNABLE_TYPE_KEY ).add( candidate );
+ }
+ }
+ };
+ }
+
+ @Override
+ public BinaryOperator<Map<String, Set<T>>> combiner()
+ {
+ return ( left, right ) ->
+ {
+ left.get( EQUAL_TYPE_KEY ).addAll( right.get( EQUAL_TYPE_KEY ) );
+ left.get( ASSIGNABLE_TYPE_KEY ).addAll( right.get( ASSIGNABLE_TYPE_KEY ) );
+ return left;
+ };
+ }
+
+ @Override
+ public Function<Map<String, Set<T>>, Optional<T>> finisher()
+ {
+ return map ->
+ {
+ Set<T> equalSet = map.get( EQUAL_TYPE_KEY );
+ if( !equalSet.isEmpty() )
+ {
+ return Optional.of( equalSet.iterator().next() );
+ }
+ Set<T> assignableSet = map.get( ASSIGNABLE_TYPE_KEY );
+ if( !assignableSet.isEmpty() )
+ {
+ return Optional.of( assignableSet.iterator().next() );
+ }
+ return Optional.empty();
+ };
+ }
+
+ @Override
+ public final Set<Characteristics> characteristics()
+ {
+ return Collections.emptySet();
+ }
+ };
+ }
+
+ /**
+ * Collect all matching HasTypes.
+ *
+ * First the ones with at least on equal type.
+ * Then the ones with at least one type assignable from {@literal type}.
+ *
+ * @param type type to match
+ * @param <T> type of HasTypes
+ * @return an optional best matching HasTypes
+ */
+ public static <T extends HasTypes> Collector<T, ?, List<T>> matchingTypes( Type type )
+ {
+ return typeToListCollector( type, new HasAssignableFromType<>( type ) );
+ }
+
+ public static <T extends HasTypes> Collector<T, ?, List<T>> closestTypes( Type type )
+ {
+ return typeToListCollector( type, new HasAssignableToType<>( type ) );
+ }
+
+ private static <T extends HasTypes> Collector<T, ?, List<T>>
+ typeToListCollector( Type type, Predicate<T> assignableTypePredicate )
+ {
+ Predicate<T> equalTypePredicate = new HasEqualType<>( type );
+ return new Collector<T, Map<String, Set<T>>, List<T>>()
+ {
+ @Override
+ public Supplier<Map<String, Set<T>>> supplier()
+ {
+ return () -> new HashMap<String, Set<T>>( 2 )
+ {{
+ put( EQUAL_TYPE_KEY, new LinkedHashSet<>() );
+ put( ASSIGNABLE_TYPE_KEY, new LinkedHashSet<>() );
+ }};
+ }
+
+ @Override
+ public BiConsumer<Map<String, Set<T>>, T> accumulator()
+ {
+ return ( map, candidate ) ->
+ {
+ if( equalTypePredicate.test( candidate ) )
+ {
+ map.get( EQUAL_TYPE_KEY ).add( candidate );
+ }
+ else if( assignableTypePredicate.test( candidate ) )
+ {
+ map.get( ASSIGNABLE_TYPE_KEY ).add( candidate );
+ }
+ };
+ }
+
+ @Override
+ public BinaryOperator<Map<String, Set<T>>> combiner()
+ {
+ return ( left, right ) ->
+ {
+ left.get( EQUAL_TYPE_KEY ).addAll( right.get( EQUAL_TYPE_KEY ) );
+ left.get( ASSIGNABLE_TYPE_KEY ).addAll( right.get( ASSIGNABLE_TYPE_KEY ) );
+ return left;
+ };
+ }
+
+ @Override
+ public Function<Map<String, Set<T>>, List<T>> finisher()
+ {
+ return map ->
+ {
+ Set<T> equalSet = map.get( EQUAL_TYPE_KEY );
+ Set<T> assignableSet = map.get( ASSIGNABLE_TYPE_KEY );
+ List<T> list = new ArrayList<>( equalSet.size() + assignableSet.size() );
+ list.addAll( equalSet );
+ list.addAll( assignableSet );
+ return list;
+ };
+ }
+
+ @Override
+ public final Set<Characteristics> characteristics()
+ {
+ return Collections.emptySet();
+ }
+ };
+ }
+
+ private HasTypesCollectors() {}
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/type/HasTypesPredicate.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/type/HasTypesPredicate.java b/core/api/src/main/java/org/apache/polygene/api/type/HasTypesPredicate.java
new file mode 100644
index 0000000..fd91a3a
--- /dev/null
+++ b/core/api/src/main/java/org/apache/polygene/api/type/HasTypesPredicate.java
@@ -0,0 +1,60 @@
+package org.apache.polygene.api.type;
+
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.lang.reflect.WildcardType;
+import java.util.List;
+import java.util.function.Predicate;
+
+import static org.apache.polygene.api.util.Classes.interfacesOf;
+
+public abstract class HasTypesPredicate<T extends HasTypes> implements Predicate<T>
+{
+ protected final List<Type> matchTypes;
+
+ protected HasTypesPredicate( List<Type> types )
+ {
+ matchTypes = types;
+ }
+
+ @Override
+ public final boolean test( T hasTypes )
+ {
+ for( Type matchType : matchTypes )
+ {
+ if( matchType instanceof Class )
+ {
+ if( hasTypes.types().anyMatch( matchPredicate( matchType ) ) )
+ {
+ return true;
+ }
+ }
+ else
+ {
+ if( matchType instanceof ParameterizedType )
+ {
+ // Foo<Bar> check
+ // First check Foo
+ ParameterizedType parameterizedType = (ParameterizedType) matchType;
+ Type rawType = parameterizedType.getRawType();
+
+ if( hasTypes.types().anyMatch( matchPredicate( rawType ) ) )
+ {
+ // Then check Bar
+ if( interfacesOf( hasTypes.types() ).anyMatch( intf -> intf.equals( matchType ) ) )
+ {
+ return true;
+ }
+ }
+ }
+ else if( matchType instanceof WildcardType )
+ {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ protected abstract Predicate<Type> matchPredicate( Type candidate );
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/type/MapType.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/type/MapType.java b/core/api/src/main/java/org/apache/polygene/api/type/MapType.java
index 4046628..23124eb 100644
--- a/core/api/src/main/java/org/apache/polygene/api/type/MapType.java
+++ b/core/api/src/main/java/org/apache/polygene/api/type/MapType.java
@@ -21,6 +21,7 @@ package org.apache.polygene.api.type;
import java.lang.reflect.Type;
import java.util.Map;
+import java.util.Objects;
import org.apache.polygene.api.util.Classes;
/**
@@ -30,38 +31,40 @@ import org.apache.polygene.api.util.Classes;
public final class MapType
extends ValueType
{
-
- private ValueType keyType;
- private ValueType valueType;
- private final Serialization.Variant variant;
-
public static boolean isMap( Type type )
{
Class<?> cl = Classes.RAW_CLASS.apply( type );
return Map.class.isAssignableFrom( cl );
}
- public static MapType of( Class<?> keyType, Class<?> valueType )
+ public static MapType of( Class<?> mapType, ValueType keyType, ValueType valueType )
{
- return new MapType( Map.class, ValueType.of( keyType ), ValueType.of( valueType ) );
+ return new MapType( mapType, keyType, valueType );
}
- public static MapType of( Class<?> keyType, Class<?> valueType, Serialization.Variant variant )
+ public static MapType of( Class<?> mapType, Class<?> keyType, Class<?> valueType )
{
- return new MapType( Map.class, ValueType.of( keyType ), ValueType.of( valueType ), variant );
+ return of( mapType, ValueType.of( keyType ), ValueType.of( valueType ) );
}
- public MapType( Class<?> type, ValueType keyType, ValueType valueType )
+ public static MapType of( ValueType keyType, ValueType valueType )
{
- this( type, keyType, valueType, Serialization.Variant.entry );
+ return new MapType( Map.class, keyType, valueType );
}
- public MapType( Class<?> type, ValueType keyType, ValueType valueType, Serialization.Variant variant )
+ public static MapType of( Class<?> keyType, Class<?> valueType )
+ {
+ return of( ValueType.of( keyType ), ValueType.of( valueType ) );
+ }
+
+ private ValueType keyType;
+ private ValueType valueType;
+
+ public MapType( Class<?> type, ValueType keyType, ValueType valueType )
{
super( type );
this.keyType = keyType;
this.valueType = valueType;
- this.variant = variant;
if( !isMap( type ) )
{
throw new IllegalArgumentException( type + " is not a Map." );
@@ -78,9 +81,21 @@ public final class MapType
return valueType;
}
- public Serialization.Variant variant()
+ @Override
+ public boolean equals( final Object o )
+ {
+ if( this == o ) { return true; }
+ if( o == null || getClass() != o.getClass() ) { return false; }
+ if( !super.equals( o ) ) { return false; }
+ MapType mapType = (MapType) o;
+ return Objects.equals( keyType, mapType.keyType ) &&
+ Objects.equals( valueType, mapType.valueType );
+ }
+
+ @Override
+ public int hashCode()
{
- return variant;
+ return Objects.hash( super.hashCode(), keyType, valueType );
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/type/MatchTypeSpecification.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/type/MatchTypeSpecification.java b/core/api/src/main/java/org/apache/polygene/api/type/MatchTypeSpecification.java
deleted file mode 100644
index 8d8ff92..0000000
--- a/core/api/src/main/java/org/apache/polygene/api/type/MatchTypeSpecification.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-
-package org.apache.polygene.api.type;
-
-import java.util.function.Predicate;
-
-/**
- * Match Type Specification for HasTypes.
- */
-public class MatchTypeSpecification
- implements Predicate<HasTypes>
-{
- private final Class<?> matchType;
-
- public MatchTypeSpecification( Class<?> matchType )
- {
- this.matchType = matchType;
- }
-
- @Override
- public boolean test( HasTypes item )
- {
- return item.types().anyMatch( matchType::isAssignableFrom );
-// for( Class<?> type : item.types() )
-// {
-// if( matchType.isAssignableFrom( type ) )
-// {
-// return true;
-// }
-// }
-// return false;
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/type/Serialization.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/type/Serialization.java b/core/api/src/main/java/org/apache/polygene/api/type/Serialization.java
deleted file mode 100644
index 981ab00..0000000
--- a/core/api/src/main/java/org/apache/polygene/api/type/Serialization.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.api.type;
-
-import java.lang.annotation.Documented;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Serialization options for Property intstances.
- * <p>
- * The {@code entry} type represents the explicit key=keyValue, value=valueValue. For JSON serialization;
- * </p>
- * <pre>
- * [
- * { "key1" : "value1" },
- * { "key2" : "value2" }
- * ]
- * </pre>
- * <p>
- * For XML serialization;
- * </p>
- * <pre>
- * <object>
- * <
- * </object>
- * </pre>
- * <p>
- * The {@code object} type represents the explicit keyValue=valueValue.
- * </p>
- */
-@Retention( RetentionPolicy.RUNTIME )
-@Target( { ElementType.TYPE, ElementType.METHOD } )
-@Documented
-public @interface Serialization
-{
- Variant value();
-
- enum Variant
- {
- entry, object
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/type/ValueCompositeType.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/type/ValueCompositeType.java b/core/api/src/main/java/org/apache/polygene/api/type/ValueCompositeType.java
index 4cf86a6..9190e68 100644
--- a/core/api/src/main/java/org/apache/polygene/api/type/ValueCompositeType.java
+++ b/core/api/src/main/java/org/apache/polygene/api/type/ValueCompositeType.java
@@ -20,7 +20,7 @@
package org.apache.polygene.api.type;
import java.lang.reflect.Type;
-import java.util.stream.Collectors;
+import java.util.Objects;
import java.util.stream.Stream;
import org.apache.polygene.api.association.AssociationDescriptor;
import org.apache.polygene.api.property.PropertyDescriptor;
@@ -28,22 +28,28 @@ import org.apache.polygene.api.util.Classes;
import org.apache.polygene.api.value.ValueComposite;
import org.apache.polygene.api.value.ValueDescriptor;
+import static java.util.stream.Collectors.toList;
+
/**
* ValueComposite ValueType.
*/
-public final class ValueCompositeType
- extends ValueType
+public final class ValueCompositeType extends ValueType
{
- private final ValueDescriptor model;
+ public static ValueCompositeType of( ValueDescriptor model )
+ {
+ return new ValueCompositeType( model );
+ }
public static boolean isValueComposite( Type type )
{
return ValueComposite.class.isAssignableFrom( Classes.RAW_CLASS.apply( type ) );
}
+ private final ValueDescriptor model;
+
public ValueCompositeType( ValueDescriptor model )
{
- super( model.types().collect( Collectors.toList() ) );
+ super( model.types().collect( toList() ) );
this.model = model;
}
@@ -66,4 +72,20 @@ public final class ValueCompositeType
{
return model.state().namedAssociations();
}
+
+ @Override
+ public boolean equals( final Object o )
+ {
+ if( this == o ) { return true; }
+ if( o == null || getClass() != o.getClass() ) { return false; }
+ if( !super.equals( o ) ) { return false; }
+ ValueCompositeType that = (ValueCompositeType) o;
+ return Objects.equals( model, that.model );
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hash( super.hashCode(), model );
+ }
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/type/ValueType.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/type/ValueType.java b/core/api/src/main/java/org/apache/polygene/api/type/ValueType.java
index fee41cb..d457d81 100644
--- a/core/api/src/main/java/org/apache/polygene/api/type/ValueType.java
+++ b/core/api/src/main/java/org/apache/polygene/api/type/ValueType.java
@@ -19,10 +19,21 @@
*/
package org.apache.polygene.api.type;
-import java.util.Collections;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.OffsetDateTime;
+import java.time.Period;
+import java.time.ZonedDateTime;
+import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;
+import org.apache.polygene.api.entity.EntityReference;
import org.apache.polygene.api.identity.Identity;
import static java.util.stream.Collectors.joining;
@@ -30,105 +41,44 @@ import static java.util.stream.Collectors.joining;
/**
* Base class for types of values in ValueComposites and Properties.
*/
-public class ValueType
- implements HasTypes
+public class ValueType implements HasTypes
{
+ public static final ValueType OBJECT = ValueType.of( Object.class );
+ public static final ValueType STRING = ValueType.of( String.class );
+ public static final ValueType CHARACTER = ValueType.of( Character.class, char.class );
+ public static final ValueType BOOLEAN = ValueType.of( Boolean.class, boolean.class );
+ public static final ValueType INTEGER = ValueType.of( Integer.class, int.class );
+ public static final ValueType LONG = ValueType.of( Long.class, long.class );
+ public static final ValueType SHORT = ValueType.of( Short.class, short.class );
+ public static final ValueType BYTE = ValueType.of( Byte.class, byte.class );
+ public static final ValueType FLOAT = ValueType.of( Float.class, float.class );
+ public static final ValueType DOUBLE = ValueType.of( Double.class, double.class );
+ public static final ValueType BIG_DECIMAL = ValueType.of( BigDecimal.class );
+ public static final ValueType BIG_INTEGER = ValueType.of( BigInteger.class );
+ public static final ValueType INSTANT = ValueType.of( Instant.class );
+ public static final ValueType ZONED_DATE_TIME = ValueType.of( ZonedDateTime.class );
+ public static final ValueType OFFSET_DATE_TIME = ValueType.of( OffsetDateTime.class );
+ public static final ValueType LOCAL_DATE_TIME = ValueType.of( LocalDateTime.class );
+ public static final ValueType LOCAL_DATE = ValueType.of( LocalDate.class );
+ public static final ValueType LOCAL_TIME = ValueType.of( LocalTime.class );
+ public static final ValueType DURATION = ValueType.of( Duration.class );
+ public static final ValueType PERIOD = ValueType.of( Period.class );
+ public static final ValueType IDENTITY = ValueType.of( Identity.class );
+ public static final ValueType ENTITY_REFERENCE = ValueType.of( EntityReference.class );
- public static ValueType of( Class<?> type )
+ public static ValueType of( Class<?>... types )
{
- return new ValueType( type );
+ return new ValueType( types );
}
- /**
- * Check if a non-null object is of any of the Primitive Value Types or an array of them.
- * <p>
- * String, Boolean, Integer, Double, Float, Long, Byte, Short and Character and their Java primitive types
- * counterparts are considered as Primitive Value Types.
- * </p>
- * <p>
- * Date, BigInteger, BigDecimal and JodaTime types are not considered as Primitive Value Types.
- * </p>
- *
- * @param object Object
- * @return true if object is a primitive value or an array of primitive values
- * @throws IllegalArgumentException if object is null
- */
- public static boolean isPrimitiveValue( Object object )
- {
- Objects.requireNonNull( object, "object" );
- if( object instanceof String
- || object instanceof Character
- || object instanceof Boolean
- || object instanceof Integer
- || object instanceof Double
- || object instanceof Float
- || object instanceof Long
- || object instanceof Byte
- || object instanceof Short )
- {
- return true;
- }
- if( object.getClass().isArray() )
- {
- return isArrayOfPrimitiveValues( object );
- }
- return false;
- }
-
- public static boolean isIdentity( Object object )
- {
- return object instanceof Identity;
- }
-
- private static boolean isArrayOfPrimitiveValues( Object array )
- {
- if( array instanceof String[]
- || array instanceof char[] || array instanceof Character[]
- || array instanceof boolean[] || array instanceof Boolean[]
- || array instanceof int[] || array instanceof Integer[]
- || array instanceof double[] || array instanceof Double[]
- || array instanceof float[] || array instanceof Float[]
- || array instanceof long[] || array instanceof Long[]
- || array instanceof byte[] || array instanceof Byte[]
- || array instanceof short[] || array instanceof Short[] )
- {
- return true;
- }
- return false;
- }
-
- public static boolean isPrimitiveValueType( ValueType valueType )
- {
- return isPrimitiveValueType( valueType.primaryType() );
- }
-
- /**
- * @see ValueType#isPrimitiveValue(java.lang.Object)
- * @param type Type
- * @return true if object is a primitive value or an array of primitive values
- */
- public static boolean isPrimitiveValueType( Class<?> type )
- {
- Objects.requireNonNull( type, "type" );
- if( String.class.isAssignableFrom( type ) )
- {
- return true;
- }
- if( type.isArray() )
- {
- return isPrimitiveValueType( type.getComponentType() );
- }
- return false;
- }
protected final List<Class<?>> types;
- public ValueType( Class<?> type )
+ protected ValueType( Class<?>... types )
{
- this( Collections.singletonList( type ) );
+ this( Arrays.asList( types ) );
}
- @SuppressWarnings( "unchecked" )
- public ValueType( List<Class<?>> types )
+ protected ValueType( List<Class<?>> types )
{
this.types = types;
}
@@ -145,6 +95,21 @@ public class ValueType
}
@Override
+ public boolean equals( Object o )
+ {
+ if( this == o ) { return true; }
+ if( o == null || getClass() != o.getClass() ) { return false; }
+ ValueType valueType = (ValueType) o;
+ return Objects.equals( types, valueType.types );
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hash( types );
+ }
+
+ @Override
public String toString()
{
String name = types.stream().map( Class::getName ).collect( joining( "," ) );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/util/Collectors.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/util/Collectors.java b/core/api/src/main/java/org/apache/polygene/api/util/Collectors.java
index e419b21..906b062 100644
--- a/core/api/src/main/java/org/apache/polygene/api/util/Collectors.java
+++ b/core/api/src/main/java/org/apache/polygene/api/util/Collectors.java
@@ -17,6 +17,7 @@
*/
package org.apache.polygene.api.util;
+import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.BinaryOperator;
@@ -24,13 +25,18 @@ import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
+/**
+ * Implementations of {@link Collector} missing from the JDK.
+ */
public class Collectors
{
/**
* Collect a single element.
+ *
+ * The Collector throws {@link IllegalArgumentException} if no or more than one element.
+ *
* @param <T> Element type
- * @return The single element
- * @throws IllegalArgumentException if no or more than one element
+ * @return The single element collector
*/
public static <T>
Collector<T, ?, T> single()
@@ -46,13 +52,14 @@ public class Collectors
/**
* Eventually collect a single element.
+ *
+ * The Collector throws {@link IllegalArgumentException} if more than one element.
+ *
* @param <T> Element type
- * @return The single element, optional
- * @throws IllegalArgumentException if more than one element
+ * @return The optional single element collector
*/
public static <T>
Collector<T, ?, Optional<T>> singleOrEmpty()
- throws IllegalArgumentException
{
return java.util.stream.Collectors.reducing(
( left, right ) ->
@@ -69,6 +76,59 @@ public class Collectors
} );
}
+ /**
+ * Collect map entries into a {@link HashMap}.
+ *
+ * The Collector throws {@link NullPointerException} if one entry has a {@literal null} value.
+ * The Collector throws {@link IllegalStateException} if duplicate keys are found.
+ *
+ * @param <T> the Map entry type
+ * @param <K> the collected map key type
+ * @param <U> the collected map value type
+ * @return a {@code Collector} which collects elements into a {@code Map}
+ */
+ public static <T extends Map.Entry<K, U>, K, U>
+ Collector<T, ?, Map<K, U>> toMap()
+ {
+ return toMap( Map.Entry::getKey, Map.Entry::getValue, HashMap::new );
+ }
+
+ /**
+ * Collect map entries into a map.
+ *
+ * The Collector throws {@link NullPointerException} if one entry has a {@literal null} value.
+ * The Collector throws {@link IllegalStateException} if duplicate keys are found.
+ *
+ * @param <M> the type of the resulting {@code Map}
+ * @param <T> the Map entry type
+ * @param <K> the collected map key type
+ * @param <U> the collected map value type
+ * @param mapSupplier a function which returns a new, empty {@code Map} into
+ * which the results will be inserted
+ * @return The map collector
+ */
+ public static <T extends Map.Entry<K, U>, K, U, M extends Map<K, U>>
+ Collector<T, ?, M> toMap( Supplier<M> mapSupplier )
+ {
+ return toMap( Map.Entry::getKey, Map.Entry::getValue, mapSupplier );
+ }
+
+ /**
+ * Collect map entries into a map.
+ *
+ * The Collector throws {@link NullPointerException} if one entry has a {@literal null} value.
+ * The Collector throws {@link IllegalStateException} if duplicate keys are found.
+ *
+ * @param <M> the type of the resulting {@code Map}
+ * @param <T> the Map entry type
+ * @param <K> the collected map key type
+ * @param <U> the collected map value type
+ * @param keyMapper a mapping function to produce keys
+ * @param valueMapper a mapping function to produce values
+ * @param mapSupplier a function which returns a new, empty {@code Map} into
+ * which the results will be inserted
+ * @return The map collector
+ */
public static <T, K, U, M extends Map<K, U>>
Collector<T, ?, M> toMap( Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
@@ -80,17 +140,86 @@ public class Collectors
mapSupplier );
}
-
+ /**
+ * Collect map entries into a {@link HashMap}, allowing null values.
+ *
+ * The Collector throws {@link IllegalStateException} if duplicate keys are found.
+ *
+ * See https://bugs.openjdk.java.net/browse/JDK-8148463
+ *
+ * @param <T> the Map entry type
+ * @param <K> the collected map key type
+ * @param <U> the collected map value type
+ * @return The map collector
+ */
public static <T extends Map.Entry<K, U>, K, U>
- Collector<T, ?, Map<K, U>> toMap()
+ Collector<T, ?, Map<K, U>> toMapWithNullValues()
{
- return java.util.stream.Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue );
+ return toMapWithNullValues( Map.Entry::getKey, Map.Entry::getValue, HashMap::new );
}
+ /**
+ * Collect map entries into a map, allowing null values.
+ *
+ * The Collector throws {@link IllegalStateException} if duplicate keys are found.
+ *
+ * See https://bugs.openjdk.java.net/browse/JDK-8148463
+ *
+ * @param <M> the type of the resulting {@code Map}
+ * @param <T> the Map entry type
+ * @param <K> the collected map key type
+ * @param <U> the collected map value type
+ * @param mapSupplier a function which returns a new, empty {@code Map} into
+ * which the results will be inserted
+ * @return The map collector
+ */
public static <T extends Map.Entry<K, U>, K, U, M extends Map<K, U>>
- Collector<T, ?, M> toMap( Supplier<M> mapSupplier )
+ Collector<T, ?, M> toMapWithNullValues( Supplier<M> mapSupplier )
{
- return toMap( Map.Entry::getKey, Map.Entry::getValue, mapSupplier );
+ return toMapWithNullValues( Map.Entry::getKey, Map.Entry::getValue, mapSupplier );
+ }
+
+ /**
+ * Collect map entries into a map, allowing null values.
+ *
+ * The Collector throws {@link IllegalStateException} if duplicate keys are found.
+ *
+ * See https://bugs.openjdk.java.net/browse/JDK-8148463
+ *
+ * @param <M> the type of the resulting {@code Map}
+ * @param <T> the Map entry type
+ * @param <K> the collected map key type
+ * @param <U> the collected map value type
+ * @param keyMapper a mapping function to produce keys
+ * @param valueMapper a mapping function to produce values
+ * @param mapSupplier a function which returns a new, empty {@code Map} into
+ * which the results will be inserted
+ * @return The map collector
+ */
+ public static <T, K, U, M extends Map<K, U>>
+ Collector<T, ?, M> toMapWithNullValues( Function<? super T, ? extends K> keyMapper,
+ Function<? super T, ? extends U> valueMapper,
+ Supplier<M> mapSupplier )
+ {
+ return java.util.stream.Collector
+ .of( mapSupplier,
+ ( map, entry ) -> map.put( keyMapper.apply( entry ),
+ valueMapper.apply( entry ) ),
+ ( left, right ) ->
+ {
+ M result = mapSupplier.get();
+ result.putAll( left );
+ for( Map.Entry<K, U> entry : right.entrySet() )
+ {
+ K key = entry.getKey();
+ if( result.containsKey( key ) )
+ {
+ throw new IllegalStateException( String.format( "Duplicate key %s", key ) );
+ }
+ result.put( key, entry.getValue() );
+ }
+ return result;
+ } );
}
private static <T> BinaryOperator<T> throwingMerger()
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/value/MissingValueSerializationException.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/value/MissingValueSerializationException.java b/core/api/src/main/java/org/apache/polygene/api/value/MissingValueSerializationException.java
deleted file mode 100644
index 00b1af7..0000000
--- a/core/api/src/main/java/org/apache/polygene/api/value/MissingValueSerializationException.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-
-package org.apache.polygene.api.value;
-
-public class MissingValueSerializationException extends ValueSerializationException
-{
- public MissingValueSerializationException()
- {
- }
-
- public MissingValueSerializationException( String message )
- {
- super( message );
- }
-
- public MissingValueSerializationException( String message, Throwable cause )
- {
- super( message, cause );
- }
-
- public MissingValueSerializationException( Throwable cause )
- {
- super( cause );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/value/ValueDescriptor.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/value/ValueDescriptor.java b/core/api/src/main/java/org/apache/polygene/api/value/ValueDescriptor.java
index b9b3f54..8407fa9 100644
--- a/core/api/src/main/java/org/apache/polygene/api/value/ValueDescriptor.java
+++ b/core/api/src/main/java/org/apache/polygene/api/value/ValueDescriptor.java
@@ -20,19 +20,15 @@
package org.apache.polygene.api.value;
-import org.apache.polygene.api.association.AssociationStateDescriptor;
import org.apache.polygene.api.composite.CompositeDescriptor;
-import org.apache.polygene.api.composite.StatefulCompositeDescriptor;
+import org.apache.polygene.api.composite.StatefulAssociationCompositeDescriptor;
import org.apache.polygene.api.type.ValueCompositeType;
/**
* Descriptor for ValueComposites.
*/
public interface ValueDescriptor
- extends CompositeDescriptor, StatefulCompositeDescriptor
+ extends CompositeDescriptor, StatefulAssociationCompositeDescriptor
{
ValueCompositeType valueType();
-
- @Override
- AssociationStateDescriptor state();
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/value/ValueDeserializer.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/value/ValueDeserializer.java b/core/api/src/main/java/org/apache/polygene/api/value/ValueDeserializer.java
deleted file mode 100644
index 88afc3a..0000000
--- a/core/api/src/main/java/org/apache/polygene/api/value/ValueDeserializer.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.api.value;
-
-import java.io.InputStream;
-import java.util.function.Function;
-import org.apache.polygene.api.structure.ModuleDescriptor;
-import org.apache.polygene.api.type.ValueType;
-
-/**
- * Use a ValueDeserializer to create new values instances from serialized state.
- *
- * <p>
- * Serialized state must be one of:
- * </p>
- * <ul>
- * <li>a ValueComposite,</li>
- * <li>an EntityReference,</li>
- * <li>a Collection,</li>
- * <li>a Map,</li>
- * <li>a Plain Value.</li>
- * </ul>
- * <p>
- * Nested plain values, EntityReferences, Collections, Maps, ValueComposites are supported.
- * EntityReferences are deserialized as their reference string.
- * </p>
- * <p>
- * Plain values can be one of:
- * </p>
- * <ul>
- * <li>String,</li>
- * <li>Character or char,</li>
- * <li>Boolean or boolean,</li>
- * <li>Integer or int,</li>
- * <li>Long or long,</li>
- * <li>Short or short,</li>
- * <li>Byte or byte,</li>
- * <li>Float or float,</li>
- * <li>Double or double,</li>
- * <li>BigInteger,</li>
- * <li>BigDecimal,</li>
- * <li>Date,</li>
- * <li>DateTime (JodaTime),</li>
- * <li>LocalDateTime (JodaTime),</li>
- * <li>LocalDate (JodaTime).</li>
- * </ul>
- * <p>
- * Values of unknown types and all arrays are considered as {@link java.io.Serializable} and by so are deserialized
- * from base64 encoded bytes using pure Java serialization. If it happens that the input is invalid, a
- * ValueSerializationException is thrown.
- * </p>
- * <p>
- * Having type information in the serialized payload allows to keep actual ValueComposite types and by so
- * circumvent {@link org.apache.polygene.api.composite.AmbiguousTypeException} when deserializing.
- * </p>
- */
-public interface ValueDeserializer
-{
-
- /**
- * Factory method for a typed deserialize function.
- *
- * <p>The returned Function may throw {@link ValueSerializationException}.</p>
- *
- * @param <T> the parametrized function return type
- * @param module the module
- * @param type the value type
- *
- * @return a deserialization function
- */
- <T> Function<String, T> deserialize( ModuleDescriptor module, Class<T> type );
-
- /**
- * Factory method for a typed deserialize function.
- *
- * <p>The returned Function may throw {@link ValueSerializationException}.</p>
- *
- * @param <T> the parametrized function return type
- * @param module the module
- * @param valueType the value type
- *
- * @return a deserialization function
- */
- <T> Function<String, T> deserialize( ModuleDescriptor module, ValueType valueType );
-
- /**
- * Factory method for an untyped deserialize function.
- *
- * <p>The returned Function may throw {@link ValueSerializationException}.</p>
- *
- * @param <T> the parametrized function return type
- * @return a deserialization function
- */
-// <T> BiFunction<ValueType, String, T> deserialize();
-
- /**
- * Deserialize a value from a state.
- *
- * @param <T> the parametrized returned type
- * @param module the module
- * @param type the value type
- * @param input the state
- *
- * @return the value
- *
- * @throws ValueSerializationException if the deserialization failed
- */
- <T> T deserialize( ModuleDescriptor module, Class<?> type, String input )
- throws ValueSerializationException;
-
- /**
- * Deserialize a value from a state.
- *
- * @param <T> the parametrized returned type
- * @param module the module
- * @param valueType the value type
- * @param input the state
- *
- * @return the value
- *
- * @throws ValueSerializationException if the deserialization failed
- */
- <T> T deserialize( ModuleDescriptor module, ValueType valueType, String input )
- throws ValueSerializationException;
-
- /**
- * Deserialize a value from a state.
- *
- * @param <T> the parametrized returned type
- * @param module the module
- * @param type the value type
- * @param input the state stream
- *
- * @return the value
- *
- * @throws ValueSerializationException if the deserialization failed
- */
- <T> T deserialize( ModuleDescriptor module, Class<?> type, InputStream input )
- throws ValueSerializationException;
-
- /**
- * Deserialize a value from a state.
- *
- * @param <T> the parametrized returned type
- * @param module the module
- * @param valueType the value type
- * @param input the state stream
- *
- * @return the value
- *
- * @throws ValueSerializationException if the deserialization failed
- */
- <T> T deserialize( ModuleDescriptor module, ValueType valueType, InputStream input )
- throws ValueSerializationException;
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/value/ValueSerialization.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/value/ValueSerialization.java b/core/api/src/main/java/org/apache/polygene/api/value/ValueSerialization.java
deleted file mode 100644
index 91c1081..0000000
--- a/core/api/src/main/java/org/apache/polygene/api/value/ValueSerialization.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.api.value;
-
-/**
- * ValueSerialization API.
- *
- * See {@link ValueSerializer} and {@link ValueDeserializer}.
- */
-public interface ValueSerialization
- extends ValueSerializer, ValueDeserializer
-{
-
- /**
- * Serialization format @Service tags.
- *
- * <p>
- * ValueSerialization implementations should be tagged with theses at assembly time so that consumers can
- * specify which format they need.
- * </p>
- */
- interface Formats
- {
-
- /**
- * Tag a ValueSerialization service that support the JSON format.
- */
- String JSON = "json";
- /**
- * Tag a ValueSerialization service that support the XML format.
- */
- String XML = "xml";
- /**
- * Tag a ValueSerialization service that support the YAML format.
- */
- String YAML = "yaml";
- }
-
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/value/ValueSerializationException.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/value/ValueSerializationException.java b/core/api/src/main/java/org/apache/polygene/api/value/ValueSerializationException.java
deleted file mode 100644
index 62faa75..0000000
--- a/core/api/src/main/java/org/apache/polygene/api/value/ValueSerializationException.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.api.value;
-
-/**
- * Thrown when an error occur during value state (de)serialization.
- */
-public class ValueSerializationException
- extends RuntimeException
-{
-
- private static final long serialVersionUID = 1L;
-
- public ValueSerializationException()
- {
- super();
- }
-
- public ValueSerializationException( String message )
- {
- super( message );
- }
-
- public ValueSerializationException( String message, Throwable cause )
- {
- super( message, cause );
- }
-
- public ValueSerializationException( Throwable cause )
- {
- super( cause.getClass().getName() + ": " + cause.getMessage(), cause );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/main/java/org/apache/polygene/api/value/ValueSerializer.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/value/ValueSerializer.java b/core/api/src/main/java/org/apache/polygene/api/value/ValueSerializer.java
deleted file mode 100644
index 736df9d..0000000
--- a/core/api/src/main/java/org/apache/polygene/api/value/ValueSerializer.java
+++ /dev/null
@@ -1,293 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.api.value;
-
-import java.io.OutputStream;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.function.Function;
-import org.apache.polygene.api.composite.AmbiguousTypeException;
-
-/**
- * Use a ValueSerializer to serialize values state.
- *
- * <p>
- * Serialized object must be one of:
- * </p>
- * <ul>
- * <li>a ValueComposite,</li>
- * <li>an EntityComposite or EntityReference,</li>
- * <li>an Iterable,</li>
- * <li>a Map,</li>
- * <li>a Plain Value.</li>
- * </ul>
- * <p>
- * Nested plain values, EntityReferences, Iterables, Maps, ValueComposites and EntityComposites are supported.
- * EntityComposites and EntityReferences are serialized as their reference string.
- * </p>
- * <p>
- * Plain values can be one of:
- * </p>
- * <ul>
- * <li>String,</li>
- * <li>Character or char,</li>
- * <li>Boolean or boolean,</li>
- * <li>Integer or int,</li>
- * <li>Long or long,</li>
- * <li>Short or short,</li>
- * <li>Byte or byte,</li>
- * <li>Float or float,</li>
- * <li>Double or double,</li>
- * <li>BigInteger,</li>
- * <li>BigDecimal,</li>
- * <li>Date,</li>
- * <li>DateTime (JodaTime),</li>
- * <li>LocalDateTime (JodaTime),</li>
- * <li>LocalDate (JodaTime).</li>
- * </ul>
- * <p>
- * Values of unknown types and all arrays are considered as {@link java.io.Serializable} and by so are serialized to
- * base64 encoded bytes using pure Java serialization. If it happens that the value is not Serializable, a
- * ValueSerializationException is thrown.
- * </p>
- * <p>
- * Having type information in the serialized payload allows to keep actual ValueComposite types and by so
- * circumvent {@link AmbiguousTypeException} when deserializing.
- * </p>
- */
-public interface ValueSerializer
-{
-
- /**
- * Factory method for a serialize function.
- *
- * @param <T> the parametrized function input type
- * @return a serialization function.
- */
- <T> Function<T, String> serialize();
-
- /**
- * Factory method for a serialize function.
- *
- * @param <T> the parametrized function input type
- * @param options ValueSerializer Options
- * @return a serialization function.
- */
- <T> Function<T, String> serialize( Options options );
-
- /**
- * Serialize the state of a value with type information.
- *
- * @param object an Object to serialize
- * @return the state
- * @throws ValueSerializationException if the Value serialization failed
- */
- String serialize( Object object )
- throws ValueSerializationException;
-
- /**
- * Serialize the state of a value.
- *
- * @param options ValueSerializer Options
- * @param object an Object to serialize
- * @return the state
- * @throws ValueSerializationException if the Value serialization failed
- */
- String serialize( Options options, Object object )
- throws ValueSerializationException;
-
- /**
- * Serialize the state of a value with type information.
- *
- * @param object an Object to serialize
- * @param output that will be used as output
- * @throws ValueSerializationException if the Value serialization failed
- */
- void serialize( Object object, OutputStream output )
- throws ValueSerializationException;
-
- /**
- * Serialize the state of a value.
- *
- * @param options ValueSerializer Options
- * @param object an Object to serialize
- * @param output that will be used as output
- * @throws ValueSerializationException if the Value serialization failed
- */
- void serialize( Options options, Object object, OutputStream output )
- throws ValueSerializationException;
-
- /**
- * Serialization options.
- */
- final class Options
- {
- /**
- * Boolean flag to include type information.
- * Default to TRUE.
- */
- public static final String INCLUDE_TYPE_INFO = "includeTypeInfo";
- public static final String MAP_ENTRIES_AS_OBJECTS = "mapentriesasobjects";
- private final Map<String, String> options = new HashMap<>();
-
- /**
- * Create new default ValueSerializer Options.
- */
- public Options()
- {
- this.options.put( INCLUDE_TYPE_INFO, "true" );
- this.options.put( MAP_ENTRIES_AS_OBJECTS, "false" );
- }
-
- /**
- * Set {@link #INCLUDE_TYPE_INFO} option to TRUE.
- * @return This
- */
- public Options withTypeInfo()
- {
- return put( INCLUDE_TYPE_INFO, true );
- }
-
- /**
- * Set {@link #INCLUDE_TYPE_INFO} option to FALSE.
- * @return This
- */
- public Options withoutTypeInfo()
- {
- return put( INCLUDE_TYPE_INFO, false );
- }
-
- public Options withMapEntriesAsObjects()
- {
- return put( MAP_ENTRIES_AS_OBJECTS, true );
- }
-
- public Options withMapEntriesAsKeyValuePairs()
- {
- return put( MAP_ENTRIES_AS_OBJECTS, false );
- }
-
- /**
- * Get Boolean option value.
- * @param option The option
- * @return The boolean value of the option, or null if absent
- */
- public Boolean getBoolean( String option )
- {
- if( !options.containsKey( option ) )
- {
- return null;
- }
- return Boolean.valueOf( options.get( option ) );
- }
-
- /**
- * Get Integer option value.
- * @param option The option
- * @return The integer value of the option, or null if absent
- */
- public Integer getInteger( String option )
- {
- if( !options.containsKey( option ) )
- {
- return null;
- }
- return Integer.valueOf( options.get( option ) );
- }
-
- /**
- * Get String option value.
- * @param option The option
- * @return The string value of the option, or null if absent
- */
- public String getString( String option )
- {
- return options.get( option );
- }
-
- /**
- * Put an option String value.
- * @param option The option
- * @param value The value
- * @return This Options instance
- */
- public Options put( String option, String value )
- {
- if( value == null )
- {
- return remove( option );
- }
- options.put( option, value );
- return this;
- }
-
- /**
- * Put an option boolean value.
- * @param option The option
- * @param value The value
- * @return This Options instance
- */
- public Options put( String option, Boolean value )
- {
- if( value == null )
- {
- return remove( option );
- }
- options.put( option, Boolean.toString( value ) );
- return this;
- }
-
- /**
- * Put an option Integer value.
- * @param option The option
- * @param value The value
- * @return This Options instance
- */
- public Options put( String option, Integer value )
- {
- if( value == null )
- {
- return remove( option );
- }
- options.put( option, value.toString() );
- return this;
- }
-
- /**
- * Remove an option value.
- * @param option The option
- * @return This Options instance
- */
- public Options remove( String option )
- {
- options.remove( option );
- return this;
- }
-
- /**
- * Get all defined options as a Map.
- * @return All defined options in a new Map
- */
- public Map<String, String> toMap()
- {
- return new HashMap<>( options );
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/test/java/org/apache/polygene/api/type/HasTypesCollectorsTest.java
----------------------------------------------------------------------
diff --git a/core/api/src/test/java/org/apache/polygene/api/type/HasTypesCollectorsTest.java b/core/api/src/test/java/org/apache/polygene/api/type/HasTypesCollectorsTest.java
new file mode 100644
index 0000000..0e92245
--- /dev/null
+++ b/core/api/src/test/java/org/apache/polygene/api/type/HasTypesCollectorsTest.java
@@ -0,0 +1,131 @@
+package org.apache.polygene.api.type;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import org.apache.polygene.api.identity.Identity;
+import org.apache.polygene.api.identity.StringIdentity;
+import org.junit.Test;
+
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+
+public class HasTypesCollectorsTest
+{
+ @Test
+ public void selectMatchingTypes()
+ {
+ List<ValueType> valueTypes = Arrays.asList(
+ ValueType.of( String.class ),
+ ValueType.of( Integer.class ),
+ ValueType.of( Number.class )
+ );
+
+ List<ValueType> number = valueTypes.stream().collect( HasTypesCollectors.matchingTypes( Number.class ) );
+ assertThat( number.size(), is( 2 ) );
+ assertThat( number.get( 0 ), equalTo( ValueType.of( Number.class ) ) );
+ assertThat( number.get( 1 ), equalTo( ValueType.of( Integer.class ) ) );
+
+ List<ValueType> integer = valueTypes.stream().collect( HasTypesCollectors.matchingTypes( Integer.class ) );
+ assertThat( integer.size(), is( 1 ) );
+ assertThat( integer.get( 0 ), equalTo( ValueType.of( Integer.class ) ) );
+ }
+
+ @Test
+ public void selectMatchingType()
+ {
+ List<ValueType> valueTypes = Arrays.asList(
+ ValueType.of( String.class ),
+ ValueType.of( Double.class ),
+ ValueType.of( Integer.class )
+ );
+
+ Optional<ValueType> number = valueTypes.stream()
+ .collect( HasTypesCollectors.matchingType( Number.class ) );
+ assertTrue( number.isPresent() );
+ assertThat( number.get(), equalTo( ValueType.of( Double.class ) ) );
+
+ Optional<ValueType> integer = valueTypes.stream()
+ .collect( HasTypesCollectors.matchingType( Integer.class ) );
+ assertTrue( integer.isPresent() );
+ assertThat( integer.get(), equalTo( ValueType.of( Integer.class ) ) );
+ }
+
+ @Test
+ public void selectMatchingValueTypes()
+ {
+ List<ValueType> valueTypes = Arrays.asList(
+ ValueType.of( String.class ),
+ ValueType.of( Number.class, Integer.class ),
+ ValueType.of( Integer.class ),
+ ValueType.of( Number.class )
+ );
+
+ List<ValueType> number = valueTypes.stream()
+ .collect( HasTypesCollectors.matchingTypes( ValueType.of( Number.class ) ) );
+ System.out.println( number );
+ assertThat( number.size(), is( 2 ) );
+ assertThat( number.get( 0 ), equalTo( ValueType.of( Number.class ) ) );
+ assertThat( number.get( 1 ), equalTo( ValueType.of( Number.class, Integer.class ) ) );
+
+ List<ValueType> integer = valueTypes.stream()
+ .collect(
+ HasTypesCollectors.matchingTypes( ValueType.of( Integer.class ) ) );
+ assertThat( integer.size(), is( 2 ) );
+ assertThat( integer.get( 0 ), equalTo( ValueType.of( Integer.class ) ) );
+ assertThat( integer.get( 1 ), equalTo( ValueType.of( Number.class, Integer.class ) ) );
+
+ List<ValueType> both = valueTypes.stream()
+ .collect( HasTypesCollectors.matchingTypes( ValueType.of( Number.class,
+ Integer.class ) ) );
+ assertThat( both.size(), is( 1 ) );
+ assertThat( both.get( 0 ), equalTo( ValueType.of( Number.class, Integer.class ) ) );
+ }
+
+ @Test
+ public void selectMatchingValueType()
+ {
+ List<ValueType> valueTypes = Arrays.asList(
+ ValueType.of( String.class ),
+ ValueType.of( Number.class, Integer.class ),
+ ValueType.of( Integer.class ),
+ ValueType.of( Number.class )
+ );
+
+ Optional<ValueType> number = valueTypes.stream()
+ .collect(
+ HasTypesCollectors.matchingType( ValueType.of( Number.class ) ) );
+ assertTrue( number.isPresent() );
+ assertThat( number.get(), equalTo( ValueType.of( Number.class ) ) );
+
+ Optional<ValueType> integer = valueTypes.stream()
+ .collect(
+ HasTypesCollectors.matchingType( ValueType.of( Integer.class ) ) );
+ assertTrue( integer.isPresent() );
+ assertThat( integer.get(), equalTo( ValueType.of( Integer.class ) ) );
+
+ Optional<ValueType> both = valueTypes.stream()
+ .collect( HasTypesCollectors.matchingType( ValueType.of( Number.class,
+ Integer.class ) ) );
+ assertTrue( both.isPresent() );
+ assertThat( both.get(), equalTo( ValueType.of( Number.class, Integer.class ) ) );
+ }
+
+ @Test
+ public void selectClosestValueTypes()
+ {
+ List<ValueType> list = new ArrayList<ValueType>()
+ {{
+ add( ValueType.of( String.class ) );
+ add( ValueType.of( Identity.class ) );
+ }};
+
+ List<ValueType> result = list.stream()
+ .collect( HasTypesCollectors.closestTypes( StringIdentity.class ) );
+ assertThat( result.size(), is( 1 ) );
+ assertThat( result.get( 0 ), equalTo( ValueType.of( Identity.class ) ) );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/test/java/org/apache/polygene/api/type/HasTypesPredicatesTest.java
----------------------------------------------------------------------
diff --git a/core/api/src/test/java/org/apache/polygene/api/type/HasTypesPredicatesTest.java b/core/api/src/test/java/org/apache/polygene/api/type/HasTypesPredicatesTest.java
new file mode 100644
index 0000000..fc87ae6
--- /dev/null
+++ b/core/api/src/test/java/org/apache/polygene/api/type/HasTypesPredicatesTest.java
@@ -0,0 +1,54 @@
+package org.apache.polygene.api.type;
+
+import java.time.LocalDate;
+import org.junit.Test;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class HasTypesPredicatesTest
+{
+ @Test
+ public void hasEqualTypePredicate()
+ {
+ assertTrue( new HasEqualType<>( Integer.class )
+ .test( ValueType.of( Integer.class ) ) );
+ assertTrue( new HasEqualType<>( Integer.class )
+ .test( ValueType.of( String.class, Integer.class ) ) );
+ assertFalse( new HasEqualType<>( Number.class )
+ .test( ValueType.of( String.class, Integer.class ) ) );
+ assertFalse( new HasEqualType<>( String.class )
+ .test( ValueType.of( LocalDate.class, Integer.class ) ) );
+
+ assertTrue( new HasEqualType<>( ValueType.of( Integer.class ) )
+ .test( ValueType.of( Integer.class ) ) );
+ assertTrue( new HasEqualType<>( ValueType.of( Integer.class ) )
+ .test( ValueType.of( String.class, Integer.class ) ) );
+ assertFalse( new HasEqualType<>( ValueType.of( Number.class ) )
+ .test( ValueType.of( String.class, Integer.class ) ) );
+ assertFalse( new HasEqualType<>( ValueType.of( String.class ) )
+ .test( ValueType.of( LocalDate.class, Integer.class ) ) );
+ }
+
+ @Test
+ public void hasAssignableTypePredicate()
+ {
+ assertTrue( new HasAssignableFromType<>( Number.class )
+ .test( ValueType.of( String.class, Integer.class ) ) );
+ assertFalse( new HasAssignableFromType<>( Integer.class )
+ .test( ValueType.of( Integer.class ) ) );
+ assertFalse( new HasAssignableFromType<>( String.class )
+ .test( ValueType.of( LocalDate.class, Integer.class ) ) );
+ }
+
+ @Test
+ public void hasEqualOrAssignablePredicate()
+ {
+ assertTrue( new HasEqualOrAssignableFromType<>( Number.class )
+ .test( ValueType.of( String.class, Integer.class ) ) );
+ assertTrue( new HasEqualOrAssignableFromType<>( Integer.class )
+ .test( ValueType.of( Integer.class ) ) );
+ assertFalse( new HasEqualOrAssignableFromType<>( String.class )
+ .test( ValueType.of( LocalDate.class, Integer.class ) ) );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/test/java/org/apache/polygene/api/type/ValueTypeFactoryTest.java
----------------------------------------------------------------------
diff --git a/core/api/src/test/java/org/apache/polygene/api/type/ValueTypeFactoryTest.java b/core/api/src/test/java/org/apache/polygene/api/type/ValueTypeFactoryTest.java
new file mode 100644
index 0000000..5b70078
--- /dev/null
+++ b/core/api/src/test/java/org/apache/polygene/api/type/ValueTypeFactoryTest.java
@@ -0,0 +1,105 @@
+package org.apache.polygene.api.type;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.concurrent.TimeUnit;
+import org.apache.polygene.api.common.UseDefaults;
+import org.apache.polygene.api.property.Property;
+import org.apache.polygene.api.value.ValueDescriptor;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.spi.module.ModuleSpi;
+import org.apache.polygene.spi.type.ValueTypeFactory;
+import org.apache.polygene.test.AbstractPolygeneTest;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.instanceOf;
+import static org.junit.Assert.assertThat;
+
+public class ValueTypeFactoryTest extends AbstractPolygeneTest
+{
+ private ValueTypeFactory valueTypeFactory;
+
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ module.values( SomeValue.class );
+ }
+
+ interface SomeValue
+ {
+ @UseDefaults
+ Property<List<String>> list();
+
+ @UseDefaults
+ Property<Map<String, Integer>> map();
+ }
+
+ @Before
+ public void setup()
+ {
+ valueTypeFactory = ( (ModuleSpi) module.instance() ).valueTypeFactory();
+ }
+
+ @Test
+ public void plainValues()
+ {
+ assertThat( valueTypeFactory.valueTypeOf( module, String.class ), equalTo( ValueType.STRING ) );
+ assertThat( valueTypeFactory.valueTypeOf( module, "" ), equalTo( ValueType.STRING ) );
+ }
+
+ @Test
+ public void enums()
+ {
+ assertThat( valueTypeFactory.valueTypeOf( module, TimeUnit.class ), instanceOf( EnumType.class ) );
+ assertThat( valueTypeFactory.valueTypeOf( module, TimeUnit.DAYS ), instanceOf( EnumType.class ) );
+ }
+
+ @Test
+ public void collections()
+ {
+ assertThat( valueTypeFactory.valueTypeOf( module, LinkedHashSet.class ),
+ instanceOf( CollectionType.class ) );
+
+ List<String> list = new ArrayList<>();
+ ValueType listValueType = valueTypeFactory.valueTypeOf( module, list );
+ assertThat( listValueType, instanceOf( CollectionType.class ) );
+ assertThat( ( (CollectionType) listValueType ).collectedType(), equalTo( ValueType.OBJECT ) );
+ }
+
+ @Test
+ public void maps()
+ {
+ assertThat( valueTypeFactory.valueTypeOf( module, TreeMap.class ), instanceOf( MapType.class ) );
+
+ HashMap<String, Integer> map = new HashMap<>();
+ ValueType mapValueType = valueTypeFactory.valueTypeOf( module, map );
+ assertThat( mapValueType, instanceOf( MapType.class ) );
+ assertThat( ( (MapType) mapValueType ).keyType(), equalTo( ValueType.OBJECT ) );
+ assertThat( ( (MapType) mapValueType ).valueType(), equalTo( ValueType.OBJECT ) );
+ }
+
+ @Test
+ public void valueComposites()
+ {
+ assertThat( valueTypeFactory.valueTypeOf( module, SomeValue.class ),
+ instanceOf( ValueCompositeType.class ) );
+ assertThat( valueTypeFactory.valueTypeOf( module, valueBuilderFactory.newValue( SomeValue.class ) ),
+ instanceOf( ValueCompositeType.class ) );
+ }
+
+ @Test
+ public void genericsAreResolvedOnValueCompositeProperties()
+ {
+ ValueDescriptor descriptor = module.typeLookup().lookupValueModel( SomeValue.class );
+ assertThat( descriptor.state().findPropertyModelByName( "list" ).valueType(),
+ equalTo( CollectionType.listOf( ValueType.STRING ) ) );
+ assertThat( descriptor.state().findPropertyModelByName( "map" ).valueType(),
+ equalTo( MapType.of( ValueType.STRING, ValueType.INTEGER ) ) );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/api/src/test/java/org/apache/polygene/api/util/CollectorsTest.java
----------------------------------------------------------------------
diff --git a/core/api/src/test/java/org/apache/polygene/api/util/CollectorsTest.java b/core/api/src/test/java/org/apache/polygene/api/util/CollectorsTest.java
index 5521b93..1beb26a 100644
--- a/core/api/src/test/java/org/apache/polygene/api/util/CollectorsTest.java
+++ b/core/api/src/test/java/org/apache/polygene/api/util/CollectorsTest.java
@@ -17,59 +17,99 @@
*/
package org.apache.polygene.api.util;
+import java.util.LinkedHashMap;
+import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import org.junit.Test;
+import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
public class CollectorsTest
{
- @Test
- public void single()
+@Test
+public void single()
+{
+ assertThat( Stream.of( 1L ).collect( Collectors.single() ), is( 1L ) );
+
+ try
+ {
+ Stream.of().collect( Collectors.single() );
+ fail( "Should have failed" );
+ }
+ catch( IllegalArgumentException ex ) {}
+ try
{
- assertThat( Stream.of( 1L ).collect( Collectors.single() ), is( 1L ) );
+ Stream.of( 1, 1 ).collect( Collectors.single() );
+ fail( "Should have failed" );
+ }
+ catch( IllegalArgumentException ex ) {}
+ try
+ {
+ Stream.of( 1, 1, 1 ).collect( Collectors.single() );
+ fail( "Should have failed" );
+ }
+ catch( IllegalArgumentException ex ) {}
+}
- try
- {
- Stream.of().collect( Collectors.single() );
- fail( "Should have failed" );
- }
- catch( IllegalArgumentException ex ) {}
- try
- {
- Stream.of( 1, 1 ).collect( Collectors.single() );
- fail( "Should have failed" );
- }
- catch( IllegalArgumentException ex ) {}
- try
- {
- Stream.of( 1, 1, 1 ).collect( Collectors.single() );
- fail( "Should have failed" );
- }
- catch( IllegalArgumentException ex ) {}
+@Test
+public void singleOrEmpty()
+{
+ assertEquals( Optional.empty(), Stream.of().collect( Collectors.singleOrEmpty() ) );
+ assertEquals( Optional.of( 1 ), Stream.of( 1 ).collect( Collectors.singleOrEmpty() ) );
+
+ try
+ {
+ Stream.of( 1, 1 ).collect( Collectors.singleOrEmpty() );
+ fail( "Should have failed" );
}
+ catch( IllegalArgumentException ex ) {}
+ try
+ {
+ Stream.of( 1, 1, 1 ).collect( Collectors.singleOrEmpty() );
+ fail( "Should have failed" );
+ }
+ catch( IllegalArgumentException ex ) {}
+}
@Test
- public void singleOrEmpty()
+ public void toMap()
{
- assertEquals( Optional.empty(), Stream.of().collect( Collectors.singleOrEmpty() ) );
- assertEquals( Optional.of( 1 ), Stream.of( 1 ).collect( Collectors.singleOrEmpty() ) );
+ Map<String, String> input = new LinkedHashMap<>();
+ input.put( "foo", "bar" );
+ input.put( "bazar", "cathedral" );
+ Map<String, String> output = input.entrySet().stream().collect( Collectors.toMap() );
+ assertThat( output.get( "foo" ), equalTo( "bar" ) );
+ assertThat( output.get( "bazar" ), equalTo( "cathedral" ) );
+ }
+ @Test
+ public void toMapRejectNullValues()
+ {
+ Map<String, String> input = new LinkedHashMap<>();
+ input.put( "foo", "bar" );
+ input.put( "bazar", null );
try
{
- Stream.of( 1, 1 ).collect( Collectors.singleOrEmpty() );
- fail( "Should have failed" );
- }
- catch( IllegalArgumentException ex ) {}
- try
- {
- Stream.of( 1, 1, 1 ).collect( Collectors.singleOrEmpty() );
- fail( "Should have failed" );
+ input.entrySet().stream().collect( Collectors.toMap() );
+ fail( "Should have failed, that's the default Map::merge behaviour" );
}
- catch( IllegalArgumentException ex ) {}
+ catch( NullPointerException expected ) {}
+ }
+
+ @Test
+ public void toMapWithNullValues()
+ {
+ Map<String, String> input = new LinkedHashMap<>();
+ input.put( "foo", "bar" );
+ input.put( "bazar", null );
+ Map<String, String> output = input.entrySet().stream().collect( Collectors.toMapWithNullValues() );
+ assertThat( output.get( "foo" ), equalTo( "bar" ) );
+ assertThat( output.get( "bazar" ), nullValue() );
}
}
[02/50] [abbrv] polygene-java git commit: Restructuring of the yeoman
generator,
to make it more easy to work with and demand naming in extensions to be
unified.
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/Heroes/webapp/styles.css
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/Heroes/webapp/styles.css b/tools/generator-polygene/app/templates/Heroes/webapp/styles.css
deleted file mode 100644
index 1774fd6..0000000
--- a/tools/generator-polygene/app/templates/Heroes/webapp/styles.css
+++ /dev/null
@@ -1,149 +0,0 @@
-/* Master Styles */
-h1 {
- color: #369;
- font-family: Arial, Helvetica, sans-serif;
- font-size: 250%;
-}
-h2, h3 {
- color: #444;
- font-family: Arial, Helvetica, sans-serif;
- font-weight: lighter;
-}
-body {
- margin: 2em;
-}
-body, input[text], button {
- color: #888;
- font-family: Cambria, Georgia;
-}
-a {
- cursor: pointer;
- cursor: hand;
-}
-button {
- font-family: Arial;
- background-color: #eee;
- border: none;
- padding: 5px 10px;
- border-radius: 4px;
- cursor: pointer;
- cursor: hand;
-}
-button:hover {
- background-color: #cfd8dc;
-}
-button:disabled {
- background-color: #eee;
- color: #aaa;
- cursor: auto;
-}
-
-/* Navigation link styles */
-nav a {
- padding: 5px 10px;
- text-decoration: none;
- margin-top: 10px;
- display: inline-block;
- background-color: #eee;
- border-radius: 4px;
-}
-nav a:visited, a:link {
- color: #607D8B;
-}
-nav a:hover {
- color: #039be5;
- background-color: #CFD8DC;
-}
-nav a.router-link-active {
- color: #039be5;
-}
-
-/* items class */
-.items {
- margin: 0 0 2em 0;
- list-style-type: none;
- padding: 0;
- width: 24em;
-}
-.items li {
- cursor: pointer;
- position: relative;
- left: 0;
- background-color: #EEE;
- margin: .5em;
- padding: .3em 0;
- height: 1.6em;
- border-radius: 4px;
-}
-.items li:hover {
- color: #607D8B;
- background-color: #DDD;
- left: .1em;
-}
-.items li.selected:hover {
- background-color: #BBD8DC;
- color: white;
-}
-.items .text {
- position: relative;
- top: -3px;
-}
-.items {
- margin: 0 0 2em 0;
- list-style-type: none;
- padding: 0;
- width: 24em;
-}
-.items li {
- cursor: pointer;
- position: relative;
- left: 0;
- background-color: #EEE;
- margin: .5em;
- padding: .3em 0;
- height: 1.6em;
- border-radius: 4px;
-}
-.items li:hover {
- color: #607D8B;
- background-color: #DDD;
- left: .1em;
-}
-.items li.selected {
- background-color: #CFD8DC;
- color: white;
-}
-
-.items li.selected:hover {
- background-color: #BBD8DC;
-}
-.items .text {
- position: relative;
- top: -3px;
-}
-.items .badge {
- display: inline-block;
- font-size: small;
- color: white;
- padding: 0.8em 0.7em 0 0.7em;
- background-color: #607D8B;
- line-height: 1em;
- position: relative;
- left: -1px;
- top: -4px;
- height: 1.8em;
- margin-right: .8em;
- border-radius: 4px 0 0 4px;
-}
-
-/* everywhere else */
-* {
- font-family: Arial, Helvetica, sans-serif;
-}
-
-
-/*
-Copyright 2016 Google Inc. All Rights Reserved.
-Use of this source code is governed by an MIT-style license that
-can be found in the LICENSE file at http://angular.io/license
-*/
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/InfrastructureLayer/CachingModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/CachingModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/CachingModule/bootstrap.tmpl
new file mode 100644
index 0000000..4945277
--- /dev/null
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/CachingModule/bootstrap.tmpl
@@ -0,0 +1,51 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.bootstrap.infrastructure;
+
+import org.apache.polygene.api.common.Visibility;
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.LayerAssembly;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.bootstrap.layered.ModuleAssembler;
+import org.apache.polygene.cache.<%- polygene.caching.toLowerCase() %>.assembly.<%- polygene.caching %>Assembler;
+
+public class <%- polygene.caching %>CachingModule
+ implements ModuleAssembler
+{
+ public static final String NAME = "<%- polygene.caching %> Caching Module";
+ private final ModuleAssembly configModule;
+
+ public <%- polygene.caching %>CachingModule( ModuleAssembly configModule )
+ {
+ this.configModule = configModule;
+ }
+
+ @Override
+ public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
+ throws AssemblyException
+ {
+ new <%- polygene.caching %>Assembler()
+ .visibleIn(Visibility.layer)
+ .withConfig( configModule, Visibility.application )
+ .assemble( module );
+
+ return module;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/InfrastructureLayer/CachingModule/module.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/CachingModule/module.js b/tools/generator-polygene/app/templates/InfrastructureLayer/CachingModule/module.js
new file mode 100644
index 0000000..474899c
--- /dev/null
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/CachingModule/module.js
@@ -0,0 +1,11 @@
+module.exports = {
+
+ write: function (p) {
+ if (p.caching !== "None") {
+
+ p.copyTemplate(p.ctx,
+ 'InfrastructureLayer/CachingModule/bootstrap.tmpl',
+ 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/infrastructure/' + p.caching + 'CachingModule.java');
+ }
+ }
+};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/InfrastructureLayer/FileConfigurationModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/FileConfigurationModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/FileConfigurationModule/bootstrap.tmpl
new file mode 100644
index 0000000..ab2ad2c
--- /dev/null
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/FileConfigurationModule/bootstrap.tmpl
@@ -0,0 +1,41 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.bootstrap.infrastructure;
+
+import org.apache.polygene.api.common.Visibility;
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.LayerAssembly;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.bootstrap.layered.ModuleAssembler;
+import org.apache.polygene.library.fileconfig.FileConfigurationAssembler;
+
+public class FileConfigurationModule
+ implements ModuleAssembler
+{
+ public static String NAME;
+
+ @Override
+ public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
+ throws AssemblyException
+ {
+ new FileConfigurationAssembler().visibleIn( Visibility.layer ).assemble( module );
+ return module;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/InfrastructureLayer/FileConfigurationModule/module.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/FileConfigurationModule/module.js b/tools/generator-polygene/app/templates/InfrastructureLayer/FileConfigurationModule/module.js
new file mode 100644
index 0000000..7ce44ef
--- /dev/null
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/FileConfigurationModule/module.js
@@ -0,0 +1,8 @@
+module.exports = {
+
+ write: function (p) {
+ p.copyTemplate(p.ctx,
+ 'InfrastructureLayer/FileConfigurationModule/bootstrap.tmpl',
+ 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/infrastructure/FileConfigurationModule.java');
+ }
+};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/InfrastructureLayer/IndexingModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/IndexingModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/IndexingModule/bootstrap.tmpl
new file mode 100644
index 0000000..a1f9479
--- /dev/null
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/IndexingModule/bootstrap.tmpl
@@ -0,0 +1,52 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.bootstrap.infrastructure;
+
+import org.apache.polygene.api.common.Visibility;
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.LayerAssembly;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.bootstrap.layered.ModuleAssembler;
+import org.apache.polygene.index.<%- polygene.indexing.toLowerCase() %>.assembly.<%- polygene.indexing %>IndexingAssembler;
+
+public class <%- polygene.indexing %>IndexingModule
+ implements ModuleAssembler
+{
+ public static final String NAME = "<%- polygene.indexing %> Indexing Module";
+ private final ModuleAssembly configModule;
+
+ public <%- polygene.indexing %>IndexingModule( ModuleAssembly configModule )
+ {
+ this.configModule = configModule;
+ }
+
+ @Override
+ public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
+ throws AssemblyException
+ {
+ new <%- polygene.indexing %>IndexingAssembler()
+ .visibleIn( Visibility.application )
+ .identifiedBy( "indexing-<%- polygene.indexing %>" )
+ .withConfig( configModule, Visibility.application )
+ .assemble( module );
+ return module;
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/InfrastructureLayer/IndexingModule/module.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/IndexingModule/module.js b/tools/generator-polygene/app/templates/InfrastructureLayer/IndexingModule/module.js
new file mode 100644
index 0000000..e34ef57
--- /dev/null
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/IndexingModule/module.js
@@ -0,0 +1,8 @@
+module.exports = {
+
+ write: function (p) {
+ p.copyTemplate(p.ctx,
+ 'InfrastructureLayer/IndexingModule/bootstrap.tmpl',
+ 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/infrastructure/' + p.indexing + 'IndexingModule.java');
+ }
+};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/InfrastructureLayer/MetricsModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/MetricsModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/MetricsModule/bootstrap.tmpl
new file mode 100644
index 0000000..2bbc875
--- /dev/null
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/MetricsModule/bootstrap.tmpl
@@ -0,0 +1,48 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.bootstrap.infrastructure;
+
+import org.apache.polygene.api.common.Visibility;
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.LayerAssembly;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.bootstrap.layered.ModuleAssembler;
+import org.apache.polygene.metrics.<%- polygene.metrics.toLowerCase() %>.assembly.<%- polygene.metrics %>MetricsAssembler;
+
+public class <%- polygene.metrics %>MetricsModule
+ implements ModuleAssembler
+{
+ public static final String NAME = "<%- polygene.metrics %> Metrics Module";
+ private final ModuleAssembly configModule;
+
+ public <%- polygene.metrics %>MetricsModule( ModuleAssembly configModule )
+ {
+ this.configModule = configModule;
+ }
+
+ @Override
+ public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
+ throws AssemblyException
+ {
+ new <%- polygene.metrics %>Assembler(Visibility.application, Visibility.module).assemble( module );
+ return module;
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/InfrastructureLayer/MetricsModule/module.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/MetricsModule/module.js b/tools/generator-polygene/app/templates/InfrastructureLayer/MetricsModule/module.js
new file mode 100644
index 0000000..6100c5c
--- /dev/null
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/MetricsModule/module.js
@@ -0,0 +1,10 @@
+module.exports = {
+
+ write: function (p) {
+ if (p.metrics !== "None") {
+ p.copyTemplate(p.ctx,
+ 'InfrastructureLayer/MetricsModule/bootstrap.tmpl',
+ 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/infrastructure/' + p.metrics + 'MetricsModule.java');
+ }
+ }
+};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl
new file mode 100644
index 0000000..ea455cd
--- /dev/null
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl
@@ -0,0 +1,43 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.bootstrap.infrastructure;
+
+import org.apache.polygene.api.common.Visibility;
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.LayerAssembly;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.bootstrap.layered.ModuleAssembler;
+import org.apache.polygene.valueserialization.<%- polygene.serialization.toLowerCase() %>.<%- polygene.serialization %>ValueSerializationAssembler;
+
+public class <%- polygene.serialization %>ValueSerializationModule
+ implements ModuleAssembler
+{
+ public static final String NAME = "<%- polygene.serialization %> Serialization Module";
+
+ @Override
+ public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
+ throws AssemblyException
+ {
+ new <%- polygene.serialization %>ValueSerializationAssembler()
+ .visibleIn( Visibility.application )
+ .assemble( module );
+ return module;
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/module.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/module.js b/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/module.js
new file mode 100644
index 0000000..7e60e99
--- /dev/null
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/module.js
@@ -0,0 +1,8 @@
+module.exports = {
+
+ write: function (p) {
+ p.copyTemplate(p.ctx,
+ 'InfrastructureLayer/SerializationModule/bootstrap.tmpl',
+ 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/infrastructure/' + p.serialization + 'ValueSerializationModule.java');
+ }
+};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/InfrastructureLayer/StorageModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/StorageModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/StorageModule/bootstrap.tmpl
new file mode 100644
index 0000000..8e68e2f
--- /dev/null
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/StorageModule/bootstrap.tmpl
@@ -0,0 +1,51 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.bootstrap.infrastructure;
+
+import org.apache.polygene.api.common.Visibility;
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.LayerAssembly;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.bootstrap.layered.ModuleAssembler;
+import org.apache.polygene.entitystore.<%- polygene.entitystore.toLowerCase() %>.assembly.<%- polygene.entitystore %>EntityStoreAssembler;
+
+public class <%- polygene.entitystore %>StorageModule
+ implements ModuleAssembler
+{
+ public static final String NAME = "<%- polygene.entitystore %> Storage Module";
+ private final ModuleAssembly configModule;
+
+ public <%- polygene.entitystore %>StorageModule( ModuleAssembly configModule )
+ {
+ this.configModule = configModule;
+ }
+
+ @Override
+ public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
+ throws AssemblyException
+ {
+ new <%- polygene.entitystore %>EntityStoreAssembler()
+ .visibleIn( Visibility.application )
+ .withConfig( configModule, Visibility.application )
+ .identifiedBy( "entitystore-<%- polygene.entitystore %>" )
+ .assemble( module );
+ return module;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/InfrastructureLayer/StorageModule/module.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/StorageModule/module.js b/tools/generator-polygene/app/templates/InfrastructureLayer/StorageModule/module.js
new file mode 100644
index 0000000..51488e0
--- /dev/null
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/StorageModule/module.js
@@ -0,0 +1,8 @@
+module.exports = {
+
+ write: function (p) {
+ p.copyTemplate(p.ctx,
+ 'InfrastructureLayer/StorageModule/bootstrap.tmpl',
+ 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/infrastructure/' + p.entitystore + 'StorageModule.java');
+ }
+};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/InfrastructureLayer/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/bootstrap.tmpl
index 2b86a4d..d02d6a9 100644
--- a/tools/generator-polygene/app/templates/InfrastructureLayer/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/bootstrap.tmpl
@@ -41,10 +41,15 @@ public class InfrastructureLayer extends LayeredLayerAssembler
throws AssemblyException
{
createModule( layer, FileConfigurationModule.class );
-
+ createModule( layer, <%= polygene.serialization %>ValueSerializationModule.class );
+<% if( polygene.metrics !== "None" ) { %>
+ createModule( layer, <%= polygene.metrics %>MetricsModule.class );
+<% } %>
+<% if( polygene.caching !== "None" ) { %>
+ createModule( layer, <%= polygene.caching %>CachingModule.class );
+<% } %>
new <%= polygene.entitystore %>StorageModule( configModule ).assemble( layer, layer.module( <%= polygene.entitystore %>StorageModule.NAME ) );
new <%= polygene.indexing %>IndexingModule( configModule ).assemble( layer, layer.module( <%= polygene.indexing %>IndexingModule.NAME ) );
- new <%= polygene.serialization %>SerializationModule().assemble( layer, layer.module( <%= polygene.serialization %>SerializationModule.NAME ) );
return layer;
}
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/InfrastructureLayer/layer.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/layer.js b/tools/generator-polygene/app/templates/InfrastructureLayer/layer.js
new file mode 100644
index 0000000..ca844d1
--- /dev/null
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/layer.js
@@ -0,0 +1,10 @@
+
+module.exports = {
+
+ write: function (p) {
+ p.copyTemplate(p.ctx,
+ 'InfrastructureLayer/bootstrap.tmpl',
+ 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/infrastructure/InfrastructureLayer.java');
+ p.copyModules(__dirname );
+ }
+};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/JacksonSerializationModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/JacksonSerializationModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/JacksonSerializationModule/bootstrap.tmpl
deleted file mode 100644
index afc0439..0000000
--- a/tools/generator-polygene/app/templates/JacksonSerializationModule/bootstrap.tmpl
+++ /dev/null
@@ -1,43 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.bootstrap.infrastructure;
-
-import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.LayerAssembly;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.bootstrap.layered.ModuleAssembler;
-import org.apache.polygene.valueserialization.jackson.JacksonValueSerializationAssembler;
-
-public class JacksonSerializationModule
- implements ModuleAssembler
-{
- public static final String NAME = "Jackson Serialization Module";
-
- @Override
- public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
- throws AssemblyException
- {
- new JacksonValueSerializationAssembler()
- .visibleIn( Visibility.application )
- .assemble( module );
- return module;
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/NoCachingModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/NoCachingModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/NoCachingModule/bootstrap.tmpl
deleted file mode 100644
index b5ebe24..0000000
--- a/tools/generator-polygene/app/templates/NoCachingModule/bootstrap.tmpl
+++ /dev/null
@@ -1,46 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.bootstrap.infrastructure;
-
-import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.LayerAssembly;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.bootstrap.layered.ModuleAssembler;
-import org.apache.polygene.entitystore.file.assembly.FileEntityStoreAssembler;
-
-public class NoCachingModule
- implements ModuleAssembler
-{
- public static final String NAME = "No Caching Module";
- private final ModuleAssembly configModule;
-
- public NoCachingModule( ModuleAssembly configModule )
- {
- this.configModule = configModule;
- }
-
- @Override
- public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
- throws AssemblyException
- {
- return module;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/RdfIndexingModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/RdfIndexingModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/RdfIndexingModule/bootstrap.tmpl
deleted file mode 100644
index 8376a2b..0000000
--- a/tools/generator-polygene/app/templates/RdfIndexingModule/bootstrap.tmpl
+++ /dev/null
@@ -1,50 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.bootstrap.infrastructure;
-
-import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.LayerAssembly;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.bootstrap.layered.ModuleAssembler;
-import org.apache.polygene.index.rdf.assembly.RdfNativeSesameStoreAssembler;
-import org.apache.polygene.library.rdf.repository.NativeConfiguration;
-
-public class RdfIndexingModule
- implements ModuleAssembler
-{
- public static final String NAME = "Rdf Indexing Module";
- private final ModuleAssembly configModule;
-
- public RdfIndexingModule( ModuleAssembly configModule )
- {
- this.configModule = configModule;
- }
-
- @Override
- public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
- throws AssemblyException
- {
- configModule.entities( NativeConfiguration.class ).visibleIn( Visibility.application );
- new RdfNativeSesameStoreAssembler(Visibility.application, Visibility.module).assemble( module );
- return module;
- }
-}
-
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/RestApiModule/HardcodedSecurityRepositoryMixin.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/RestApiModule/HardcodedSecurityRepositoryMixin.tmpl b/tools/generator-polygene/app/templates/RestApiModule/HardcodedSecurityRepositoryMixin.tmpl
deleted file mode 100644
index fc73bf6..0000000
--- a/tools/generator-polygene/app/templates/RestApiModule/HardcodedSecurityRepositoryMixin.tmpl
+++ /dev/null
@@ -1,54 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.model.security;
-
-import java.util.Collections;
-import java.util.List;
-import org.apache.polygene.api.unitofwork.concern.UnitOfWorkPropagation;
-
-public class HardcodedSecurityRepositoryMixin
- implements SecurityRepository
-{
-
- @Override
- public boolean verifyPassword( String userName, String password )
- {
- if( userName.equals("admin") && password.equals("secret") )
- {
- return true;
- }
- if( userName.equals("user") && password.equals("123") )
- {
- return true;
- }
- return false;
- }
-
- @UnitOfWorkPropagation
- public List<String> findRoleNamesOfUser( String name )
- {
- if( "admin".equals( name ) )
- {
- return Collections.singletonList("admin");
- }
- return Collections.singletonList("user");
- }
-}
-
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/RestApiModule/SecurityRepository.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/RestApiModule/SecurityRepository.tmpl b/tools/generator-polygene/app/templates/RestApiModule/SecurityRepository.tmpl
deleted file mode 100644
index f007485..0000000
--- a/tools/generator-polygene/app/templates/RestApiModule/SecurityRepository.tmpl
+++ /dev/null
@@ -1,36 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.model.security;
-
-import java.util.List;
-import org.apache.polygene.api.concern.Concerns;
-import org.apache.polygene.api.unitofwork.concern.UnitOfWorkConcern;
-import org.apache.polygene.api.unitofwork.concern.UnitOfWorkPropagation;
-
-@Concerns( UnitOfWorkConcern.class )
-public interface SecurityRepository
-{
- @UnitOfWorkPropagation
- boolean verifyPassword( String user, String password );
-
- @UnitOfWorkPropagation
- List<String> findRoleNamesOfUser( String name );
-}
-
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/RestApiModule/SimpleEnroler.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/RestApiModule/SimpleEnroler.tmpl b/tools/generator-polygene/app/templates/RestApiModule/SimpleEnroler.tmpl
deleted file mode 100644
index 3b21a9d..0000000
--- a/tools/generator-polygene/app/templates/RestApiModule/SimpleEnroler.tmpl
+++ /dev/null
@@ -1,52 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.rest.security;
-
-import java.util.ArrayList;
-import java.util.List;
-import org.apache.polygene.api.injection.scope.Service;
-import org.apache.polygene.api.injection.scope.Uses;
-import org.restlet.Application;
-import org.restlet.data.ClientInfo;
-import org.restlet.security.Enroler;
-import org.restlet.security.Role;
-import <%= packageName %>.model.security.SecurityRepository;
-
-
-public class SimpleEnroler
- implements Enroler
-{
- @Service
- private SecurityRepository repository;
-
- @Uses
- private Application application;
-
- @Override
- public void enrole( ClientInfo clientInfo )
- {
- org.restlet.security.User user = clientInfo.getUser();
- String name = user.getName();
- List<String> roleList = repository.findRoleNamesOfUser( name );
- List<Role> restletRoles = new ArrayList<>();
- roleList.stream().map( roleName -> Role.get( application, roleName ) );
- clientInfo.setRoles( restletRoles );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/RestApiModule/SimpleVerifier.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/RestApiModule/SimpleVerifier.tmpl b/tools/generator-polygene/app/templates/RestApiModule/SimpleVerifier.tmpl
deleted file mode 100644
index e8b7e11..0000000
--- a/tools/generator-polygene/app/templates/RestApiModule/SimpleVerifier.tmpl
+++ /dev/null
@@ -1,46 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.rest.security;
-
-import org.apache.polygene.api.injection.scope.Service;
-import org.restlet.security.SecretVerifier;
-import org.restlet.security.Verifier;
-import <%= packageName %>.model.security.SecurityRepository;
-
-public class SimpleVerifier extends SecretVerifier
- implements Verifier
-{
- @Service
- private SecurityRepository repository;
-
- @Override
- public int verify( String user, char[] secret )
- {
- if( user == null || secret == null )
- {
- return RESULT_UNKNOWN;
- }
- if( repository.verifyPassword( user, String.valueOf( secret ) ) )
- {
- return RESULT_VALID;
- }
- return RESULT_INVALID;
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/RestApiModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/RestApiModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/RestApiModule/bootstrap.tmpl
deleted file mode 100644
index 202776d..0000000
--- a/tools/generator-polygene/app/templates/RestApiModule/bootstrap.tmpl
+++ /dev/null
@@ -1,56 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.bootstrap.connectivity;
-
-import <%= packageName %>.rest.security.SimpleEnroler;
-import <%= packageName %>.rest.security.SimpleVerifier;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.LayerAssembly;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.bootstrap.layered.ModuleAssembler;
-import org.apache.polygene.library.restlet.assembly.RestletCrudConnectivityAssembler;
-import org.apache.polygene.library.restlet.resource.EntryPoint;
-<% if( hasFeature('sample (heroes) web application') ) { %>
-import <%= packageName %>.model.heroes.Hero;
-<% } -%>
-
-public class RestApiModule
- implements ModuleAssembler
-{
- public static String NAME;
-
- @Override
- public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
- throws AssemblyException
- {
- module.objects( SimpleVerifier.class, SimpleEnroler.class);
-
- new RestletCrudConnectivityAssembler().assemble( module );
- module.values( EntryPoint.class );
-<% if( hasFeature('sample (heroes) web application') ) { -%>
- module.values( Hero.class );
- module.services( Hero.class );
-<% } else { -%>
- module.values( /* add value types */ );
- module.services( /* add services */ );
-<% } -%>
- return module;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/SecurityModule/SecurityRepository.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/SecurityModule/SecurityRepository.tmpl b/tools/generator-polygene/app/templates/SecurityModule/SecurityRepository.tmpl
deleted file mode 100644
index c503999..0000000
--- a/tools/generator-polygene/app/templates/SecurityModule/SecurityRepository.tmpl
+++ /dev/null
@@ -1,35 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.model.security;
-
-import java.util.List;
-import org.apache.polygene.api.concern.Concerns;
-import org.apache.polygene.api.unitofwork.concern.UnitOfWorkConcern;
-import org.apache.polygene.api.unitofwork.concern.UnitOfWorkPropagation;
-
-@Concerns( UnitOfWorkConcern.class )
-public interface SecurityRepository
-{
- @UnitOfWorkPropagation
- boolean verifyPassword( String user, String password );
-
- @UnitOfWorkPropagation
- List<String> findRoleNamesOfUser( String name );
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/SecurityModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/SecurityModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/SecurityModule/bootstrap.tmpl
deleted file mode 100644
index b944612..0000000
--- a/tools/generator-polygene/app/templates/SecurityModule/bootstrap.tmpl
+++ /dev/null
@@ -1,46 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.bootstrap.domain;
-
-import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.LayerAssembly;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.bootstrap.layered.ModuleAssembler;
-import <%= packageName %>.model.security.SecurityRepository;
-import <%= packageName %>.model.security.HardcodedSecurityRepositoryMixin;
-
-public class SecurityModule
- implements ModuleAssembler
-{
- public static String NAME;
-
- @Override
- public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
- throws AssemblyException
- {
- module.services( SecurityRepository.class )
- .withMixins( HardcodedSecurityRepositoryMixin.class )
- .visibleIn( Visibility.application )
- .instantiateOnStartup();
-
- return module;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/SolrIndexingModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/SolrIndexingModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/SolrIndexingModule/bootstrap.tmpl
deleted file mode 100644
index 2644f78..0000000
--- a/tools/generator-polygene/app/templates/SolrIndexingModule/bootstrap.tmpl
+++ /dev/null
@@ -1,49 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.bootstrap.infrastructure;
-
-import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.LayerAssembly;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.bootstrap.layered.ModuleAssembler;
-import org.apache.polygene.index.rdf.assembly.RdfNativeSesameStoreAssembler;
-import org.apache.polygene.library.rdf.repository.NativeConfiguration;
-
-public class SolrIndexingModule
- implements ModuleAssembler
-{
- public static final String NAME = "Solr Indexing Module";
- private final ModuleAssembly configModule;
-
- public SolrIndexingModule( ModuleAssembly configModule )
- {
- this.configModule = configModule;
- }
-
- @Override
- public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
- throws AssemblyException
- {
- new SolrAssembler(Visibility.application, Visibility.module).assemble( module );
- return module;
- }
-}
-
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/StorageModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/StorageModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/StorageModule/bootstrap.tmpl
deleted file mode 100644
index 467fadd..0000000
--- a/tools/generator-polygene/app/templates/StorageModule/bootstrap.tmpl
+++ /dev/null
@@ -1,51 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.bootstrap.infrastructure;
-
-import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.LayerAssembly;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.bootstrap.layered.ModuleAssembler;
-import org.apache.polygene.entitystore.<%- polygene.entitystore.toLowerCase() %>.assembly.<%- polygene.entitystore %>EntityStoreAssembler;
-
-public class <%- polygene.entitystore %>StorageModule
- implements ModuleAssembler
-{
- public static final String NAME = "<%- polygene.entitystore %> Storage Module";
- private final ModuleAssembly configModule;
-
- public <%- polygene.entitystore %>StorageModule( ModuleAssembly configModule )
- {
- this.configModule = configModule;
- }
-
- @Override
- public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
- throws AssemblyException
- {
- new <%- polygene.entitystore %>EntityStoreAssembler()
- .visibleIn( Visibility.application )
- .withConfig( configModule, Visibility.application )
- .identifiedBy( "<%- polygene.entitystore %>store" )
- .assemble( module );
- return module;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/buildtool/build.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/buildtool/build.js b/tools/generator-polygene/app/templates/buildtool/build.js
new file mode 100644
index 0000000..7df3c75
--- /dev/null
+++ b/tools/generator-polygene/app/templates/buildtool/build.js
@@ -0,0 +1,22 @@
+module.exports = {
+
+ write: function (p) {
+ copyBuildFile(p, "app");
+ copyBuildFile(p, "bootstrap");
+ copyBuildFile(p, "model");
+ copyBuildFile(p, "rest");
+ p.copyTemplate(p.ctx, 'buildtool/gradle-root.tmpl', 'build.gradle');
+ p.copyTemplate(p.ctx, 'buildtool/settings.tmpl', 'settings.gradle');
+ p.copyTemplate(p.ctx, 'buildtool/gradlew.tmpl', 'gradlew');
+ p.copyTemplate(p.ctx, 'buildtool/gradlew-bat.tmpl', 'gradlew.bat');
+
+ p.ctx.fs.copy(p.ctx.templatePath('buildtool/gradle-wrapper.jar_'), p.ctx.destinationPath('gradle/wrapper/gradle-wrapper.jar'));
+ p.ctx.fs.copy(p.ctx.templatePath('buildtool/gradle-wrapper.properties_'), p.ctx.destinationPath('gradle/wrapper/gradle-wrapper.properties'));
+ }
+};
+
+function copyBuildFile(p, subproject) {
+ p.copyTemplate(p.ctx,
+ 'buildtool/gradle-' + subproject + '.tmpl',
+ subproject + '/build.gradle');
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/buildtool/gradle-bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/buildtool/gradle-bootstrap.tmpl b/tools/generator-polygene/app/templates/buildtool/gradle-bootstrap.tmpl
index ceb0541..bc0a651 100644
--- a/tools/generator-polygene/app/templates/buildtool/gradle-bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/buildtool/gradle-bootstrap.tmpl
@@ -33,4 +33,12 @@ dependencies {
compile "org.apache.polygene.extensions:org.apache.polygene.extension.indexing-<%= polygene.indexing.toLowerCase() %>:$polygeneVersion"
compile "org.apache.polygene.extensions:org.apache.polygene.extension.valueserialization-<%= polygene.serialization.toLowerCase() %>:$polygeneVersion"
+<% if( polygene.caching !== "None" ) { %>
+ compile "org.apache.polygene.extensions:org.apache.polygene.extension.cache-<%= polygene.caching.toLowerCase() %>:$polygeneVersion"
+<% } %>
+
+<% if( polygene.metrics !== "None" ) { %>
+ compile "org.apache.polygene.extensions:org.apache.polygene.extension.metrics-<%= polygene.metrics.toLowerCase() %>:$polygeneVersion"
+<% } %>
+
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/buildtool/settings.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/buildtool/settings.tmpl b/tools/generator-polygene/app/templates/buildtool/settings.tmpl
index 3016193..2d8e164 100644
--- a/tools/generator-polygene/app/templates/buildtool/settings.tmpl
+++ b/tools/generator-polygene/app/templates/buildtool/settings.tmpl
@@ -22,7 +22,7 @@ include 'app',
'model',
'rest'
-rootProject.name = '<%= polygene.entitystore %>'
+rootProject.name = '<%= polygene.name %>'
validateProject(rootProject, "")
[30/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/MapEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/MapEntityStoreMixin.java b/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/MapEntityStoreMixin.java
index dc4db58..ef9816c 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/MapEntityStoreMixin.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/MapEntityStoreMixin.java
@@ -14,12 +14,9 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
- *
*/
package org.apache.polygene.spi.entitystore.helpers;
-import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.time.Instant;
@@ -28,7 +25,15 @@ import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.function.Function;
import java.util.stream.Stream;
+import javax.json.Json;
+import javax.json.JsonArray;
+import javax.json.JsonArrayBuilder;
+import javax.json.JsonException;
+import javax.json.JsonObject;
+import javax.json.JsonObjectBuilder;
+import javax.json.JsonValue;
import org.apache.polygene.api.common.Optional;
import org.apache.polygene.api.common.QualifiedName;
import org.apache.polygene.api.entity.EntityDescriptor;
@@ -39,15 +44,11 @@ import org.apache.polygene.api.identity.StringIdentity;
import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.injection.scope.Structure;
import org.apache.polygene.api.injection.scope.This;
-import org.apache.polygene.api.service.qualifier.Tagged;
import org.apache.polygene.api.structure.Application;
import org.apache.polygene.api.structure.ModuleDescriptor;
-import org.apache.polygene.api.type.ValueType;
import org.apache.polygene.api.unitofwork.NoSuchEntityTypeException;
import org.apache.polygene.api.usecase.Usecase;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.api.value.ValueSerializationException;
-import org.apache.polygene.spi.PolygeneSPI;
+import org.apache.polygene.serialization.javaxjson.JavaxJson;
import org.apache.polygene.spi.entity.EntityState;
import org.apache.polygene.spi.entity.EntityStatus;
import org.apache.polygene.spi.entitystore.DefaultEntityStoreUnitOfWork;
@@ -56,11 +57,7 @@ import org.apache.polygene.spi.entitystore.EntityStoreException;
import org.apache.polygene.spi.entitystore.EntityStoreSPI;
import org.apache.polygene.spi.entitystore.EntityStoreUnitOfWork;
import org.apache.polygene.spi.entitystore.StateCommitter;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.json.JSONTokener;
-import org.json.JSONWriter;
+import org.apache.polygene.spi.serialization.JsonSerialization;
/**
* Implementation of EntityStore that works with an implementation of MapEntityStore.
@@ -80,14 +77,10 @@ public class MapEntityStoreMixin
private EntityStoreSPI entityStoreSpi;
@Structure
- private PolygeneSPI spi;
-
- @Structure
private Application application;
@Service
- @Tagged( ValueSerialization.Formats.JSON )
- private ValueSerialization valueSerialization;
+ private JsonSerialization jsonSerialization;
@Optional
@Service
@@ -97,58 +90,70 @@ public class MapEntityStoreMixin
private IdentityGenerator identityGenerator;
@Override
- public void activateMapEntityStore()
- throws Exception
- {
- }
+ public void activateMapEntityStore() {}
// EntityStore
@Override
- public EntityStoreUnitOfWork newUnitOfWork( ModuleDescriptor module, Usecase usecaseMetaInfo, Instant currentTime )
+ public EntityStoreUnitOfWork newUnitOfWork( ModuleDescriptor module, Usecase usecase, Instant currentTime )
{
- return new DefaultEntityStoreUnitOfWork( module, entityStoreSpi, newUnitOfWorkId(), usecaseMetaInfo, currentTime );
+ return new DefaultEntityStoreUnitOfWork( module, entityStoreSpi, newUnitOfWorkId(),
+ usecase, currentTime );
}
// EntityStoreSPI
@Override
- public EntityState newEntityState( EntityStoreUnitOfWork unitOfWork,
- EntityReference reference,
- EntityDescriptor entityDescriptor
- )
+ public EntityState newEntityState( EntityStoreUnitOfWork uow,
+ EntityReference reference, EntityDescriptor entityDescriptor )
{
- return new DefaultEntityState( unitOfWork.currentTime(), reference, entityDescriptor );
+ return new DefaultEntityState( uow.currentTime(), reference, entityDescriptor );
}
@Override
- public synchronized EntityState entityStateOf( EntityStoreUnitOfWork unitofwork,
- ModuleDescriptor module,
- EntityReference reference
- )
+ public synchronized EntityState entityStateOf( EntityStoreUnitOfWork uow,
+ ModuleDescriptor module, EntityReference reference )
{
- Reader in = mapEntityStore.get( reference );
- return readEntityState( module, in );
+ try
+ {
+ Reader in = mapEntityStore.get( reference );
+ EntityState loadedState = readEntityState( module, in );
+ if( loadedState.status() == EntityStatus.UPDATED )
+ {
+ List<EntityState> migrated = new ArrayList<>( 1 );
+ migrated.add( loadedState );
+ synchMigratedEntities( migrated );
+ }
+ return loadedState;
+ }
+ catch( EntityStoreException ex )
+ {
+ throw ex;
+ }
+ catch( Exception ex )
+ {
+ throw new EntityStoreException( ex );
+ }
}
@Override
- public synchronized String versionOf( EntityStoreUnitOfWork unitofwork,
- EntityReference reference
- )
+ public synchronized String versionOf( EntityStoreUnitOfWork uow, EntityReference reference )
{
- Reader in = mapEntityStore.get( reference );
try
{
- JSONObject jsonObject = new JSONObject( new JSONTokener( in ) );
- return jsonObject.getString( JSONKeys.VERSION );
+ Reader in = mapEntityStore.get( reference );
+ return Json.createReader( in ).readObject().getString( JSONKeys.VERSION );
}
- catch( JSONException e )
+ catch( EntityStoreException ex )
{
- throw new EntityStoreException( e );
+ throw ex;
+ }
+ catch( Exception ex )
+ {
+ throw new EntityStoreException( ex );
}
}
@Override
- public StateCommitter applyChanges( final EntityStoreUnitOfWork unitofwork, final Iterable<EntityState> state
- )
+ public StateCommitter applyChanges( EntityStoreUnitOfWork uow, Iterable<EntityState> state )
throws EntityStoreException
{
return new StateCommitter()
@@ -158,34 +163,47 @@ public class MapEntityStoreMixin
{
try
{
- mapEntityStore.applyChanges( changer -> {
- for( EntityState entityState : state )
+ mapEntityStore.applyChanges(
+ changer ->
{
- DefaultEntityState state1 = (DefaultEntityState) entityState;
- if( state1.status().equals( EntityStatus.NEW ) )
+ for( EntityState entityState : state )
{
- try (Writer writer = changer.newEntity( state1.entityReference(), state1.entityDescriptor() ))
+ DefaultEntityState state1 = (DefaultEntityState) entityState;
+ String newVersion = uow.identity().toString();
+ Instant lastModified = uow.currentTime();
+ if( state1.status().equals( EntityStatus.NEW ) )
{
- writeEntityState( state1, writer, unitofwork.identity().toString(), unitofwork.currentTime() );
+ try( Writer writer = changer.newEntity( state1.entityReference(),
+ state1.entityDescriptor() ) )
+ {
+ writeEntityState( state1, writer, newVersion, lastModified );
+ }
}
- }
- else if( state1.status().equals( EntityStatus.UPDATED ) )
- {
- try (Writer writer = changer.updateEntity( state1.entityReference(), state1.entityDescriptor() ))
+ else if( state1.status().equals( EntityStatus.UPDATED ) )
{
- writeEntityState( state1, writer, unitofwork.identity().toString(), unitofwork.currentTime() );
+ MapEntityStore.MapChange mapChange = new MapEntityStore.MapChange(
+ state1.entityReference(), state1.entityDescriptor(),
+ state1.version(), newVersion, lastModified
+ );
+ try( Writer writer = changer.updateEntity( mapChange ) )
+ {
+ writeEntityState( state1, writer, newVersion, lastModified );
+ }
+ }
+ else if( state1.status().equals( EntityStatus.REMOVED ) )
+ {
+ changer.removeEntity( state1.entityReference(), state1.entityDescriptor() );
}
}
- else if( state1.status().equals( EntityStatus.REMOVED ) )
- {
- changer.removeEntity( state1.entityReference(), state1.entityDescriptor() );
- }
- }
- } );
+ } );
+ }
+ catch( EntityStoreException ex )
+ {
+ throw ex;
}
- catch( IOException e )
+ catch( Exception ex )
{
- throw new EntityStoreException( e );
+ throw new EntityStoreException( ex );
}
}
@@ -197,62 +215,90 @@ public class MapEntityStoreMixin
}
@Override
- public Stream<EntityState> entityStates( final ModuleDescriptor module )
+ public Stream<EntityState> entityStates( ModuleDescriptor module )
{
- List<EntityState> migrated = new ArrayList<>();
- return mapEntityStore
- .entityStates()
- .map( reader ->
- {
- EntityState entity = readEntityState( module, reader );
- if( entity.status() == EntityStatus.UPDATED )
- {
- migrated.add( entity );
- // Synch back 100 at a time
- if( migrated.size() > 100 )
- {
- try
- {
- synchMigratedEntities( migrated );
- }
- catch( IOException e )
- {
- throw new EntityStoreException( "Synchronization of Migrated Entities failed.", e );
- }
- }
- }
- return entity;
- } )
- .onClose( () ->
- {
- // Synch any remaining migrated entities
- if( !migrated.isEmpty() )
- {
- try
- {
- synchMigratedEntities( migrated );
- }
- catch( IOException e )
- {
- throw new EntityStoreException( "Synchronization of Migrated Entities failed.", e );
- }
- }
- } );
+ try
+ {
+ Stream<Reader> stateStream = mapEntityStore.entityStates();
+ List<EntityState> migrated = new ArrayList<>();
+ String migrationErrorMsg = "Synchronization of Migrated Entities failed.";
+ Function<Reader, EntityState> function = reader ->
+ {
+ EntityState entity = readEntityState( module, reader );
+ if( entity.status() == EntityStatus.UPDATED )
+ {
+ migrated.add( entity );
+ // Sync back 100 at a time
+ if( migrated.size() > 100 )
+ {
+ try
+ {
+ synchMigratedEntities( migrated );
+ }
+ catch( EntityStoreException ex )
+ {
+ throw ex;
+ }
+ catch( Exception ex )
+ {
+ throw new EntityStoreException( migrationErrorMsg, ex );
+ }
+ }
+ }
+ return entity;
+ };
+ Runnable closer = () ->
+ {
+ // Sync any remaining migrated entities
+ if( !migrated.isEmpty() )
+ {
+ try
+ {
+ synchMigratedEntities( migrated );
+ }
+ catch( EntityStoreException ex )
+ {
+ throw ex;
+ }
+ catch( Exception ex )
+ {
+ throw new EntityStoreException( migrationErrorMsg, ex );
+ }
+ }
+ };
+ return stateStream.map( function ).onClose( closer );
+ }
+ catch( EntityStoreException ex )
+ {
+ throw ex;
+ }
+ catch( Exception ex )
+ {
+ throw new EntityStoreException( ex );
+ }
}
private void synchMigratedEntities( final List<EntityState> migratedEntities )
- throws IOException
+ throws Exception
{
- mapEntityStore.applyChanges( changer -> {
- for( EntityState migratedEntity : migratedEntities )
+ mapEntityStore.applyChanges(
+ changer ->
{
- DefaultEntityState state = (DefaultEntityState) migratedEntity;
- try (Writer writer = changer.updateEntity( state.entityReference(), state.entityDescriptor() ))
+ for( EntityState migratedEntity : migratedEntities )
{
- writeEntityState( state, writer, state.version(), state.lastModified() );
+ DefaultEntityState state = (DefaultEntityState) migratedEntity;
+ String version = state.version();
+ Instant lastModified = state.lastModified();
+ MapEntityStore.MapChange mapChange = new MapEntityStore.MapChange(
+ state.entityReference(), state.entityDescriptor(),
+ version, version, lastModified
+ );
+ try( Writer writer = changer.updateEntity( mapChange ) )
+ {
+ writeEntityState( state, writer, version, lastModified );
+ }
}
- }
- } );
+ } );
migratedEntities.clear();
}
@@ -261,87 +307,63 @@ public class MapEntityStoreMixin
return identityGenerator.generate( EntityStore.class );
}
- protected void writeEntityState(DefaultEntityState state, Writer writer, String version, Instant lastModified )
+ protected void writeEntityState( DefaultEntityState state, Writer writer, String version, Instant lastModified )
throws EntityStoreException
{
try
{
- JSONWriter json = new JSONWriter( writer );
- JSONWriter properties = json.object().
- key( JSONKeys.IDENTITY ).value( state.entityReference().identity() ).
- key( JSONKeys.APPLICATION_VERSION ).value( application.version() ).
- key( JSONKeys.TYPE ).value( state.entityDescriptor().types().findFirst().get().getName() ).
- key( JSONKeys.VERSION ).value( version ).
- key( JSONKeys.MODIFIED ).value( lastModified.toEpochMilli() ).
- key( JSONKeys.PROPERTIES ).object();
+ JsonObjectBuilder json = Json.createObjectBuilder();
+ json.add( JSONKeys.IDENTITY, state.entityReference().identity().toString() );
+ json.add( JSONKeys.APPLICATION_VERSION, application.version() );
+ json.add( JSONKeys.TYPE, state.entityDescriptor().primaryType().getName() );
+ json.add( JSONKeys.VERSION, version );
+ json.add( JSONKeys.MODIFIED, lastModified.toEpochMilli() );
+ JsonObjectBuilder properties = Json.createObjectBuilder();
EntityDescriptor entityType = state.entityDescriptor();
- entityType.state().properties().forEach( persistentProperty -> {
- Object value = state.properties().get( persistentProperty.qualifiedName() );
- try
- {
- json.key( persistentProperty.qualifiedName().name() );
- if( value == null || ValueType.isPrimitiveValue( value ) )
- {
- json.value( value );
- }
- else
- {
- String serialized = valueSerialization.serialize( value );
- if( serialized.startsWith( "{" ) )
- {
- json.value( new JSONObject( serialized ) );
- }
- else if( serialized.startsWith( "[" ) )
- {
- json.value( new JSONArray( serialized ) );
- }
- else
- {
- json.value( serialized );
- }
- }
- }
- catch( JSONException e )
+ entityType.state().properties().forEach(
+ persistentProperty ->
{
- throw new ValueSerializationException( "Unable to write property " + persistentProperty, e );
- }
- } );
-
- JSONWriter associations = properties.endObject().key( JSONKeys.ASSOCIATIONS ).object();
- for( Map.Entry<QualifiedName, EntityReference> stateNameEntityReferenceEntry : state.associations()
- .entrySet() )
+ Object value = state.properties().get( persistentProperty.qualifiedName() );
+ JsonValue jsonValue = jsonSerialization.toJson( value );
+ properties.add( persistentProperty.qualifiedName().name(), jsonValue );
+ } );
+ json.add( JSONKeys.PROPERTIES, properties.build() );
+
+ JsonObjectBuilder associations = Json.createObjectBuilder();
+ for( Map.Entry<QualifiedName, EntityReference> entry : state.associations().entrySet() )
{
- EntityReference value = stateNameEntityReferenceEntry.getValue();
- associations.key( stateNameEntityReferenceEntry.getKey().name() ).
- value( value != null ? value.identity() : null );
+ EntityReference value = entry.getValue();
+ associations.add( entry.getKey().name(), value == null ? null : value.identity().toString() );
}
+ json.add( JSONKeys.ASSOCIATIONS, associations.build() );
- JSONWriter manyAssociations = associations.endObject().key( JSONKeys.MANY_ASSOCIATIONS ).object();
- for( Map.Entry<QualifiedName, List<EntityReference>> stateNameListEntry : state.manyAssociations()
- .entrySet() )
+ JsonObjectBuilder manyAssociations = Json.createObjectBuilder();
+ for( Map.Entry<QualifiedName, List<EntityReference>> entry : state.manyAssociations().entrySet() )
{
- JSONWriter assocs = manyAssociations.key( stateNameListEntry.getKey().name() ).array();
- for( EntityReference entityReference : stateNameListEntry.getValue() )
+ JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
+ for( EntityReference entityReference : entry.getValue() )
{
- assocs.value( entityReference.identity() );
+ arrayBuilder.add( entityReference.identity().toString() );
}
- assocs.endArray();
+ manyAssociations.add( entry.getKey().name(), arrayBuilder.build() );
}
+ json.add( JSONKeys.MANY_ASSOCIATIONS, manyAssociations.build() );
- JSONWriter namedAssociations = manyAssociations.endObject().key( JSONKeys.NAMED_ASSOCIATIONS ).object();
- for( Map.Entry<QualifiedName, Map<String, EntityReference>> stateNameMapEntry : state.namedAssociations()
- .entrySet() )
+ JsonObjectBuilder namedAssociations = Json.createObjectBuilder();
+ for( Map.Entry<QualifiedName, Map<String, EntityReference>> entry : state.namedAssociations().entrySet() )
{
- JSONWriter assocs = namedAssociations.key( stateNameMapEntry.getKey().name() ).object();
- for( Map.Entry<String, EntityReference> namedRef : stateNameMapEntry.getValue().entrySet() )
+ JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
+ for( Map.Entry<String, EntityReference> namedRef : entry.getValue().entrySet() )
{
- assocs.key( namedRef.getKey() ).value( namedRef.getValue().identity() );
+ objectBuilder.add( namedRef.getKey(), namedRef.getValue().identity().toString() );
}
- assocs.endObject();
+ namedAssociations.add( entry.getKey().name(), objectBuilder.build() );
}
- namedAssociations.endObject().endObject();
+ json.add( JSONKeys.NAMED_ASSOCIATIONS, namedAssociations.build() );
+ JsonObject jsonState = json.build();
+ Json.createWriter( writer ).write( jsonState );
}
- catch( JSONException e )
+ catch( Exception e )
{
throw new EntityStoreException( "Could not store EntityState", e );
}
@@ -352,31 +374,38 @@ public class MapEntityStoreMixin
{
try
{
- JSONObject jsonObject = new JSONObject( new JSONTokener( entityState ) );
+ JsonObject parsedState = Json.createReader( entityState ).readObject();
+ JsonObjectBuilder jsonStateBuilder = JavaxJson.toBuilder( parsedState );
final EntityStatus[] status = { EntityStatus.LOADED };
- String version = jsonObject.getString( JSONKeys.VERSION );
- Instant modified = Instant.ofEpochMilli(jsonObject.getLong( JSONKeys.MODIFIED ));
- Identity identity = new StringIdentity(jsonObject.getString( JSONKeys.IDENTITY ));
+ String version = parsedState.getString( JSONKeys.VERSION );
+ Instant modified = Instant.ofEpochMilli( parsedState.getJsonNumber( JSONKeys.MODIFIED ).longValueExact() );
+ Identity identity = new StringIdentity( parsedState.getString( JSONKeys.IDENTITY ) );
// Check if version is correct
- String currentAppVersion = jsonObject.optString( JSONKeys.APPLICATION_VERSION, "0.0" );
- if( !currentAppVersion.equals( application.version() ) )
+ JsonObject state;
+ String currentAppVersion = parsedState.getString( JSONKeys.APPLICATION_VERSION, "0.0" );
+ if( currentAppVersion.equals( application.version() ) )
+ {
+ state = jsonStateBuilder.build();
+ }
+ else
{
if( migration != null )
{
- migration.migrate( jsonObject, application.version(), this );
+ state = migration.migrate( jsonStateBuilder.build(), application.version(), this );
}
else
{
// Do nothing - set version to be correct
- jsonObject.put( JSONKeys.APPLICATION_VERSION, application.version() );
+ jsonStateBuilder.add( JSONKeys.APPLICATION_VERSION, application.version() );
+ state = jsonStateBuilder.build();
}
// State changed
status[ 0 ] = EntityStatus.UPDATED;
}
- String type = jsonObject.getString( JSONKeys.TYPE );
+ String type = state.getString( JSONKeys.TYPE );
EntityDescriptor entityDescriptor = module.entityDescriptor( type );
if( entityDescriptor == null )
@@ -385,107 +414,101 @@ public class MapEntityStoreMixin
}
Map<QualifiedName, Object> properties = new HashMap<>();
- JSONObject props = jsonObject.getJSONObject( JSONKeys.PROPERTIES );
- entityDescriptor.state().properties().forEach( propertyDescriptor -> {
- Object jsonValue;
- try
+ JsonObject props = state.getJsonObject( JSONKeys.PROPERTIES );
+ entityDescriptor.state().properties().forEach(
+ property ->
{
- jsonValue = props.get( propertyDescriptor.qualifiedName().name() );
- if( JSONObject.NULL.equals( jsonValue ) )
+ try
{
- properties.put( propertyDescriptor.qualifiedName(), null );
+ JsonValue jsonValue = props.get( property.qualifiedName().name() );
+ Object value = jsonSerialization.fromJson( module, property.valueType(), jsonValue );
+ properties.put( property.qualifiedName(), value );
}
- else
+ catch( JsonException e )
{
- Object value = valueSerialization.deserialize( module, propertyDescriptor.valueType(), jsonValue
- .toString() );
- properties.put( propertyDescriptor.qualifiedName(), value );
+ // Value not found, default it
+ Object initialValue = property.resolveInitialValue( module );
+ properties.put( property.qualifiedName(), initialValue );
+ status[ 0 ] = EntityStatus.UPDATED;
}
- }
- catch( JSONException e )
- {
- // Value not found, default it
- Object initialValue = propertyDescriptor.resolveInitialValue(module);
- properties.put( propertyDescriptor.qualifiedName(), initialValue );
- status[ 0 ] = EntityStatus.UPDATED;
- }
- } );
+ } );
Map<QualifiedName, EntityReference> associations = new HashMap<>();
- JSONObject assocs = jsonObject.getJSONObject( JSONKeys.ASSOCIATIONS );
- entityDescriptor.state().associations().forEach( associationType -> {
- try
+ JsonObject assocs = state.getJsonObject( JSONKeys.ASSOCIATIONS );
+ entityDescriptor.state().associations().forEach(
+ association ->
{
- Object jsonValue = assocs.get( associationType.qualifiedName().name() );
- EntityReference value = jsonValue == JSONObject.NULL
- ? null
- : EntityReference.parseEntityReference( (String) jsonValue );
- associations.put( associationType.qualifiedName(), value );
- }
- catch( JSONException e )
- {
- // Association not found, default it to null
- associations.put( associationType.qualifiedName(), null );
- status[ 0 ] = EntityStatus.UPDATED;
- }
- } );
+ try
+ {
+ String jsonValue = assocs.getString( association.qualifiedName().name(), null );
+ EntityReference value = jsonValue == null
+ ? null
+ : EntityReference.parseEntityReference( jsonValue );
+ associations.put( association.qualifiedName(), value );
+ }
+ catch( JsonException e )
+ {
+ // Association not found, default it to null
+ associations.put( association.qualifiedName(), null );
+ status[ 0 ] = EntityStatus.UPDATED;
+ }
+ } );
- JSONObject manyAssocs = jsonObject.getJSONObject( JSONKeys.MANY_ASSOCIATIONS );
+ JsonObject manyAssocs = state.getJsonObject( JSONKeys.MANY_ASSOCIATIONS );
Map<QualifiedName, List<EntityReference>> manyAssociations = new HashMap<>();
- entityDescriptor.state().manyAssociations().forEach( manyAssociationType -> {
- List<EntityReference> references = new ArrayList<>();
- try
+ entityDescriptor.state().manyAssociations().forEach(
+ association ->
{
- JSONArray jsonValues = manyAssocs.getJSONArray( manyAssociationType.qualifiedName().name() );
- for( int i = 0; i < jsonValues.length(); i++ )
+ List<EntityReference> references = new ArrayList<>();
+ try
{
- Object jsonValue = jsonValues.getString( i );
- EntityReference value = jsonValue == JSONObject.NULL
- ? null
- : EntityReference.parseEntityReference( (String) jsonValue );
- references.add( value );
+ JsonArray jsonValues = manyAssocs.getJsonArray( association.qualifiedName().name() );
+ for( int i = 0; i < jsonValues.size(); i++ )
+ {
+ String jsonValue = jsonValues.getString( i, null );
+ EntityReference value = jsonValue == null
+ ? null
+ : EntityReference.parseEntityReference( jsonValue );
+ references.add( value );
+ }
+ manyAssociations.put( association.qualifiedName(), references );
}
- manyAssociations.put( manyAssociationType.qualifiedName(), references );
- }
- catch( JSONException e )
- {
- // ManyAssociation not found, default to empty one
- manyAssociations.put( manyAssociationType.qualifiedName(), references );
- }
- } );
+ catch( JsonException e )
+ {
+ // ManyAssociation not found, default to empty one
+ manyAssociations.put( association.qualifiedName(), references );
+ }
+ } );
- JSONObject namedAssocs = jsonObject.getJSONObject( JSONKeys.NAMED_ASSOCIATIONS );
+ JsonObject namedAssocs = state.getJsonObject( JSONKeys.NAMED_ASSOCIATIONS );
Map<QualifiedName, Map<String, EntityReference>> namedAssociations = new HashMap<>();
- entityDescriptor.state().namedAssociations().forEach( namedAssociationType -> {
- Map<String, EntityReference> references = new LinkedHashMap<>();
- try
+ entityDescriptor.state().namedAssociations().forEach(
+ association ->
{
- JSONObject jsonValues = namedAssocs.getJSONObject( namedAssociationType.qualifiedName().name() );
- JSONArray names = jsonValues.names();
- if( names != null )
+ Map<String, EntityReference> references = new LinkedHashMap<>();
+ try
{
- for( int idx = 0; idx < names.length(); idx++ )
+ JsonObject jsonValues = namedAssocs.getJsonObject( association.qualifiedName().name() );
+ for( String name : jsonValues.keySet() )
{
- String name = names.getString( idx );
- Object value = jsonValues.get( name );
- EntityReference ref = value == JSONObject.NULL
+ String value = jsonValues.getString( name, null );
+ EntityReference ref = value == null
? null
- : EntityReference.parseEntityReference( (String) value );
+ : EntityReference.parseEntityReference( value );
references.put( name, ref );
}
+ namedAssociations.put( association.qualifiedName(), references );
}
- namedAssociations.put( namedAssociationType.qualifiedName(), references );
- }
- catch( JSONException e )
- {
- // NamedAssociation not found, default to empty one
- namedAssociations.put( namedAssociationType.qualifiedName(), references );
- }
- } );
+ catch( JsonException e )
+ {
+ // NamedAssociation not found, default to empty one
+ namedAssociations.put( association.qualifiedName(), references );
+ }
+ } );
return new DefaultEntityState( version,
modified,
- EntityReference.create(identity),
+ EntityReference.create( identity ),
status[ 0 ],
entityDescriptor,
properties,
@@ -494,25 +517,26 @@ public class MapEntityStoreMixin
namedAssociations
);
}
- catch( JSONException e )
+ catch( Exception e )
{
throw new EntityStoreException( e );
}
}
@Override
- public JSONObject jsonStateOf( String id )
- throws IOException
+ public JsonObject jsonStateOf( String id )
{
- JSONObject jsonObject;
- try (Reader reader = mapEntityStore.get( EntityReference.parseEntityReference( id ) ))
+ try( Reader reader = mapEntityStore.get( EntityReference.parseEntityReference( id ) ) )
+ {
+ return Json.createReader( reader ).readObject();
+ }
+ catch( EntityStoreException ex )
{
- jsonObject = new JSONObject( new JSONTokener( reader ) );
+ throw ex;
}
- catch( JSONException e )
+ catch( Exception ex )
{
- throw new IOException( e );
+ throw new EntityStoreException( ex );
}
- return jsonObject;
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/Migration.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/Migration.java b/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/Migration.java
index 4b5e8e6..6a8ebfb 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/Migration.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/Migration.java
@@ -20,14 +20,14 @@
package org.apache.polygene.spi.entitystore.helpers;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.JsonException;
+import javax.json.JsonObject;
/**
* State Migration SPI.
*/
public interface Migration
{
- boolean migrate( JSONObject state, String toVersion, StateStore stateStore )
- throws JSONException;
+ JsonObject migrate( JsonObject state, String toVersion, StateStore stateStore )
+ throws JsonException;
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/StateStore.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/StateStore.java b/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/StateStore.java
index 1f1f728..8aa9e6e 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/StateStore.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/entitystore/helpers/StateStore.java
@@ -20,14 +20,13 @@
package org.apache.polygene.spi.entitystore.helpers;
-import java.io.IOException;
-import org.json.JSONObject;
+import javax.json.JsonObject;
+import org.apache.polygene.spi.entitystore.EntityStoreException;
/**
* StateStore SPI.
*/
public interface StateStore
{
- JSONObject jsonStateOf( String id )
- throws IOException;
+ JsonObject jsonStateOf( String id ) throws EntityStoreException;
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/module/ModuleSpi.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/module/ModuleSpi.java b/core/spi/src/main/java/org/apache/polygene/spi/module/ModuleSpi.java
index 8aa7c0d..eccc612 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/module/ModuleSpi.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/module/ModuleSpi.java
@@ -21,10 +21,10 @@ package org.apache.polygene.spi.module;
import org.apache.polygene.api.identity.IdentityGenerator;
import org.apache.polygene.api.metrics.MetricsProvider;
+import org.apache.polygene.api.serialization.Serialization;
import org.apache.polygene.api.structure.Module;
-import org.apache.polygene.api.structure.TypeLookup;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.spi.entitystore.EntityStore;
+import org.apache.polygene.spi.type.ValueTypeFactory;
public interface ModuleSpi extends Module
{
@@ -32,9 +32,9 @@ public interface ModuleSpi extends Module
IdentityGenerator identityGenerator();
- ValueSerialization valueSerialization();
-
- TypeLookup typeLookup();
+ Serialization serialization();
MetricsProvider metricsProvider();
+
+ ValueTypeFactory valueTypeFactory();
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinaryDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinaryDeserializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinaryDeserializer.java
new file mode 100644
index 0000000..a8f2c2c
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinaryDeserializer.java
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.spi.serialization;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.UncheckedIOException;
+import java.util.Base64;
+import org.apache.polygene.api.structure.ModuleDescriptor;
+import org.apache.polygene.api.type.ValueType;
+
+import static java.util.stream.Collectors.joining;
+
+public abstract class AbstractBinaryDeserializer extends AbstractDeserializer
+{
+ @Override
+ public <T> T deserialize( ModuleDescriptor module, ValueType valueType, Reader state )
+ {
+ String stateString;
+ try( BufferedReader buffer = new BufferedReader( state ) )
+ {
+ stateString = buffer.lines().collect( joining( "\n" ) );
+ }
+ catch( IOException ex )
+ {
+ throw new UncheckedIOException( ex );
+ }
+ byte[] decoded = Base64.getDecoder().decode( stateString );
+ return deserialize( module, valueType, new ByteArrayInputStream( decoded ) );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinarySerializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinarySerializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinarySerializer.java
new file mode 100644
index 0000000..e673ad7
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinarySerializer.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.spi.serialization;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.io.Writer;
+import java.util.Base64;
+import org.apache.polygene.api.common.Optional;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+/**
+ * Base Binary Serializer.
+ *
+ * Implementations work on bytes, this base serializer encode these bytes in Base64 to produce Strings.
+ */
+public abstract class AbstractBinarySerializer extends AbstractSerializer
+{
+ @Override
+ public void serialize( Options options, Writer writer, @Optional Object object )
+ {
+ try
+ {
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ serialize( options, output, object );
+ byte[] base64 = Base64.getEncoder().encode( output.toByteArray() );
+ writer.write( new String( base64, UTF_8 ) );
+ }
+ catch( IOException ex )
+ {
+ throw new UncheckedIOException( ex );
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractDeserializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractDeserializer.java
new file mode 100644
index 0000000..17982f3
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractDeserializer.java
@@ -0,0 +1,155 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.spi.serialization;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.io.Reader;
+import java.io.StringReader;
+import java.util.function.Function;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+import org.apache.polygene.api.entity.EntityReference;
+import org.apache.polygene.api.serialization.Deserializer;
+import org.apache.polygene.api.structure.ModuleDescriptor;
+import org.apache.polygene.api.type.CollectionType;
+import org.apache.polygene.api.type.MapType;
+import org.apache.polygene.api.type.ValueType;
+import org.apache.polygene.spi.module.ModuleSpi;
+
+public abstract class AbstractDeserializer implements Deserializer
+{
+ protected static final ValueType ENTITY_REF_LIST_VALUE_TYPE = CollectionType.listOf( EntityReference.class );
+ protected static final ValueType ENTITY_REF_MAP_VALUE_TYPE = MapType.of( String.class, EntityReference.class );
+
+ @Override
+ public <T> T deserialize( ModuleDescriptor module, ValueType valueType, String state )
+ {
+ return deserialize( module, valueType, new StringReader( state ) );
+ }
+
+ @Override
+ public <T> Function<String, T> deserializeFunction( ModuleDescriptor module, ValueType valueType )
+ {
+ return state -> deserialize( module, valueType, new StringReader( state ) );
+ }
+
+ @Override
+ public <T> Stream<T> deserializeEach( ModuleDescriptor module, ValueType valueType, Iterable<String> states )
+ {
+ return StreamSupport.stream( states.spliterator(), false )
+ .map( state -> deserialize( module, valueType, new StringReader( state ) ) );
+ }
+
+ @Override
+ public <T> Stream<T> deserializeEach( ModuleDescriptor module, ValueType valueType, String... states )
+ {
+ return Stream.of( states ).map( state -> deserialize( module, valueType, new StringReader( state ) ) );
+ }
+
+ @Override
+ public <T> T fromBytes( ModuleDescriptor module, ValueType valueType, byte[] bytes )
+ {
+ return deserialize( module, valueType, new ByteArrayInputStream( bytes ) );
+ }
+
+ @Override
+ public <T> Function<byte[], T> fromBytesFunction( ModuleDescriptor module, ValueType valueType )
+ {
+ return bytes -> deserialize( module, valueType, new ByteArrayInputStream( bytes ) );
+ }
+
+ @Override
+ public <T> Stream<T> fromBytesEach( ModuleDescriptor module, ValueType valueType, Iterable<byte[]> states )
+ {
+ return StreamSupport.stream( states.spliterator(), false )
+ .map( bytes -> deserialize( module, valueType, new ByteArrayInputStream( bytes ) ) );
+ }
+
+ @Override
+ public <T> Stream<T> fromBytesEach( ModuleDescriptor module, ValueType valueType, byte[]... states )
+ {
+ return Stream.of( states ).map( bytes -> deserialize( module, valueType, new ByteArrayInputStream( bytes ) ) );
+ }
+
+ @Override
+ public <T> T deserialize( ModuleDescriptor module, Class<T> type, InputStream state )
+ {
+ return deserialize( module, valueTypeOf( module, type ), state );
+ }
+
+ @Override
+ public <T> T deserialize( ModuleDescriptor module, Class<T> type, Reader state )
+ {
+ return deserialize( module, valueTypeOf( module, type ), state );
+ }
+
+ @Override
+ public <T> T deserialize( ModuleDescriptor module, Class<T> type, String state )
+ {
+ return deserialize( module, valueTypeOf( module, type ), state );
+ }
+
+ @Override
+ public <T> Function<String, T> deserializeFunction( ModuleDescriptor module, Class<T> type )
+ {
+ return deserializeFunction( module, valueTypeOf( module, type ) );
+ }
+
+ @Override
+ public <T> Stream<T> deserializeEach( ModuleDescriptor module, Class<T> type, Iterable<String> states )
+ {
+ return deserializeEach( module, valueTypeOf( module, type ), states );
+ }
+
+ @Override
+ public <T> Stream<T> deserializeEach( ModuleDescriptor module, Class<T> type, String... states )
+ {
+ return deserializeEach( module, valueTypeOf( module, type ), states );
+ }
+
+ @Override
+ public <T> T fromBytes( ModuleDescriptor module, Class<T> type, byte[] bytes )
+ {
+ return fromBytes( module, valueTypeOf( module, type ), bytes );
+ }
+
+ @Override
+ public <T> Function<byte[], T> fromBytesFunction( ModuleDescriptor module, Class<T> type )
+ {
+ return fromBytesFunction( module, valueTypeOf( module, type ) );
+ }
+
+ @Override
+ public <T> Stream<T> fromBytesEach( ModuleDescriptor module, Class<T> type, Iterable<byte[]> states )
+ {
+ return fromBytesEach( module, valueTypeOf( module, type ), states );
+ }
+
+ @Override
+ public <T> Stream<T> fromBytesEach( ModuleDescriptor module, Class<T> type, byte[]... states )
+ {
+ return fromBytesEach( module, valueTypeOf( module, type ), states );
+ }
+
+ private ValueType valueTypeOf( ModuleDescriptor module, Class<?> type )
+ {
+ // TODO Remove (ModuleSpi) cast
+ return ( (ModuleSpi) module.instance() ).valueTypeFactory().valueTypeOf( module, type );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractSerializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractSerializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractSerializer.java
new file mode 100644
index 0000000..b5f10ff
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractSerializer.java
@@ -0,0 +1,147 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.spi.serialization;
+
+import java.io.ByteArrayOutputStream;
+import java.io.OutputStream;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.util.function.Function;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+import org.apache.polygene.api.common.Optional;
+import org.apache.polygene.api.serialization.Serializer;
+
+public abstract class AbstractSerializer implements Serializer
+{
+ @Override
+ public void serialize( Writer writer, @Optional Object object )
+ {
+ serialize( Options.DEFAULT, writer, object );
+ }
+
+ @Override
+ public void serialize( OutputStream output, @Optional Object object )
+ {
+ serialize( Options.DEFAULT, output, object );
+ }
+
+ @Override
+ public String serialize( Options options, @Optional Object object )
+ {
+ StringWriter writer = new StringWriter();
+ serialize( options, writer, object );
+ return writer.toString();
+ }
+
+ @Override
+ public String serialize( @Optional Object object )
+ {
+ return serialize( Options.DEFAULT, object );
+ }
+
+ @Override
+ public <T> Function<T, String> serializeFunction( Options options )
+ {
+ return object -> serialize( options, object );
+ }
+
+ @Override
+ public <T> Function<T, String> serializeFunction()
+ {
+ return object -> serialize( Options.DEFAULT, object );
+ }
+
+ @Override
+ public Stream<String> serializeEach( Options options, Iterable<Object> objects )
+ {
+ return StreamSupport.stream( objects.spliterator(), false )
+ .map( object -> serialize( options, object ) );
+ }
+
+ @Override
+ public Stream<String> serializeEach( Iterable<Object> objects )
+ {
+ return StreamSupport.stream( objects.spliterator(), false )
+ .map( object -> serialize( Options.DEFAULT, object ) );
+ }
+
+ @Override
+ public Stream<String> serializeEach( Options options, Object... objects )
+ {
+ return Stream.of( objects ).map( object -> serialize( options, object ) );
+ }
+
+ @Override
+ public Stream<String> serializeEach( Object... objects )
+ {
+ return Stream.of( objects ).map( object -> serialize( Options.DEFAULT, object ) );
+ }
+
+ @Override
+ public byte[] toBytes( Options options, @Optional Object object )
+ {
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ serialize( options, output, object );
+ return output.toByteArray();
+ }
+
+ @Override
+ public byte[] toBytes( @Optional Object object )
+ {
+ return toBytes( Options.DEFAULT, object );
+ }
+
+ @Override
+ public <T> Function<T, byte[]> toBytesFunction( Options options )
+ {
+ return object -> toBytes( options, object );
+ }
+
+ @Override
+ public <T> Function<T, byte[]> toBytesFunction()
+ {
+ return object -> toBytes( Options.DEFAULT, object );
+ }
+
+ @Override
+ public Stream<byte[]> toBytesEach( Options options, Iterable<Object> objects )
+ {
+ return StreamSupport.stream( objects.spliterator(), false )
+ .map( object -> toBytes( options, object ) );
+ }
+
+ @Override
+ public Stream<byte[]> toBytesEach( Iterable<Object> objects )
+ {
+ return StreamSupport.stream( objects.spliterator(), false )
+ .map( object -> toBytes( Options.DEFAULT, object ) );
+ }
+
+ @Override
+ public Stream<byte[]> toBytesEach( Options options, Object... objects )
+ {
+ return Stream.of( objects ).map( object -> toBytes( options, object ) );
+ }
+
+ @Override
+ public Stream<byte[]> toBytesEach( Object... objects )
+ {
+ return Stream.of( objects ).map( object -> toBytes( Options.DEFAULT, object ) );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextDeserializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextDeserializer.java
new file mode 100644
index 0000000..0575489
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextDeserializer.java
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.spi.serialization;
+
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import org.apache.polygene.api.structure.ModuleDescriptor;
+import org.apache.polygene.api.type.ValueType;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+public abstract class AbstractTextDeserializer extends AbstractDeserializer
+{
+ @Override
+ public <T> T deserialize( ModuleDescriptor module, ValueType valueType, InputStream state )
+ {
+ return deserialize( module, valueType, new InputStreamReader( state, UTF_8 ) );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextSerializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextSerializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextSerializer.java
new file mode 100644
index 0000000..3d8bb16
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextSerializer.java
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.spi.serialization;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.StringWriter;
+import java.io.UncheckedIOException;
+import org.apache.polygene.api.common.Optional;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+/**
+ * Base Text Serializer.
+ *
+ * Implementations work on Strings, this base serializer encode these strings in UTF-8 to produce bytes.
+ */
+public abstract class AbstractTextSerializer extends AbstractSerializer
+{
+ public void serialize( Options options, OutputStream output, @Optional Object object )
+ {
+ try
+ {
+ StringWriter writer = new StringWriter();
+ serialize( options, writer, object );
+ output.write( writer.toString().getBytes( UTF_8 ) );
+ }
+ catch( IOException ex )
+ {
+ throw new UncheckedIOException( ex );
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonDeserializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonDeserializer.java
new file mode 100644
index 0000000..84c8993
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonDeserializer.java
@@ -0,0 +1,164 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.spi.serialization;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.UncheckedIOException;
+import java.util.function.Function;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+import javax.json.Json;
+import javax.json.JsonObject;
+import javax.json.JsonReader;
+import javax.json.JsonValue;
+import javax.json.stream.JsonParser;
+import javax.json.stream.JsonParsingException;
+import org.apache.polygene.api.serialization.Deserializer;
+import org.apache.polygene.api.structure.ModuleDescriptor;
+import org.apache.polygene.api.type.ValueType;
+import org.apache.polygene.spi.module.ModuleSpi;
+
+import static java.util.stream.Collectors.joining;
+
+public interface JsonDeserializer extends Deserializer
+{
+ <T> T fromJson( ModuleDescriptor module, ValueType valueType, JsonValue state );
+
+ default <T> Function<JsonValue, T> fromJsonFunction( ModuleDescriptor module, ValueType valueType )
+ {
+ return state -> fromJson( module, valueType, state );
+ }
+
+ default <T> Stream<T> fromJsonEach( ModuleDescriptor module, ValueType valueType, Stream<JsonValue> states )
+ {
+ return states.map( fromJsonFunction( module, valueType ) );
+ }
+
+ default <T> Stream<T> fromJsonEach( ModuleDescriptor module, ValueType valueType, Iterable<JsonValue> states )
+ {
+ return fromJsonEach( module, valueType, StreamSupport.stream( states.spliterator(), false ) );
+ }
+
+ default <T> Stream<T> fromJsonEach( ModuleDescriptor module, ValueType valueType, JsonValue... states )
+ {
+ return fromJsonEach( module, valueType, Stream.of( states ) );
+ }
+
+ default <T> T fromJson( ModuleDescriptor module, Class<T> type, JsonValue state )
+ {
+ // TODO Remove (ModuleSpi) cast
+ ValueType valueType = ( (ModuleSpi) module.instance() ).valueTypeFactory().valueTypeOf( module, type );
+ return fromJson( module, valueType, state );
+ }
+
+ default <T> Function<JsonValue, T> fromJson( ModuleDescriptor module, Class<T> type )
+ {
+ return state -> fromJson( module, type, state );
+ }
+
+ default <T> Stream<T> fromJsonEach( ModuleDescriptor module, Class<T> valueType, Stream<JsonValue> states )
+ {
+ return states.map( fromJson( module, valueType ) );
+ }
+
+ default <T> Stream<T> fromJsonEach( ModuleDescriptor module, Class<T> valueType, Iterable<JsonValue> states )
+ {
+ return fromJsonEach( module, valueType, StreamSupport.stream( states.spliterator(), false ) );
+ }
+
+ default <T> Stream<T> fromJsonEach( ModuleDescriptor module, Class<T> valueType, JsonValue... states )
+ {
+ return fromJsonEach( module, valueType, Stream.of( states ) );
+ }
+
+ @Override
+ default <T> T deserialize( ModuleDescriptor module, ValueType valueType, Reader state )
+ {
+ // JSR-353 Does not allow reading "out of structure" values
+ // See https://www.jcp.org/en/jsr/detail?id=353
+ // And commented JsonReader#readValue() method in the javax.json API
+ // BUT, it will be part of the JsonReader contract in the next version
+ // See https://www.jcp.org/en/jsr/detail?id=374
+ // Implementation by provider is optional though, so we'll always need a default implementation here.
+ // Fortunately, JsonParser has new methods allowing to read structures while parsing so it will be easy to do.
+ // In the meantime, a poor man's implementation reading the json into memory will do.
+ // TODO Revisit values out of structure JSON deserialization when JSR-374 is out
+ String stateString;
+ try( BufferedReader buffer = new BufferedReader( state ) )
+ {
+ stateString = buffer.lines().collect( joining( "\n" ) );
+ }
+ catch( IOException ex )
+ {
+ throw new UncheckedIOException( ex );
+ }
+ // We want plain Strings, BigDecimals, BigIntegers to be deserialized even when unquoted
+ Function<String, T> plainValueFunction = string ->
+ {
+ String poorMans = "{\"value\":" + string + "}";
+ JsonObject poorMansJson = Json.createReader( new StringReader( poorMans ) ).readObject();
+ JsonValue value = poorMansJson.get( "value" );
+ return fromJson( module, valueType, value );
+ };
+ Function<String, T> outOfStructureFunction = string ->
+ {
+ // Is this an unquoted plain value?
+ try
+ {
+ return plainValueFunction.apply( '"' + string + '"' );
+ }
+ catch( JsonParsingException ex )
+ {
+ return plainValueFunction.apply( string );
+ }
+ };
+ try( JsonParser parser = Json.createParser( new StringReader( stateString ) ) )
+ {
+ if( parser.hasNext() )
+ {
+ JsonParser.Event e = parser.next();
+ switch( e )
+ {
+ case VALUE_NULL:
+ return null;
+ case START_ARRAY:
+ case START_OBJECT:
+ // JSON Structure
+ try( JsonReader reader = Json.createReader( new StringReader( stateString ) ) )
+ {
+ return fromJson( module, valueType, reader.read() );
+ }
+ default:
+ // JSON Value out of structure
+ return outOfStructureFunction.apply( stateString );
+ }
+ }
+ }
+ catch( JsonParsingException ex )
+ {
+ return outOfStructureFunction.apply( stateString );
+ }
+ // Empty state string?
+ JsonValue emptyJsonString = Json.createReader( new StringReader( "{\"empty\":\"\"}" ) )
+ .readObject().get( "empty" );
+ return fromJson( module, valueType, emptyJsonString );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerialization.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerialization.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerialization.java
new file mode 100644
index 0000000..a98e70f
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerialization.java
@@ -0,0 +1,24 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.spi.serialization;
+
+import org.apache.polygene.api.serialization.Serialization;
+
+public interface JsonSerialization extends Serialization, JsonSerializer, JsonDeserializer
+{
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerializer.java
new file mode 100644
index 0000000..b64f240
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerializer.java
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.spi.serialization;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.io.Writer;
+import java.util.function.Function;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+import javax.json.JsonString;
+import javax.json.JsonValue;
+import org.apache.polygene.api.common.Optional;
+import org.apache.polygene.api.serialization.Serializer;
+
+public interface JsonSerializer extends Serializer
+{
+ <T> Function<T, JsonValue> toJsonFunction( Options options );
+
+ default <T> Function<T, JsonValue> toJsonFunction()
+ {
+ return object -> toJsonFunction( Options.DEFAULT ).apply( object );
+ }
+
+ default JsonValue toJson( Options options, @Optional Object object )
+ {
+ return toJsonFunction( options ).apply( object );
+ }
+
+ default JsonValue toJson( @Optional Object object )
+ {
+ return toJsonFunction( Options.DEFAULT ).apply( object );
+ }
+
+ default <T> Stream<JsonValue> toJsonEach( Options options, Stream<T> objects )
+ {
+ return objects.map( toJsonFunction( options ) );
+ }
+
+ default <T> Stream<JsonValue> toJsonEach( Options options, Iterable<T> objects )
+ {
+ return toJsonEach( options, StreamSupport.stream( objects.spliterator(), false ) );
+ }
+
+ default <T> Stream<JsonValue> toJsonEach( Options options, Object... objects )
+ {
+ return toJsonEach( options, Stream.of( objects ) );
+ }
+
+ default <T> Stream<JsonValue> toJsonEach( Stream<T> objects )
+ {
+ return objects.map( toJsonFunction( Options.DEFAULT ) );
+ }
+
+ default <T> Stream<JsonValue> toJsonEach( Iterable<T> objects )
+ {
+ return toJsonEach( Options.DEFAULT, StreamSupport.stream( objects.spliterator(), false ) );
+ }
+
+ default <T> Stream<JsonValue> toJsonEach( Object... objects )
+ {
+ return toJsonEach( Options.DEFAULT, Stream.of( objects ) );
+ }
+
+ default void serialize( Options options, Writer writer, @Optional Object object )
+ {
+ JsonValue jsonValue = toJson( options, object );
+ if( jsonValue == null )
+ {
+ return;
+ }
+ try
+ {
+ // TODO FIX ThIS SHIT of "out of structure" value (de)serialization
+ // We want plain Strings to be serialized without quotes which is non JSON compliant
+ // See https://java.net/jira/browse/JSON_PROCESSING_SPEC-65
+ if( jsonValue.getValueType() == JsonValue.ValueType.STRING )
+ {
+ writer.write( ( (JsonString) jsonValue ).getString() );
+ }
+ else
+ {
+ writer.write( jsonValue.toString() );
+ }
+ }
+ catch( IOException ex )
+ {
+ throw new UncheckedIOException( ex );
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlDeserializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlDeserializer.java
new file mode 100644
index 0000000..c7ac42b
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlDeserializer.java
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.spi.serialization;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.util.function.Function;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import org.apache.polygene.api.serialization.Deserializer;
+import org.apache.polygene.api.serialization.SerializationException;
+import org.apache.polygene.api.structure.ModuleDescriptor;
+import org.apache.polygene.api.type.CollectionType;
+import org.apache.polygene.api.type.EnumType;
+import org.apache.polygene.api.type.MapType;
+import org.apache.polygene.api.type.ValueCompositeType;
+import org.apache.polygene.api.type.ValueType;
+import org.apache.polygene.api.value.ValueDescriptor;
+import org.apache.polygene.spi.module.ModuleSpi;
+import org.w3c.dom.Document;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+public interface XmlDeserializer extends Deserializer
+{
+ <T> T fromXml( ModuleDescriptor module, ValueType valueType, Document state );
+
+ default <T> Function<Document, T> fromXmlFunction( ModuleDescriptor module, ValueType valueType )
+ {
+ return state -> fromXml( module, valueType, state );
+ }
+
+ default <T> Stream<T> fromXmlEach( ModuleDescriptor module, ValueType valueType, Stream<Document> states )
+ {
+ return states.map( fromXmlFunction( module, valueType ) );
+ }
+
+ default <T> Stream<T> fromXmlEach( ModuleDescriptor module, ValueType valueType, Iterable<Document> states )
+ {
+ return fromXmlEach( module, valueType, StreamSupport.stream( states.spliterator(), false ) );
+ }
+
+ default <T> Stream<T> fromXmlEach( ModuleDescriptor module, ValueType valueType, Document... states )
+ {
+ return fromXmlEach( module, valueType, Stream.of( states ) );
+ }
+
+ default <T> T fromXml( ModuleDescriptor module, Class<T> type, Document state )
+ {
+ // TODO Remove (ModuleSpi) cast
+ ValueType valueType = ( (ModuleSpi) module.instance() ).valueTypeFactory().valueTypeOf( module, type );
+ return fromXml( module, valueType, state );
+ }
+
+ default <T> Function<Document, T> fromXml( ModuleDescriptor module, Class<T> type )
+ {
+ return state -> fromXml( module, type, state );
+ }
+
+ default <T> Stream<T> fromXmlEach( ModuleDescriptor module, Class<T> valueType, Stream<Document> states )
+ {
+ return states.map( fromXml( module, valueType ) );
+ }
+
+ default <T> Stream<T> fromXmlEach( ModuleDescriptor module, Class<T> valueType, Iterable<Document> states )
+ {
+ return fromXmlEach( module, valueType, StreamSupport.stream( states.spliterator(), false ) );
+ }
+
+ default <T> Stream<T> fromXmlEach( ModuleDescriptor module, Class<T> valueType, Document... states )
+ {
+ return fromXmlEach( module, valueType, Stream.of( states ) );
+ }
+
+ @Override
+ default <T> T deserialize( ModuleDescriptor module, ValueType valueType, Reader state )
+ {
+ try
+ {
+ DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
+ Document doc = docBuilder.parse( new InputSource( state ) );
+ return fromXml( module, valueType, doc );
+ }
+ catch( SAXException | IOException | ParserConfigurationException ex )
+ {
+ throw new SerializationException( "Unable to read XML document", ex );
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlSerialization.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlSerialization.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlSerialization.java
new file mode 100644
index 0000000..12fda54
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlSerialization.java
@@ -0,0 +1,24 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.spi.serialization;
+
+import org.apache.polygene.api.serialization.Serialization;
+
+public interface XmlSerialization extends Serialization, XmlSerializer, XmlDeserializer
+{
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlSerializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlSerializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlSerializer.java
new file mode 100644
index 0000000..32ce539
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlSerializer.java
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.spi.serialization;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.io.Writer;
+import java.util.function.Function;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import org.apache.polygene.api.common.Optional;
+import org.apache.polygene.api.serialization.SerializationException;
+import org.apache.polygene.api.serialization.Serializer;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+
+/**
+ * XML State Serializer.
+ */
+public interface XmlSerializer extends Serializer
+{
+ <T> Function<T, Document> toXmlFunction( Options options );
+
+ default <T> Function<T, Document> toXmlFunction()
+ {
+ return object -> toXmlFunction( Options.DEFAULT ).apply( object );
+ }
+
+ default Document toXml( Options options, @Optional Object object )
+ {
+ return toXmlFunction( options ).apply( object );
+ }
+
+ default Document toXml( @Optional Object object )
+ {
+ return toXmlFunction( Options.DEFAULT ).apply( object );
+ }
+
+ default <T> Stream<Document> toXmlEach( Options options, Stream<T> objects )
+ {
+ return objects.map( toXmlFunction( options ) );
+ }
+
+ default <T> Stream<Document> toXmlEach( Options options, Iterable<T> objects )
+ {
+ return toXmlEach( options, StreamSupport.stream( objects.spliterator(), false ) );
+ }
+
+ default <T> Stream<Document> toXmlEach( Options options, Object... objects )
+ {
+ return toXmlEach( options, Stream.of( objects ) );
+ }
+
+ default <T> Stream<Document> toXmlEach( Stream<T> objects )
+ {
+ return objects.map( toXmlFunction( Options.DEFAULT ) );
+ }
+
+ default <T> Stream<Document> toXmlEach( Iterable<T> objects )
+ {
+ return toXmlEach( Options.DEFAULT, StreamSupport.stream( objects.spliterator(), false ) );
+ }
+
+ default <T> Stream<Document> toXmlEach( Object... objects )
+ {
+ return toXmlEach( Options.DEFAULT, Stream.of( objects ) );
+ }
+
+ default void serialize( Options options, Writer writer, @Optional Object object )
+ {
+ Document xmlDocument = toXml( options, object );
+ if( xmlDocument == null )
+ {
+ return;
+ }
+ try
+ {
+ // We want plain Strings to be serialized without quotes
+ if( xmlDocument.getNodeType() == Node.TEXT_NODE )
+ {
+ writer.write( xmlDocument.getNodeValue() );
+ }
+ else
+ {
+ Transformer transformer = TransformerFactory.newInstance().newTransformer();
+ transformer.setOutputProperty( OutputKeys.METHOD, "xml" );
+ transformer.setOutputProperty( OutputKeys.VERSION, "1.1" );
+ transformer.setOutputProperty( OutputKeys.STANDALONE, "yes" );
+ transformer.setOutputProperty( OutputKeys.ENCODING, "UTF-8" );
+ transformer.transform( new DOMSource( xmlDocument ), new StreamResult( writer ) );
+ }
+ }
+ catch( IOException ex )
+ {
+ throw new UncheckedIOException( ex );
+ }
+ catch( TransformerException ex )
+ {
+ throw new SerializationException( "Unable to transform XML Document to String", ex );
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/serialization/package.html
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/package.html b/core/spi/src/main/java/org/apache/polygene/spi/serialization/package.html
new file mode 100644
index 0000000..2e2f188
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/package.html
@@ -0,0 +1,24 @@
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ ~
+ ~
+ -->
+<html>
+ <body>
+ <h2>Serialization SPI.</h2>
+ </body>
+</html>
[27/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/testsupport/src/main/java/org/apache/polygene/test/value/AbstractCollectionSerializationTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/value/AbstractCollectionSerializationTest.java b/core/testsupport/src/main/java/org/apache/polygene/test/value/AbstractCollectionSerializationTest.java
deleted file mode 100644
index 4660421..0000000
--- a/core/testsupport/src/main/java/org/apache/polygene/test/value/AbstractCollectionSerializationTest.java
+++ /dev/null
@@ -1,433 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.test.value;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import org.apache.polygene.api.common.Optional;
-import org.apache.polygene.api.injection.scope.Service;
-import org.apache.polygene.api.property.Property;
-import org.apache.polygene.api.type.CollectionType;
-import org.apache.polygene.api.type.MapType;
-import org.apache.polygene.api.type.ValueCompositeType;
-import org.apache.polygene.api.type.ValueType;
-import org.apache.polygene.api.value.ValueBuilder;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.AbstractPolygeneTest;
-import org.junit.Test;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-
-/**
- * Assert that ValueSerialization behaviour on Collections and Maps is correct.
- */
-// TODO How to assert that given a collection of valuecomposites when serializing and deserializing we have no OOME?
-public class AbstractCollectionSerializationTest
- extends AbstractPolygeneTest
-{
-
- @Override
- public void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- module.values( SomeValue.class );
- }
-
- @Service
- @SuppressWarnings( "ProtectedField" )
- protected ValueSerialization valueSerialization;
-
- @Test
- public void givenPrimitiveArrayWithIntsWhenSerializingAndDeserializingExpectEquals()
- throws Exception
- {
- int[] primitiveArray = new int[]
- {
- 23, 42, -23, -42
- };
- String output = valueSerialization.serialize( primitiveArray );
- int[] deserialized = valueSerialization.deserialize( module, int[].class, output );
- assertArrayEquals( primitiveArray, deserialized );
- }
-
- @Test
- public void givenArrayWithByteAndNullElementWhenSerializingAndDeserializingExpectEquals()
- throws Exception
- {
- Byte[] array = new Byte[]
- {
- 9, null, -12, -12, 127, -128, 73
- };
- String output = valueSerialization.serialize( array );
- Byte[] deserialized = valueSerialization.deserialize( module, Byte[].class, output );
- assertArrayEquals( array, deserialized );
- }
-
- @Test
- public void givenIterableTypeWithByteAndNullElementWhenSerializingAndDeserializingExpectEquals()
- throws Exception
- {
- String output = valueSerialization.serialize( new AdHocIterable<>( byteCollection() ) );
- CollectionType collectionType = new CollectionType( List.class, new ValueType( Byte.class ) );
- List<Byte> list = valueSerialization.deserialize( module, collectionType, output );
- assertEquals( byteCollection(), list );
- }
-
- @Test
- public void givenCollectionTypeWithByteAndNullElementWhenSerializingAndDeserializingExpectEquals()
- throws Exception
- {
- String output = valueSerialization.serialize( byteCollection() );
- CollectionType collectionType = new CollectionType( Set.class, new ValueType( Byte.class ) );
- Set<Byte> list = valueSerialization.deserialize( module, collectionType, output );
- assertEquals( new LinkedHashSet<>( byteCollection() ), list );
- }
-
- @Test
- public void givenCollectionTypeWithCharacterAndNullElementWhenSerializingAndDeserializingExpectEquals()
- throws Exception
- {
- String output = valueSerialization.serialize( characterCollection() );
- CollectionType collectionType = new CollectionType( List.class, new ValueType( Character.class ) );
- List<Character> list = valueSerialization.deserialize( module, collectionType, output );
- assertEquals( characterCollection(), list );
- }
-
- @Test
- public void givenCollectionTypeWithShortAndNullElementWhenSerializingAndDeserializingExpectEquals()
- throws Exception
- {
- String output = valueSerialization.serialize( shortCollection() );
- CollectionType collectionType = new CollectionType( List.class, new ValueType( Short.class ) );
- List<Short> list = valueSerialization.deserialize( module, collectionType, output );
- assertEquals( shortCollection(), list );
- }
-
- @Test
- public void givenCollectionTypeWithIntegerAndNullElementWhenSerializingAndDeserializingExpectEquals()
- throws Exception
- {
- String output = valueSerialization.serialize( integerCollection() );
- CollectionType collectionType = new CollectionType( List.class, new ValueType( Integer.class ) );
- List<Integer> list = valueSerialization.deserialize( module, collectionType, output );
- assertEquals( integerCollection(), list );
- }
-
- @Test
- public void givenCollectionTypeWithLongAndNullElementWhenSerializingAndDeserializingExpectEquals()
- throws Exception
- {
- String output = valueSerialization.serialize( longCollection() );
- CollectionType collectionType = new CollectionType( List.class, new ValueType( Long.class ) );
- List<Long> list = valueSerialization.deserialize( module, collectionType, output );
- assertEquals( longCollection(), list );
- }
-
- @Test
- public void givenCollectionTypeWithFloatAndNullElementWhenSerializingAndDeserializingExpectEquals()
- throws Exception
- {
- String output = valueSerialization.serialize( floatCollection() );
- CollectionType collectionType = new CollectionType( List.class, new ValueType( Float.class ) );
- List<Float> list = valueSerialization.deserialize( module, collectionType, output );
- assertEquals( floatCollection(), list );
- }
-
- @Test
- public void givenCollectionTypeWithDoubleAndNullElementWhenSerializingExpectCorrectJsonOutput()
- throws Exception
- {
- String output = valueSerialization.serialize( doubleCollection() );
- CollectionType collectionType = new CollectionType( List.class, new ValueType( Double.class ) );
- List<Double> list = valueSerialization.deserialize( module, collectionType, output );
- assertEquals( doubleCollection(), list );
-
- }
-
- @Test
- public void givenCollectionTypeWithBigIntegerAndNullElementWhenSerializingAndDeserializingExpectEquals()
- throws Exception
- {
- String output = valueSerialization.serialize( bigIntegerCollection() );
- CollectionType collectionType = new CollectionType( List.class, new ValueType( BigInteger.class ) );
- List<BigInteger> list = valueSerialization.deserialize( module, collectionType, output );
- assertEquals( bigIntegerCollection(), list );
- }
-
- @Test
- public void givenCollectionTypeWithBigDecimalAndNullElementWhenSerializingAndDeserializingExpectEquals()
- throws Exception
- {
- String output = valueSerialization.serialize( bigDecimalCollection() );
- CollectionType collectionType = new CollectionType( Collection.class, new ValueType( BigDecimal.class ) );
- Collection<BigDecimal> collection = valueSerialization.deserialize( module, collectionType, output );
- assertEquals( bigDecimalCollection(), collection );
- }
-
- @Test
- public void givenMapOfStringByteAndNullElementWhenSerializingAndDeserializingExpectEquals()
- throws Exception
- {
- String output = valueSerialization.serialize( stringByteMap() );
- MapType mapType = new MapType( Map.class, new ValueType( String.class ), new ValueType( Byte.class ) );
- Map<String, Byte> value = valueSerialization.deserialize( module, mapType, output );
- assertEquals( stringByteMap(), value );
- }
-
- @Test
- public void givenMapOfStringListStringAndNullElementWhenSerializingAndDeserializingExpectEquals()
- throws Exception
- {
- String output = valueSerialization.serialize( stringMultiMap() );
- CollectionType collectionType = new CollectionType( List.class, new ValueType( String.class ) );
- MapType mapType = new MapType( Map.class, new ValueType( String.class ), collectionType );
- Map<String, List<String>> value = valueSerialization.deserialize( module, mapType, output );
- assertEquals( stringMultiMap(), value );
- }
-
- @Test
- public void givenListOfMapStringStringAndNullElementWhenSerializingAndDeserializingExpectEquals()
- throws Exception
- {
- String output = valueSerialization.serialize( stringListOfMaps() );
- ValueType stringType = new ValueType( String.class );
- CollectionType collectionType = new CollectionType( List.class, new MapType( Map.class, stringType, stringType ) );
- List<Map<String, String>> value = valueSerialization.deserialize( module, collectionType, output );
- assertEquals( stringListOfMaps(), value );
- }
-
- @Test
- public void givenListOfValueCompositesAndNullElementWhenSerializingAndDeserializingExpectEquals()
- throws Exception
- {
- String output = valueSerialization.serialize( valueCompositesList() );
- ValueCompositeType valueType = module.valueDescriptor( SomeValue.class.getName() ).valueType();
- CollectionType collectionType = new CollectionType( List.class, valueType );
- List<SomeValue> value = valueSerialization.deserialize( module, collectionType, output );
- assertEquals( valueCompositesList(), value );
- }
-
- private ArrayList<Byte> byteCollection()
- {
- ArrayList<Byte> value = new ArrayList<>();
- value.add( (byte) 9 );
- value.add( null );
- value.add( (byte) -12 );
- value.add( (byte) -12 );
- value.add( (byte) 127 );
- value.add( (byte) -128 );
- value.add( (byte) 73 );
- return value;
- }
-
- private List<Character> characterCollection()
- {
- List<Character> value = new ArrayList<>();
- value.add( 'Q' );
- value.add( 'i' );
- value.add( null );
- value.add( '4' );
- value.add( 'j' );
- return value;
- }
-
- private Collection<Short> shortCollection()
- {
- Collection<Short> value = new ArrayList<>();
- value.add( (short) -32768 );
- value.add( (short) 32767 );
- value.add( (short) -82 );
- value.add( null );
- return value;
- }
-
- private Collection<Integer> integerCollection()
- {
- Collection<Integer> value = new ArrayList<>();
- value.add( Integer.MAX_VALUE );
- value.add( -283 );
- value.add( null );
- value.add( Integer.MIN_VALUE );
- value.add( 238 );
- return value;
- }
-
- private Collection<Long> longCollection()
- {
- Collection<Long> value = new ArrayList<>();
- value.add( 98239723L );
- value.add( -1298233L );
- value.add( -1L );
- value.add( 0L );
- value.add( null );
- value.add( 1L );
- value.add( Long.MAX_VALUE );
- value.add( Long.MIN_VALUE );
- return value;
- }
-
- private Collection<Float> floatCollection()
- {
- Collection<Float> value = new ArrayList<>();
- value.add( -1f );
- value.add( 1f );
- value.add( 1f );
- value.add( 0f );
- value.add( Float.MAX_VALUE );
- value.add( Float.MIN_VALUE );
- value.add( null );
- value.add( 0.123456f );
- value.add( -0.232321f );
- return value;
- }
-
- private Collection<Double> doubleCollection()
- {
- Collection<Double> value = new ArrayList<>();
- value.add( -1.0 );
- value.add( 1.0 );
- value.add( 0.0 );
- value.add( Double.MAX_VALUE );
- value.add( null );
- value.add( Double.MIN_VALUE );
- value.add( 0.123456 );
- value.add( -0.232321 );
- return value;
- }
-
- private Collection<BigInteger> bigIntegerCollection()
- {
- Collection<BigInteger> value = new ArrayList<>();
- value.add( new BigInteger( "-1" ) );
- value.add( BigInteger.ZERO );
- value.add( BigInteger.ONE );
- value.add( null );
- value.add( BigInteger.TEN );
- value.add( new BigInteger( "-1827368263823729372397239829332" ) );
- value.add( new BigInteger( "2398723982982379827373972398723" ) );
- return value;
- }
-
- private Collection<BigDecimal> bigDecimalCollection()
- {
- Collection<BigDecimal> value = new ArrayList<>();
- value.add( new BigDecimal( "1.2" ) );
- value.add( new BigDecimal( "3.4" ) );
- value.add( null );
- value.add( new BigDecimal( "5.6" ) );
- return value;
- }
-
- private Map<String, Byte> stringByteMap()
- {
- Map<String, Byte> value = new LinkedHashMap<>();
- value.put( "a", (byte) 9 );
- value.put( "b", null );
- value.put( "c", (byte) -12 );
- return value;
- }
-
- private Map<String, List<String>> stringMultiMap()
- {
- Map<String, List<String>> value = new LinkedHashMap<>();
- List<String> list = new ArrayList<>();
- list.add( "foo" );
- list.add( "bar" );
- list.add( null );
- list.add( "cathedral" );
- list.add( "bazar" );
- value.put( "alpha", list );
- value.put( "beta", null );
- value.put( "gamma", Collections.<String>emptyList() );
- return value;
- }
-
- private List<Map<String, String>> stringListOfMaps()
- {
- List<Map<String, String>> value = new ArrayList<>();
- Map<String, String> map = new LinkedHashMap<>();
- map.put( "foo", "bar" );
- map.put( "cathedral", "bazar" );
- map.put( "yield", null );
- map.put( "42", "23" );
- value.add( map );
- value.add( null );
- value.add( Collections.<String, String>emptyMap() );
- return value;
- }
-
- private List<SomeValue> valueCompositesList()
- {
- List<SomeValue> list = new ArrayList<>();
- list.add( newSomeValue( "", "bazar" ) );
- list.add( null );
- list.add( newSomeValue( "bar", null ) );
- return list;
- }
-
- public interface SomeValue
- {
-
- Property<String> foo();
-
- @Optional
- Property<String> cathedral();
- }
-
- private SomeValue newSomeValue( String foo, String cathedral )
- {
- ValueBuilder<SomeValue> builder = module.instance().newValueBuilder( SomeValue.class );
- SomeValue value = builder.prototype();
- value.foo().set( foo );
- if( cathedral != null )
- {
- value.cathedral().set( cathedral );
- }
- return builder.newInstance();
- }
-
- private static class AdHocIterable<T> implements Iterable<T>
- {
- private final Iterable<T> delegate;
-
- private AdHocIterable( Iterable<T> delegate )
- {
- this.delegate = delegate;
- }
-
- @Override
- public Iterator<T> iterator()
- {
- return delegate.iterator();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/testsupport/src/main/java/org/apache/polygene/test/value/AbstractJsonDateFormatTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/value/AbstractJsonDateFormatTest.java b/core/testsupport/src/main/java/org/apache/polygene/test/value/AbstractJsonDateFormatTest.java
deleted file mode 100644
index 35f310e..0000000
--- a/core/testsupport/src/main/java/org/apache/polygene/test/value/AbstractJsonDateFormatTest.java
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.test.value;
-
-import java.time.Duration;
-import java.time.Instant;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.LocalTime;
-import java.time.OffsetDateTime;
-import java.time.Period;
-import java.time.ZoneId;
-import java.time.ZoneOffset;
-import java.time.ZonedDateTime;
-import java.util.List;
-import org.apache.polygene.api.injection.scope.Service;
-import org.apache.polygene.api.type.CollectionType;
-import org.apache.polygene.api.type.ValueType;
-import org.apache.polygene.api.value.ValueDeserializer;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.AbstractPolygeneTest;
-import org.junit.Test;
-
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertThat;
-
-/**
- * Assert that a JSON ValueDeserializer support various date formats.
- */
-@SuppressWarnings( "ProtectedField" )
-public class AbstractJsonDateFormatTest
- extends AbstractPolygeneTest
-{
-
- private final ValueType offsetDateTimeType = new ValueType( OffsetDateTime.class );
- private final ValueType zonedDateTimeType = new ValueType( ZonedDateTime.class );
- private final ValueType localDateTimeType = new ValueType( LocalDateTime.class );
- private final ValueType localTimeType = new ValueType( LocalTime.class );
- private final ValueType localDateType = new ValueType( LocalDate.class );
- private final ValueType instantType = new ValueType( Instant.class );
- private final ValueType durationType = new ValueType( Duration.class );
- private final ValueType periodType = new ValueType( Period.class );
-
- @Override
- public void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- }
-
- @Service
- protected ValueDeserializer valueDeserializer;
-
- @Test
- public void givenLocalDateTimeFormatWhenConvertingFromSerializedStateExpectValidDate()
- throws Exception
- {
- CollectionType collectionType = new CollectionType( List.class, localDateTimeType );
- List<LocalDateTime> value = valueDeserializer.deserialize( module, collectionType, "[\"2009-08-12T14:54:27\"]" );
- LocalDateTime expected = LocalDateTime.of( 2009, 8, 12, 14, 54, 27 );
- assertThat( value.get( 0 ), equalTo( expected ) );
- }
-
- @Test
- public void givenLocalDateFormatWhenConvertingFromSerializedStateExpectValidDate()
- throws Exception
- {
- CollectionType collectionType = new CollectionType( List.class, localDateType );
- List<LocalDate> value = valueDeserializer.deserialize( module, collectionType, "[\"2009-08-12\"]" );
- LocalDate expected = LocalDate.of( 2009, 8, 12 );
- assertThat( value.get( 0 ), equalTo( expected ) );
- }
-
- @Test
- public void givenLocalTimeFormatWhenConvertingFromSerializedStateExpectValidDate()
- throws Exception
- {
- CollectionType collectionType = new CollectionType( List.class, localTimeType );
- List<LocalTime> value = valueDeserializer.deserialize( module, collectionType, "[\"14:54:27\"]" );
- LocalTime expected = LocalTime.of( 14, 54, 27 );
- assertThat( value.get( 0 ), equalTo( expected ) );
- }
-
- @Test
- public void givenOffsetDateTimeFormatWhenConvertingFromSerializedStateExpectValidDate()
- throws Exception
- {
- CollectionType collectionType = new CollectionType( List.class, offsetDateTimeType );
- List<OffsetDateTime> value = valueDeserializer.deserialize( module, collectionType, "[\"2009-08-12T14:54:27.895+08:00\"]" );
- OffsetDateTime expected = OffsetDateTime.of( 2009, 8, 12, 14, 54, 27, 895000000, ZoneOffset.ofHours( 8 ) );
- assertThat( value.get( 0 ), equalTo( expected ) );
- }
-
- @Test
- public void givenZonedDateTimeFormatWhenConvertingFromSerializedStateExpectValidDate()
- throws Exception
- {
- CollectionType collectionType = new CollectionType( List.class, zonedDateTimeType );
- List<ZonedDateTime> value = valueDeserializer.deserialize( module, collectionType, "[\"2009-08-12T14:54:27.895+02:00[CET]\"]" );
- ZonedDateTime expected = ZonedDateTime.of( 2009, 8, 12, 14, 54, 27, 895000000, ZoneId.of( "CET" ) );
- assertThat( value.get( 0 ), equalTo( expected ) );
- }
-
- @Test
- public void givenInstantFormatWhenConvertingFromSerializedStateExpectValidDate()
- throws Exception
- {
- CollectionType collectionType = new CollectionType( List.class, instantType);
- List<Instant> value = valueDeserializer.deserialize( module, collectionType, "[\"2016-06-11T08:47:12.620Z\"]" );
- Instant expected = Instant.parse("2016-06-11T08:47:12.620Z" );
- assertThat( value.get( 0 ), equalTo( expected ) );
- }
-
- @Test
- public void givenDurationFormatWhenConvertingFromSerializedStateExpectValidDate()
- throws Exception
- {
- CollectionType collectionType = new CollectionType( List.class, durationType );
- List<Duration> value = valueDeserializer.deserialize( module, collectionType, "[\"PT3.5S\"]" );
- Duration expected = Duration.ofMillis( 3500 );
- assertThat( value.get( 0 ), equalTo( expected ) );
- }
-
- @Test
- public void givenPeriodFormatWhenConvertingFromSerializedStateExpectValidDate()
- throws Exception
- {
- CollectionType collectionType = new CollectionType( List.class, periodType );
- List<Period> value = valueDeserializer.deserialize( module, collectionType, "[\"P3Y5M13D\"]" );
- Period expected = Period.of( 3, 5, 13);
- assertThat( value.get( 0 ), equalTo( expected ) );
- }
-
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/testsupport/src/main/java/org/apache/polygene/test/value/AbstractPlainValueSerializationTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/value/AbstractPlainValueSerializationTest.java b/core/testsupport/src/main/java/org/apache/polygene/test/value/AbstractPlainValueSerializationTest.java
deleted file mode 100644
index c001b6f..0000000
--- a/core/testsupport/src/main/java/org/apache/polygene/test/value/AbstractPlainValueSerializationTest.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.test.value;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.OffsetDateTime;
-import java.time.ZoneOffset;
-import java.time.ZonedDateTime;
-import org.apache.polygene.api.entity.EntityReference;
-import org.apache.polygene.api.injection.scope.Service;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.test.AbstractPolygeneTest;
-import org.junit.Test;
-
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.hamcrest.core.IsNot.not;
-import static org.junit.Assert.assertThat;
-
-/**
- * Assert that ValueSerialization behaviour on plain values is correct.
- */
-public abstract class AbstractPlainValueSerializationTest
- extends AbstractPolygeneTest
-{
- @Service
- protected ValueSerialization valueSerialization;
-
- @Test
- public void givenCharacterValueWhenSerializingAndDeserializingExpectEquals()
- {
- String serialized = valueSerialization.serialize( 'q' );
- assertThat( "Serialized", serialized, equalTo( "q" ) );
-
- Character deserialized = valueSerialization.deserialize( module, Character.class, serialized );
- assertThat( "Deserialized", deserialized, equalTo( 'q' ) );
- }
-
- @Test
- public void givenEmptyStringValueWhenSerializingAndDeserializingExpectEquals()
- {
- String serialized = valueSerialization.serialize( "" );
- assertThat( "Serialized", serialized, equalTo( "" ) );
-
- String deserialized = valueSerialization.deserialize( module, String.class, serialized );
- assertThat( "Deserialized", deserialized, equalTo( "" ) );
- }
-
- @Test
- public void givenStringValueWhenSerializingAndDeserializingExpectEquals()
- {
- String serialized = valueSerialization.serialize( "test" );
- assertThat( serialized, equalTo( "test" ) );
-
- String deserialized = valueSerialization.deserialize( module, String.class, serialized );
- assertThat( deserialized, equalTo( "test" ) );
- }
-
- @Test
- public void givenBooleanValueWhenSerializingAndDeserializingExpectEquals()
- {
- String serialized = valueSerialization.serialize( Boolean.TRUE );
- assertThat( serialized, equalTo( "true" ) );
-
- Boolean deserialized = valueSerialization.deserialize( module, Boolean.class, serialized );
- assertThat( deserialized, equalTo( Boolean.TRUE ) );
- }
-
- @Test
- public void givenIntegerValueWhenSerializingAndDeserializingExpectEquals()
- {
- String serialized = valueSerialization.serialize( 42 );
- assertThat( serialized, equalTo( "42" ) );
- Integer deserialized = valueSerialization.deserialize( module, Integer.class, serialized );
- assertThat( deserialized, equalTo( 42 ) );
- }
-
- @Test
- public void givenLongValueWhenSerializingAndDeserializingExpectEquals()
- {
- String serialized = valueSerialization.serialize( 42L );
- assertThat( serialized, equalTo( "42" ) );
-
- Long deserialized = valueSerialization.deserialize( module, Long.class, serialized );
- assertThat( deserialized, equalTo( 42L ) );
- }
-
- @Test
- public void givenShortValueWhenSerializingAndDeserializingExpectEquals()
- {
- String serialized = valueSerialization.serialize( (short) 42 );
- assertThat( serialized, equalTo( "42" ) );
-
- Short deserialized = valueSerialization.deserialize( module, Short.class, serialized );
- assertThat( deserialized, equalTo( (short) 42 ) );
- }
-
- @Test
- public void givenByteValueWhenSerializingAndDeserializingExpectEquals()
- {
- String serialized = valueSerialization.serialize( (byte) 42 );
- assertThat( serialized, equalTo( "42" ) );
- Byte deserialized = valueSerialization.deserialize( module, Byte.class, serialized );
- assertThat( deserialized, equalTo( (byte) 42 ) );
- }
-
- @Test
- public void givenFloatValueWhenSerializingAndDeserializingExpectEquals()
- {
- String serialized = valueSerialization.serialize( 42F );
- assertThat( serialized, equalTo( "42.0" ) );
-
- Float deserialized = valueSerialization.deserialize( module, Float.class, serialized );
- assertThat( deserialized, equalTo( 42F ) );
- }
-
- @Test
- public void givenDoubleValueWhenSerializingAndDeserializingExpectEquals()
- {
- String serialized = valueSerialization.serialize( 42D );
- assertThat( serialized, equalTo( "42.0" ) );
-
- Double deserialized = valueSerialization.deserialize( module, Double.class, serialized );
- assertThat( deserialized, equalTo( 42D ) );
- }
-
- @Test
- public void givenBigIntegerValueWhenSerializingAndDeserializingExpectEquals()
- {
- BigInteger bigInteger = new BigInteger( "42424242424242424242424242" );
- assertThat( bigInteger, not( equalTo( BigInteger.valueOf( bigInteger.longValue() ) ) ) );
-
- String serialized = valueSerialization.serialize( bigInteger );
- assertThat( serialized, equalTo( "42424242424242424242424242" ) );
-
- BigInteger deserialized = valueSerialization.deserialize( module, BigInteger.class, serialized );
- assertThat( deserialized, equalTo( bigInteger ) );
- }
-
- @Test
- public void givenBigDecimalValueWhenSerializingAndDeserializingExpectEquals()
- {
- BigDecimal bigDecimal = new BigDecimal( "42.2376931348623157e+309" );
- assertThat( bigDecimal.doubleValue(), equalTo( Double.POSITIVE_INFINITY ) );
-
- String serialized = valueSerialization.serialize( bigDecimal );
- assertThat( serialized, equalTo( "4.22376931348623157E+310" ) );
-
- BigDecimal deserialized = valueSerialization.deserialize( module, BigDecimal.class, serialized );
- assertThat( deserialized, equalTo( bigDecimal ) );
- }
-
- @Test
- public void givenDateTimeValueWhenSerializingAndDeserializingExpectEquals()
- {
- String serialized = valueSerialization.serialize( OffsetDateTime.of( 2020, 3, 4, 13, 24, 35, 123000000, ZoneOffset.ofHours( 1 ) ) );
- assertThat( serialized, equalTo( "2020-03-04T13:24:35.123+01:00" ) );
- ZonedDateTime deserialized = valueSerialization.deserialize( module, ZonedDateTime.class, serialized );
- assertThat( deserialized, equalTo( ZonedDateTime.of( 2020, 3, 4, 13, 24, 35, 123000000, ZoneOffset.ofHours( 1 ) ) ) );
- }
-
- @Test
- public void givenLocalDateTimeValueWhenSerializingAndDeserializingExpectEquals()
- {
- // Serialized without TimeZone
- String serialized = valueSerialization.serialize( LocalDateTime.of( 2020, 3, 4, 13, 23, 12 ) );
- assertThat( serialized, equalTo( "2020-03-04T13:23:12" ) );
-
- LocalDateTime deserialized = valueSerialization.deserialize( module, LocalDateTime.class, serialized );
- assertThat( deserialized, equalTo( LocalDateTime.of( 2020, 3, 4, 13, 23, 12 ) ) );
- }
-
- @Test
- public void givenLocalDateValueWhenSerializingAndDeserializingExpectEquals()
- {
- String serialized = valueSerialization.serialize( LocalDate.of( 2020, 3, 4 ) );
- assertThat( serialized, equalTo( "2020-03-04" ) );
-
- LocalDate deserialized = valueSerialization.deserialize( module, LocalDate.class, serialized );
- assertThat( deserialized, equalTo( LocalDate.of( 2020,3,4 ) ) );
- }
-
- @Test
- public void givenEntityReferenceValueWhenSerializingAndDeserializingExpectEquals()
- {
- String serialized = valueSerialization.serialize( EntityReference.parseEntityReference( "ABCD-1234" ) );
- assertThat( serialized, equalTo( "ABCD-1234" ) );
-
- EntityReference deserialized = valueSerialization.deserialize( module, EntityReference.class, serialized );
- assertThat( deserialized, equalTo( EntityReference.parseEntityReference( "ABCD-1234" ) ) );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/testsupport/src/main/java/org/apache/polygene/test/value/AbstractValueCompositeSerializationTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/value/AbstractValueCompositeSerializationTest.java b/core/testsupport/src/main/java/org/apache/polygene/test/value/AbstractValueCompositeSerializationTest.java
deleted file mode 100644
index 44ab1f4..0000000
--- a/core/testsupport/src/main/java/org/apache/polygene/test/value/AbstractValueCompositeSerializationTest.java
+++ /dev/null
@@ -1,431 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.test.value;
-
-import java.io.ByteArrayOutputStream;
-import java.io.Serializable;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.LocalTime;
-import java.time.OffsetDateTime;
-import java.time.ZoneOffset;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import org.apache.polygene.api.injection.scope.Structure;
-import org.apache.polygene.api.structure.Module;
-import org.apache.polygene.test.AbstractPolygeneTest;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TestName;
-import org.apache.polygene.api.association.Association;
-import org.apache.polygene.api.association.ManyAssociation;
-import org.apache.polygene.api.association.NamedAssociation;
-import org.apache.polygene.api.common.Optional;
-import org.apache.polygene.api.common.UseDefaults;
-import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.api.entity.EntityBuilder;
-import org.apache.polygene.api.entity.EntityComposite;
-import org.apache.polygene.api.entity.EntityReference;
-import org.apache.polygene.api.injection.scope.Service;
-import org.apache.polygene.api.injection.scope.This;
-import org.apache.polygene.api.mixin.Mixins;
-import org.apache.polygene.api.property.Property;
-import org.apache.polygene.api.unitofwork.UnitOfWork;
-import org.apache.polygene.api.value.ValueBuilder;
-import org.apache.polygene.api.value.ValueComposite;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.EntityTestAssembler;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-
-/**
- * Assert that ValueSerialization behaviour on ValueComposites is correct.
- */
-// TODO Assert Arrays behaviour!
-// TODO Assert Generics behaviour!
-public abstract class AbstractValueCompositeSerializationTest
- extends AbstractPolygeneTest
-{
- @Rule
- public TestName testName = new TestName();
-
- @Structure
- Module moduleInstance;
-
- @Override
- public void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- module.values( SomeValue.class, AnotherValue.class, FooValue.class, CustomFooValue.class,
- SpecificCollection.class /*, SpecificValue.class, GenericValue.class */ );
-
- new EntityTestAssembler().visibleIn( Visibility.layer ).assemble( module.layer().module( "persistence" ) );
- module.entities( BarEntity.class );
- }
-
- @Service
- protected ValueSerialization valueSerialization;
-
- @Test
- public void givenValueCompositeWhenSerializingAndDeserializingExpectEquals()
- throws Exception
- {
- try(UnitOfWork uow = unitOfWorkFactory.newUnitOfWork())
- {
- SomeValue some = buildSomeValue();
-
- // Serialize using injected service
- ByteArrayOutputStream output = new ByteArrayOutputStream();
- valueSerialization.serialize( some, output );
- String stateString = output.toString( "UTF-8" );
-
- // Deserialize using Module API
- System.out.println(stateString);
- SomeValue some2 = moduleInstance.newValueFromSerializedState( SomeValue.class, stateString );
-
- assertThat( "String Integer Map", some2.stringIntMap().get().get( "foo" ), equalTo( 42 ) );
- assertThat( "String Value Map", some2.stringValueMap().get().get( "foo" ).internalVal(), equalTo( "Bar" ) );
- assertThat( "Nested Entities", some2.barAssociation().get().cathedral().get(), equalTo( "bazar in barAssociation" ) );
-
- assertThat( "Same value", some, equalTo( some2 ) );
- assertThat( "Same JSON value toString", stateString, equalTo( some2.toString() ) );
- assertThat( "Same JSON value", some.customFoo().get() instanceof CustomFooValue, is( true ) );
- assertThat( "Same JSON value explicit", some.customFooValue().get() instanceof CustomFooValue, is( true ) );
- assertThat( "Same value toString", some.toString(), equalTo( some2.toString() ) );
- }
- }
-
- /**
- * @return a SomeValue ValueComposite whose state is populated with test data.
- */
- private SomeValue buildSomeValue()
- {
- ValueBuilder<SomeValue> builder = moduleInstance.newValueBuilder( SomeValue.class );
- SomeValue proto = builder.prototype();
- proto.anotherList().get().add( moduleInstance.newValue( AnotherValue.class ) );
-
- ValueBuilder<SpecificCollection> specificColBuilder = moduleInstance.newValueBuilder( SpecificCollection.class );
- SpecificCollection specificColProto = specificColBuilder.prototype();
- List<String> genericList = new ArrayList<>( 2 );
- genericList.add( "Some" );
- genericList.add( "String" );
- specificColProto.genericList().set( genericList );
- proto.specificCollection().set( specificColBuilder.newInstance() );
-
- AnotherValue anotherValue1 = createAnotherValue( "Foo", "Bar" );
- AnotherValue anotherValue2 = createAnotherValue( "Habba", "ZoutZout" );
- AnotherValue anotherValue3 = createAnotherValue( "Niclas", "Hedhman" );
-
- // FIXME Some Control Chars are not supported in JSON nor in XML, what should we do about it?
- // Should Polygene Core ensure the chars used in strings are supported by the whole stack?
- // proto.string().set( "Foo\"Bar\"\nTest\f\t\b" );
- proto.string().set( "Foo\"Bar\"\nTest\t" );
- proto.string2().set( "/Foo/bar" );
- proto.number().set( 43L );
- proto.localTime().set( LocalTime.now() );
- proto.dateTime().set( OffsetDateTime.of( 2020, 3, 4, 13, 24, 35, 0, ZoneOffset.ofHours( 1 ) ) );
- proto.localDate().set( LocalDate.now() );
- proto.localDateTime().set( LocalDateTime.now() );
- proto.entityReference().set( EntityReference.parseEntityReference( "12345" ) );
- proto.stringIntMap().get().put( "foo", 42 );
-
- // Can't put more than one entry in Map because this test rely on the fact that the underlying implementations
- // maintain a certain order but it's not the case on some JVMs. On OpenJDK 8 they are reversed for example.
- // This should not be enforced tough as both the Map API and the JSON specification state that name-value pairs
- // are unordered.
- // As a consequence this test should be enhanced to be Map order independant.
- //
- // proto.stringIntMap().get().put( "bar", 67 );
-
- proto.stringValueMap().get().put( "foo", anotherValue1 );
- proto.another().set( anotherValue1 );
- // proto.arrayOfValues().set( new AnotherValue[] { anotherValue1, anotherValue2, anotherValue3 } );
- proto.serializable().set( new SerializableObject() );
- proto.foo().set( moduleInstance.newValue( FooValue.class ) );
- proto.fooValue().set( moduleInstance.newValue( FooValue.class ) );
- proto.customFoo().set( moduleInstance.newValue( CustomFooValue.class ) );
- proto.customFooValue().set( moduleInstance.newValue( CustomFooValue.class ) );
-
- // Arrays
- // TODO FIXME Disabled as ValueComposite equality fails here
- //proto.primitiveByteArray().set( new byte[]
- // {
- // 9, -12, 42, -12, 127, 23, -128, 73
- // } );
- //proto.byteArray().set( new Byte[]
- // {
- // 9, null, -12, 23, -12, 127, -128, 73
- // } );
-
- // NestedEntities
- proto.barAssociation().set( buildBarEntity( "bazar in barAssociation" ) );
- proto.barEntityAssociation().set( buildBarEntity( "bazar in barEntityAssociation" ) );
- proto.barManyAssociation().add( buildBarEntity( "bazar ONE in barManyAssociation" ) );
- proto.barManyAssociation().add( buildBarEntity( "bazar TWO in barManyAssociation" ) );
- proto.barEntityManyAssociation().add( buildBarEntity( "bazar ONE in barEntityManyAssociation" ) );
- proto.barEntityManyAssociation().add( buildBarEntity( "bazar TWO in barEntityManyAssociation" ) );
- proto.barNamedAssociation().put( "bazar", buildBarEntity( "bazar in barNamedAssociation" ) );
- proto.barNamedAssociation().put( "cathedral", buildBarEntity( "cathedral in barNamedAssociation" ) );
- proto.barEntityNamedAssociation().put( "bazar", buildBarEntity( "bazar in barEntityNamedAssociation" ) );
- proto.barEntityNamedAssociation().put( "cathedral", buildBarEntity( "cathedral in barEntityNamedAssociation" ) );
-
- return builder.newInstance();
- }
-
- private AnotherValue createAnotherValue( String val1, String val2 )
- {
- ValueBuilder<AnotherValue> valueBuilder = moduleInstance.newValueBuilder( AnotherValue.class );
- valueBuilder.prototype().val1().set( val1 );
- valueBuilder.prototypeFor( AnotherValueInternalState.class ).val2().set( val2 );
- return valueBuilder.newInstance();
- }
-
- private BarEntity buildBarEntity( String cathedral )
- {
- EntityBuilder<BarEntity> barBuilder = unitOfWorkFactory.currentUnitOfWork().newEntityBuilder( BarEntity.class );
- barBuilder.instance().cathedral().set( cathedral );
- return barBuilder.newInstance();
- }
-
- public enum TestEnum
- {
- somevalue, anothervalue
- }
-
- public interface SomeValue
- extends ValueComposite
- {
- Property<String> string();
-
- Property<String> string2();
-
- @Optional
- Property<String> nullString();
-
- @UseDefaults
- Property<String> emptyString();
-
- @UseDefaults
- Property<Long> number();
-
- Property<LocalTime> localTime();
-
- Property<OffsetDateTime> dateTime();
-
- Property<LocalDate> localDate();
-
- Property<LocalDateTime> localDateTime();
-
- Property<EntityReference> entityReference();
-
- @UseDefaults
- Property<List<String>> stringList();
-
- @UseDefaults
- Property<Map<String, Integer>> stringIntMap();
-
- @UseDefaults
- Property<Map<String, AnotherValue>> stringValueMap();
-
- Property<AnotherValue> another();
-
- // Property<AnotherValue[]> arrayOfValues();
-
- @Optional
- Property<AnotherValue> anotherNull();
-
- @UseDefaults
- Property<List<AnotherValue>> anotherList();
-
- @Optional
- Property<List<AnotherValue>> anotherListNull();
-
- @UseDefaults
- Property<List<AnotherValue>> anotherListEmpty();
-
- @UseDefaults
- Property<TestEnum> testEnum();
-
- // TODO FIXME Disabled as ValueComposite equality fails here
- //Property<byte[]> primitiveByteArray();
- //
- //@Optional
- //Property<byte[]> primitiveByteArrayNull();
- //
- //Property<Byte[]> byteArray();
- //
- //@Optional
- //Property<Byte[]> byteArrayNull();
-
- Property<Object> serializable();
-
- Property<Foo> foo();
-
- Property<FooValue> fooValue();
-
- Property<Foo> customFoo();
-
- Property<FooValue> customFooValue();
-
- Property<SpecificCollection> specificCollection();
-
- /* Too complicated to do generics here for now
- Property<SpecificValue> specificValue();
- */
- @Optional
- Association<Bar> barAssociationOptional();
-
- Association<Bar> barAssociation();
-
- Association<BarEntity> barEntityAssociation();
-
- ManyAssociation<Bar> barManyAssociationEmpty();
-
- ManyAssociation<Bar> barManyAssociation();
-
- ManyAssociation<BarEntity> barEntityManyAssociation();
-
- NamedAssociation<Bar> barNamedAssociationEmpty();
-
- NamedAssociation<Bar> barNamedAssociation();
-
- NamedAssociation<BarEntity> barEntityNamedAssociation();
- }
-
- public interface SpecificCollection
- extends GenericCollection<String>
- {
- }
-
- public interface GenericCollection<TYPE>
- extends ValueComposite
- {
- @UseDefaults
- Property<List<TYPE>> genericList();
- }
-
- public interface SpecificValue
- extends GenericValue<String>
- {
- }
-
- public interface GenericValue<TYPE>
- extends ValueComposite
- {
- @Optional
- Property<TYPE> item();
- }
-
- @Mixins( AnotherValueMixin.class )
- public interface AnotherValue
- extends ValueComposite
- {
- @UseDefaults
- Property<String> val1();
-
- String internalVal();
- }
-
- public interface AnotherValueInternalState
- {
- @UseDefaults
- Property<String> val2();
- }
-
- public static abstract class AnotherValueMixin
- implements AnotherValue
- {
- @This
- private AnotherValueInternalState internalState;
-
- @Override
- public String internalVal()
- {
- return internalState.val2().get();
- }
- }
-
- public interface Foo
- {
- @UseDefaults
- Property<String> bar();
- }
-
- public interface FooValue
- extends Foo, ValueComposite
- {
- }
-
- public interface CustomFooValue
- extends FooValue
- {
- @UseDefaults
- Property<String> custom();
- }
-
- public interface Bar
- {
- @UseDefaults
- Property<String> cathedral();
- }
-
- public interface BarEntity
- extends Bar, EntityComposite
- {
- }
-
- public static class SerializableObject
- implements Serializable
- {
- private static final long serialVersionUID = 1L;
- private final String foo = "Foo";
- private final int val = 35;
-
- @Override
- public boolean equals( Object o )
- {
- if( this == o )
- {
- return true;
- }
- if( o == null || getClass() != o.getClass() )
- {
- return false;
- }
- SerializableObject that = (SerializableObject) o;
- return val == that.val && foo.equals( that.foo );
- }
-
- @Override
- public int hashCode()
- {
- int result = foo.hashCode();
- result = 31 * result + val;
- return result;
- }
- }
-}
-
-
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/testsupport/src/main/java/org/apache/polygene/test/value/package.html
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/value/package.html b/core/testsupport/src/main/java/org/apache/polygene/test/value/package.html
deleted file mode 100644
index 31f0033..0000000
--- a/core/testsupport/src/main/java/org/apache/polygene/test/value/package.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one
- ~ or more contributor license agreements. See the NOTICE file
- ~ distributed with this work for additional information
- ~ regarding copyright ownership. The ASF licenses this file
- ~ to you under the Apache License, Version 2.0 (the
- ~ "License"); you may not use this file except in compliance
- ~ with the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- ~
- ~
- -->
-<html>
- <body>
- <h2>ValueSerialization SPI Test Support.</h2>
- </body>
-</html>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/dependencies.gradle
----------------------------------------------------------------------
diff --git a/dependencies.gradle b/dependencies.gradle
index 61f2b2a..7b5ebfd 100644
--- a/dependencies.gradle
+++ b/dependencies.gradle
@@ -28,13 +28,13 @@ dependencies.repositoriesUrls << [
// Core dependencies
def asmVersion = '5.2'
-def orgJsonVersion = '20130213'
+def javaxJsonVersion = '1.0'
def osgiVersion = '4.3.1'
dependencies.libraries << [
asm : "org.ow2.asm:asm:$asmVersion",
asm_commons: "org.ow2.asm:asm-commons:$asmVersion",
asm_util : "org.ow2.asm:asm-util:$asmVersion",
- org_json : "org.codeartisans:org.json:$orgJsonVersion",
+ javax_json : "javax.json:javax.json-api:$javaxJsonVersion",
osgi_core : "org.osgi:org.osgi.core:$osgiVersion",
]
@@ -61,10 +61,13 @@ def jcloudsVersion = '2.0.1'
def jdbmVersion = '2.4'
def jedisVersion = '2.9.0'
def jettyVersion = '9.2.17.v20160517' // 9.3.x Tests fail!
+def johnzonVersion = '1.0.0'
+def jooqVersion = '3.9.0'
def leveldbVersion = '0.9'
def leveldbJniVersion = '1.8'
def liquibaseVersion = '3.5.3'
def mongodbVersion = '3.4.2'
+def msgpackVersion = '0.8.11'
def restletVersion = '2.3.9'
def rdfVersion = '2.7.16' // 2.8.x change query results!! 4.x exists
def riakVersion = '2.1.1'
@@ -114,6 +117,8 @@ dependencies.libraries << [
jetty_continuation : "org.eclipse.jetty:jetty-continuation:$jettyVersion",
jetty_client : "org.eclipse.jetty:jetty-client:$jettyVersion",
jetty_xml : "org.eclipse.jetty:jetty-xml:$jettyVersion",
+ johnzon : "org.apache.johnzon:johnzon-core:$johnzonVersion",
+ jooq : "org.jooq:jooq:$jooqVersion",
jdbm : "jdbm:jdbm:$jdbmVersion",
jedis : "redis.clients:jedis:$jedisVersion",
leveldb_api : "org.iq80.leveldb:leveldb-api:$leveldbVersion",
@@ -121,6 +126,7 @@ dependencies.libraries << [
leveldb_jni_all : "org.fusesource.leveldbjni:leveldbjni-all:$leveldbJniVersion",
liquibase : "org.liquibase:liquibase-core:$liquibaseVersion",
mongodb : "org.mongodb:mongo-java-driver:$mongodbVersion",
+ msgpack : "org.msgpack:msgpack-core:$msgpackVersion",
osgi_compendium : "org.osgi:org.osgi.compendium:$osgiVersion",
osgi_enterprise : "org.osgi:org.osgi.enterprise:$osgiVersion",
restlet : [ "org.restlet.jee:org.restlet:$restletVersion",
@@ -178,11 +184,12 @@ def h2Version = '1.4.193'
def hamcrestVersion = '1.3'
def jaxRsApiVersion = '2.0.1'
def junitVersion = '4.12'
-def logbackVersion = '1.2.1'
+def logbackVersion = '1.2.1' // TODO Replace with Apache Log4j 2
def mockitoVersion = '2.7.14'
def mysqlVersion = '6.0.5'
def postgresqlVersion = '42.0.0'
def sqliteVersion = '3.16.1'
+def xmlUnitVersion = '2.3.0'
dependencies.libraries << [
awaitility : "org.awaitility:awaitility:$awaitilityVersion",
derby : "org.apache.derby:derby:$derbyVersion",
@@ -200,6 +207,7 @@ dependencies.libraries << [
postgres : "org.postgresql:postgresql:$postgresqlVersion",
spring_testsupport: "org.springframework:spring-test:$springVersion",
sqlite : "org.xerial:sqlite-jdbc:$sqliteVersion",
+ xmlunit : "org.xmlunit:xmlunit-matchers:$xmlUnitVersion",
]
// Default dependencies
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/cache-ehcache/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/cache-ehcache/build.gradle b/extensions/cache-ehcache/build.gradle
index 48bd5a5..c61a790 100644
--- a/extensions/cache-ehcache/build.gradle
+++ b/extensions/cache-ehcache/build.gradle
@@ -34,7 +34,6 @@ dependencies {
runtimeOnly polygene.core.runtime
testImplementation polygene.core.testsupport
- testImplementation polygene.extension( 'valueserialization-orgjson' )
testRuntimeOnly libraries.logback
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/cache-memcache/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/cache-memcache/build.gradle b/extensions/cache-memcache/build.gradle
index 034661e..8aa67a7 100644
--- a/extensions/cache-memcache/build.gradle
+++ b/extensions/cache-memcache/build.gradle
@@ -32,7 +32,6 @@ dependencies {
runtimeOnly polygene.core.runtime
testImplementation polygene.internals.testsupport
- testImplementation polygene.extension( 'valueserialization-orgjson' )
testRuntimeOnly libraries.logback
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-cassandra/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/entitystore-cassandra/build.gradle b/extensions/entitystore-cassandra/build.gradle
index ffe2cd8..b1f32a8 100644
--- a/extensions/entitystore-cassandra/build.gradle
+++ b/extensions/entitystore-cassandra/build.gradle
@@ -34,7 +34,6 @@ dependencies {
runtimeOnly polygene.core.runtime
testImplementation polygene.internals.testsupport
- testImplementation polygene.extension( 'valueserialization-jackson' )
testRuntimeOnly libraries.logback
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-cassandra/src/main/java/org/apache/polygene/entitystore/cassandra/CassandraEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-cassandra/src/main/java/org/apache/polygene/entitystore/cassandra/CassandraEntityStoreMixin.java b/extensions/entitystore-cassandra/src/main/java/org/apache/polygene/entitystore/cassandra/CassandraEntityStoreMixin.java
index 234a76f..80b638a 100644
--- a/extensions/entitystore-cassandra/src/main/java/org/apache/polygene/entitystore/cassandra/CassandraEntityStoreMixin.java
+++ b/extensions/entitystore-cassandra/src/main/java/org/apache/polygene/entitystore/cassandra/CassandraEntityStoreMixin.java
@@ -47,14 +47,11 @@ import org.apache.polygene.api.injection.scope.Structure;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.property.PropertyDescriptor;
import org.apache.polygene.api.service.ServiceActivation;
-import org.apache.polygene.api.service.qualifier.Tagged;
import org.apache.polygene.api.structure.Application;
import org.apache.polygene.api.structure.ModuleDescriptor;
import org.apache.polygene.api.unitofwork.NoSuchEntityTypeException;
import org.apache.polygene.api.unitofwork.UnitOfWork;
import org.apache.polygene.api.usecase.Usecase;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.api.value.ValueSerializer;
import org.apache.polygene.spi.entity.EntityState;
import org.apache.polygene.spi.entity.EntityStatus;
import org.apache.polygene.spi.entity.ManyAssociationState;
@@ -66,6 +63,7 @@ import org.apache.polygene.spi.entitystore.EntityStoreSPI;
import org.apache.polygene.spi.entitystore.EntityStoreUnitOfWork;
import org.apache.polygene.spi.entitystore.StateCommitter;
import org.apache.polygene.spi.entitystore.helpers.DefaultEntityState;
+import org.apache.polygene.spi.serialization.JsonSerialization;
import static java.util.stream.StreamSupport.stream;
import static org.apache.polygene.entitystore.cassandra.CassandraCluster.APP_VERSION_COLUMN;
@@ -88,7 +86,6 @@ public class CassandraEntityStoreMixin
implements EntityStore, EntityStoreSPI, ServiceActivation
{
- private static final ValueSerializer.Options MAP_OPTIONS = new ValueSerializer.Options().withMapEntriesAsObjects();
@This
private CassandraCluster cluster;
@@ -100,8 +97,7 @@ public class CassandraEntityStoreMixin
private CassandraMigration migration;
@Service
- @Tagged( ValueSerialization.Formats.JSON )
- private ValueSerialization valueSerialization;
+ private JsonSerialization valueSerialization;
@Optional
@Service
@@ -414,7 +410,7 @@ public class CassandraEntityStoreMixin
.collect(
Collectors.toMap( Map.Entry::getKey,
entry -> entry.getValue().toString() ) );
- String serialized = valueSerialization.serialize( MAP_OPTIONS, refs );
+ String serialized = valueSerialization.serialize( refs );
named.put( descriptor.qualifiedName().name(), serialized );
} );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-cassandra/src/test/java/org/apache/polygene/entitystore/cassandra/CassandraMapEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-cassandra/src/test/java/org/apache/polygene/entitystore/cassandra/CassandraMapEntityStoreTest.java b/extensions/entitystore-cassandra/src/test/java/org/apache/polygene/entitystore/cassandra/CassandraMapEntityStoreTest.java
index af97dc9..addc487 100644
--- a/extensions/entitystore-cassandra/src/test/java/org/apache/polygene/entitystore/cassandra/CassandraMapEntityStoreTest.java
+++ b/extensions/entitystore-cassandra/src/test/java/org/apache/polygene/entitystore/cassandra/CassandraMapEntityStoreTest.java
@@ -27,7 +27,6 @@ import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
import org.apache.polygene.test.entity.CanRemoveAll;
import org.apache.polygene.test.internal.DockerRule;
-import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
import org.junit.ClassRule;
/**
@@ -51,7 +50,6 @@ public class CassandraMapEntityStoreTest
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
module.services( CassandraEntityStoreService.class ).withTypes( CanRemoveAll.class ).withMixins( EmptyCassandraTableMixin.class );
- new JacksonValueSerializationAssembler().assemble( module );
// START SNIPPET: assembly
new CassandraEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-file/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/entitystore-file/build.gradle b/extensions/entitystore-file/build.gradle
index bc73c80..b430e7d 100644
--- a/extensions/entitystore-file/build.gradle
+++ b/extensions/entitystore-file/build.gradle
@@ -30,9 +30,7 @@ dependencies {
implementation polygene.library( 'constraints' )
runtimeOnly polygene.core.runtime
-
testImplementation polygene.core.testsupport
- testImplementation polygene.extension( 'valueserialization-orgjson' )
testRuntimeOnly libraries.logback
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-file/src/main/java/org/apache/polygene/entitystore/file/FileEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-file/src/main/java/org/apache/polygene/entitystore/file/FileEntityStoreMixin.java b/extensions/entitystore-file/src/main/java/org/apache/polygene/entitystore/file/FileEntityStoreMixin.java
index f1605a5..270503d 100644
--- a/extensions/entitystore-file/src/main/java/org/apache/polygene/entitystore/file/FileEntityStoreMixin.java
+++ b/extensions/entitystore-file/src/main/java/org/apache/polygene/entitystore/file/FileEntityStoreMixin.java
@@ -154,7 +154,7 @@ public class FileEntityStoreMixin
@Override
public void applyChanges( MapChanges changes )
- throws IOException
+ throws Exception
{
try
{
@@ -183,7 +183,7 @@ public class FileEntityStoreMixin
}
@Override
- public Writer updateEntity( final EntityReference ref, EntityDescriptor descriptor )
+ public Writer updateEntity( MapChange mapChange )
throws IOException
{
return new StringWriter( 1000 )
@@ -194,7 +194,7 @@ public class FileEntityStoreMixin
{
super.close();
String state = this.toString();
- File dataFile = getDataFile( ref );
+ File dataFile = getDataFile( mapChange.reference() );
store( dataFile, state );
}
};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-file/src/test/java/org/apache/polygene/entitystore/file/FileEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-file/src/test/java/org/apache/polygene/entitystore/file/FileEntityStoreTest.java b/extensions/entitystore-file/src/test/java/org/apache/polygene/entitystore/file/FileEntityStoreTest.java
index 14ba8a8..d18be11 100644
--- a/extensions/entitystore-file/src/test/java/org/apache/polygene/entitystore/file/FileEntityStoreTest.java
+++ b/extensions/entitystore-file/src/test/java/org/apache/polygene/entitystore/file/FileEntityStoreTest.java
@@ -27,7 +27,6 @@ import org.apache.polygene.library.fileconfig.FileConfigurationAssembler;
import org.apache.polygene.library.fileconfig.FileConfigurationOverride;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
@@ -49,7 +48,6 @@ public class FileEntityStoreTest
.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
// START SNIPPET: assembly
new FileEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-file/src/test/java/org/apache/polygene/entitystore/file/FileEntityStoreWithCacheTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-file/src/test/java/org/apache/polygene/entitystore/file/FileEntityStoreWithCacheTest.java b/extensions/entitystore-file/src/test/java/org/apache/polygene/entitystore/file/FileEntityStoreWithCacheTest.java
index 512feb0..95988da 100644
--- a/extensions/entitystore-file/src/test/java/org/apache/polygene/entitystore/file/FileEntityStoreWithCacheTest.java
+++ b/extensions/entitystore-file/src/test/java/org/apache/polygene/entitystore/file/FileEntityStoreWithCacheTest.java
@@ -27,7 +27,6 @@ import org.apache.polygene.library.fileconfig.FileConfigurationAssembler;
import org.apache.polygene.library.fileconfig.FileConfigurationOverride;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.cache.AbstractEntityStoreWithCacheTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
@@ -47,7 +46,6 @@ public class FileEntityStoreWithCacheTest
.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
new FileEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-geode/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/entitystore-geode/build.gradle b/extensions/entitystore-geode/build.gradle
index e38e9f1..5cf6185 100644
--- a/extensions/entitystore-geode/build.gradle
+++ b/extensions/entitystore-geode/build.gradle
@@ -33,7 +33,6 @@ dependencies {
runtimeOnly polygene.core.runtime
testImplementation polygene.core.testsupport
- testImplementation polygene.extension( 'valueserialization-orgjson' )
testRuntimeOnly libraries.logback
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-geode/src/main/java/org/apache/polygene/entitystore/geode/GeodeEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-geode/src/main/java/org/apache/polygene/entitystore/geode/GeodeEntityStoreMixin.java b/extensions/entitystore-geode/src/main/java/org/apache/polygene/entitystore/geode/GeodeEntityStoreMixin.java
index 0cfe27a..c140c28 100644
--- a/extensions/entitystore-geode/src/main/java/org/apache/polygene/entitystore/geode/GeodeEntityStoreMixin.java
+++ b/extensions/entitystore-geode/src/main/java/org/apache/polygene/entitystore/geode/GeodeEntityStoreMixin.java
@@ -154,7 +154,7 @@ public class GeodeEntityStoreMixin
}
@Override
- public void applyChanges( MapChanges changes ) throws IOException
+ public void applyChanges( MapChanges changes ) throws Exception
{
changes.visitMap( new MapChanger()
{
@@ -177,10 +177,10 @@ public class GeodeEntityStoreMixin
}
@Override
- public Writer updateEntity( EntityReference ref, EntityDescriptor entityDescriptor )
+ public Writer updateEntity( MapChange mapChange )
throws IOException
{
- return newEntity( ref, entityDescriptor );
+ return newEntity( mapChange.reference(), mapChange.descriptor() );
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-geode/src/test/java/org/apache/polygene/entitystore/geode/GeodeEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-geode/src/test/java/org/apache/polygene/entitystore/geode/GeodeEntityStoreTest.java b/extensions/entitystore-geode/src/test/java/org/apache/polygene/entitystore/geode/GeodeEntityStoreTest.java
index 5f2a4f9..a6aa1e1 100644
--- a/extensions/entitystore-geode/src/test/java/org/apache/polygene/entitystore/geode/GeodeEntityStoreTest.java
+++ b/extensions/entitystore-geode/src/test/java/org/apache/polygene/entitystore/geode/GeodeEntityStoreTest.java
@@ -25,7 +25,6 @@ import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.geode.assembly.GeodeEntityStoreAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
public class GeodeEntityStoreTest
extends AbstractEntityStoreTest
@@ -39,7 +38,6 @@ public class GeodeEntityStoreTest
super.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
// START SNIPPET: assembly
new GeodeEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-geode/src/test/java/org/apache/polygene/entitystore/geode/GeodeEntityStoreWithCacheTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-geode/src/test/java/org/apache/polygene/entitystore/geode/GeodeEntityStoreWithCacheTest.java b/extensions/entitystore-geode/src/test/java/org/apache/polygene/entitystore/geode/GeodeEntityStoreWithCacheTest.java
index 6dd02c4..3b30a1b 100644
--- a/extensions/entitystore-geode/src/test/java/org/apache/polygene/entitystore/geode/GeodeEntityStoreWithCacheTest.java
+++ b/extensions/entitystore-geode/src/test/java/org/apache/polygene/entitystore/geode/GeodeEntityStoreWithCacheTest.java
@@ -25,7 +25,6 @@ import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.geode.assembly.GeodeEntityStoreAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.cache.AbstractEntityStoreWithCacheTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
public class GeodeEntityStoreWithCacheTest
extends AbstractEntityStoreWithCacheTest
@@ -37,7 +36,6 @@ public class GeodeEntityStoreWithCacheTest
super.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
new GeodeEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-hazelcast/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/entitystore-hazelcast/build.gradle b/extensions/entitystore-hazelcast/build.gradle
index 176f586..ae1046c 100644
--- a/extensions/entitystore-hazelcast/build.gradle
+++ b/extensions/entitystore-hazelcast/build.gradle
@@ -33,7 +33,6 @@ dependencies {
runtimeOnly polygene.core.runtime
testImplementation polygene.core.testsupport
- testImplementation polygene.extension( 'valueserialization-orgjson' )
testRuntimeOnly libraries.logback
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-hazelcast/src/main/java/org/apache/polygene/entitystore/hazelcast/HazelcastEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-hazelcast/src/main/java/org/apache/polygene/entitystore/hazelcast/HazelcastEntityStoreMixin.java b/extensions/entitystore-hazelcast/src/main/java/org/apache/polygene/entitystore/hazelcast/HazelcastEntityStoreMixin.java
index 57d646c..749d980 100644
--- a/extensions/entitystore-hazelcast/src/main/java/org/apache/polygene/entitystore/hazelcast/HazelcastEntityStoreMixin.java
+++ b/extensions/entitystore-hazelcast/src/main/java/org/apache/polygene/entitystore/hazelcast/HazelcastEntityStoreMixin.java
@@ -104,7 +104,7 @@ public class HazelcastEntityStoreMixin
@Override
public void applyChanges( MapChanges changes )
- throws IOException
+ throws Exception
{
changes.visitMap( new MapChanger()
{
@@ -127,10 +127,10 @@ public class HazelcastEntityStoreMixin
}
@Override
- public Writer updateEntity( EntityReference ref, EntityDescriptor entityDescriptor )
+ public Writer updateEntity( MapChange mapChange )
throws IOException
{
- return newEntity( ref, entityDescriptor );
+ return newEntity( mapChange.reference(), mapChange.descriptor());
}
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-hazelcast/src/test/java/org/apache/polygene/entitystore/hazelcast/HazelcastEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-hazelcast/src/test/java/org/apache/polygene/entitystore/hazelcast/HazelcastEntityStoreTest.java b/extensions/entitystore-hazelcast/src/test/java/org/apache/polygene/entitystore/hazelcast/HazelcastEntityStoreTest.java
index de6c474..c2d705f 100644
--- a/extensions/entitystore-hazelcast/src/test/java/org/apache/polygene/entitystore/hazelcast/HazelcastEntityStoreTest.java
+++ b/extensions/entitystore-hazelcast/src/test/java/org/apache/polygene/entitystore/hazelcast/HazelcastEntityStoreTest.java
@@ -19,8 +19,6 @@
*/
package org.apache.polygene.entitystore.hazelcast;
-import org.junit.After;
-import org.junit.Test;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.api.unitofwork.UnitOfWorkCompletionException;
import org.apache.polygene.bootstrap.AssemblyException;
@@ -28,7 +26,8 @@ import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.hazelcast.assembly.HazelcastEntityStoreAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
+import org.junit.After;
+import org.junit.Test;
public class HazelcastEntityStoreTest
extends AbstractEntityStoreTest
@@ -43,7 +42,6 @@ public class HazelcastEntityStoreTest
super.assemble( module );
ModuleAssembly configModule = module.layer().module( "config" );
new EntityTestAssembler().assemble( configModule );
- new OrgJsonValueSerializationAssembler().assemble( module );
// START SNIPPET: assembly
new HazelcastEntityStoreAssembler().withConfig( configModule, Visibility.layer ).assemble( module );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-hazelcast/src/test/java/org/apache/polygene/entitystore/hazelcast/HazelcastEntityStoreWithCacheTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-hazelcast/src/test/java/org/apache/polygene/entitystore/hazelcast/HazelcastEntityStoreWithCacheTest.java b/extensions/entitystore-hazelcast/src/test/java/org/apache/polygene/entitystore/hazelcast/HazelcastEntityStoreWithCacheTest.java
index f0a86c3..2b0cfa1 100644
--- a/extensions/entitystore-hazelcast/src/test/java/org/apache/polygene/entitystore/hazelcast/HazelcastEntityStoreWithCacheTest.java
+++ b/extensions/entitystore-hazelcast/src/test/java/org/apache/polygene/entitystore/hazelcast/HazelcastEntityStoreWithCacheTest.java
@@ -25,7 +25,6 @@ import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.hazelcast.assembly.HazelcastEntityStoreAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.cache.AbstractEntityStoreWithCacheTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
public class HazelcastEntityStoreWithCacheTest
extends AbstractEntityStoreWithCacheTest
@@ -37,7 +36,6 @@ public class HazelcastEntityStoreWithCacheTest
super.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
new HazelcastEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-jclouds/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/entitystore-jclouds/build.gradle b/extensions/entitystore-jclouds/build.gradle
index 01a732e..8db7d5c 100644
--- a/extensions/entitystore-jclouds/build.gradle
+++ b/extensions/entitystore-jclouds/build.gradle
@@ -37,7 +37,6 @@ dependencies {
runtimeOnly libraries.jaxb_api
testImplementation polygene.internals.testsupport
- testImplementation polygene.extension( 'valueserialization-orgjson' )
testImplementation libraries.jclouds_filesystem
testRuntimeOnly libraries.logback
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-jclouds/src/main/java/org/apache/polygene/entitystore/jclouds/JCloudsMapEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-jclouds/src/main/java/org/apache/polygene/entitystore/jclouds/JCloudsMapEntityStoreMixin.java b/extensions/entitystore-jclouds/src/main/java/org/apache/polygene/entitystore/jclouds/JCloudsMapEntityStoreMixin.java
index 38cdd80..2ab821b 100644
--- a/extensions/entitystore-jclouds/src/main/java/org/apache/polygene/entitystore/jclouds/JCloudsMapEntityStoreMixin.java
+++ b/extensions/entitystore-jclouds/src/main/java/org/apache/polygene/entitystore/jclouds/JCloudsMapEntityStoreMixin.java
@@ -188,7 +188,7 @@ public class JCloudsMapEntityStoreMixin
@Override
public void applyChanges( MapChanges changes )
- throws IOException
+ throws Exception
{
final BlobStore blobStore = storeContext.getBlobStore();
changes.visitMap(
@@ -216,12 +216,13 @@ public class JCloudsMapEntityStoreMixin
}
@Override
- public Writer updateEntity( final EntityReference ref, EntityDescriptor entityDescriptor )
+ public Writer updateEntity( MapChange mapChange )
throws IOException
{
- if( !blobStore.blobExists( container, ref.identity().toString() ) )
+ String identity = mapChange.reference().identity().toString();
+ if( !blobStore.blobExists( container, identity ) )
{
- throw new EntityNotFoundException( ref );
+ throw new EntityNotFoundException( mapChange.reference() );
}
return new StringWriter()
{
@@ -231,7 +232,7 @@ public class JCloudsMapEntityStoreMixin
{
super.close();
ByteSource payload = ByteSource.wrap( toString().getBytes( UTF_8 ) );
- Blob blob = blobStore.blobBuilder( ref.identity().toString() )
+ Blob blob = blobStore.blobBuilder( identity )
.payload( payload )
.contentLength( payload.size() )
.build();
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsFilesystemTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsFilesystemTest.java b/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsFilesystemTest.java
index fc0a16a..91abf14 100644
--- a/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsFilesystemTest.java
+++ b/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsFilesystemTest.java
@@ -22,12 +22,10 @@ package org.apache.polygene.entitystore.jclouds;
import java.util.Collections;
import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.jclouds.assembly.JCloudsEntityStoreAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.jclouds.filesystem.reference.FilesystemConstants;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
@@ -40,12 +38,10 @@ public class JCloudsFilesystemTest
@Override
public void assemble( ModuleAssembly module )
- throws AssemblyException
{
super.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
new JCloudsEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
JCloudsMapEntityStoreConfiguration defaults = config.forMixin( JCloudsMapEntityStoreConfiguration.class )
.declareDefaults();
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsS3Test.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsS3Test.java b/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsS3Test.java
index f375b02..416ae61 100644
--- a/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsS3Test.java
+++ b/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsS3Test.java
@@ -25,7 +25,6 @@ import org.apache.polygene.entitystore.jclouds.assembly.JCloudsEntityStoreAssemb
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
import org.apache.polygene.test.internal.DockerRule;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.junit.ClassRule;
public class JCloudsS3Test extends AbstractEntityStoreTest
@@ -39,7 +38,6 @@ public class JCloudsS3Test extends AbstractEntityStoreTest
super.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
new JCloudsEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
JCloudsMapEntityStoreConfiguration defaults = config.forMixin( JCloudsMapEntityStoreConfiguration.class )
.declareDefaults();
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsTransientTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsTransientTest.java b/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsTransientTest.java
index 62074a6..266c0e1 100644
--- a/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsTransientTest.java
+++ b/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsTransientTest.java
@@ -21,28 +21,22 @@
package org.apache.polygene.entitystore.jclouds;
import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.jclouds.assembly.JCloudsEntityStoreAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
public class JCloudsTransientTest
extends AbstractEntityStoreTest
{
-
@Override
public void assemble( ModuleAssembly module )
- throws AssemblyException
{
super.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
// START SNIPPET: assembly
new JCloudsEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
// END SNIPPET: assembly
}
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsWithCacheTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsWithCacheTest.java b/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsWithCacheTest.java
index 3f18f58..72f89cf 100644
--- a/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsWithCacheTest.java
+++ b/extensions/entitystore-jclouds/src/test/java/org/apache/polygene/entitystore/jclouds/JCloudsWithCacheTest.java
@@ -25,7 +25,6 @@ import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.jclouds.assembly.JCloudsEntityStoreAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.cache.AbstractEntityStoreWithCacheTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
public class JCloudsWithCacheTest
extends AbstractEntityStoreWithCacheTest
@@ -37,7 +36,6 @@ public class JCloudsWithCacheTest
super.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
new JCloudsEntityStoreAssembler().withConfig( config, Visibility.layer ).assemble( module );
}
}
[37/50] [abbrv] polygene-java git commit: Fix json & xml loading of
Configuration defaults
Posted by pa...@apache.org.
Fix json & xml loading of Configuration defaults
POLYGENE-191
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/3d4805fa
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/3d4805fa
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/3d4805fa
Branch: refs/heads/serialization-3.0
Commit: 3d4805fa75175e54cffdcff64703c4d6eb9a5b7e
Parents: 86d0169
Author: Paul Merlin <pa...@apache.org>
Authored: Sun Feb 26 23:44:06 2017 +0100
Committer: Paul Merlin <pa...@apache.org>
Committed: Mon Mar 13 11:24:03 2017 +0100
----------------------------------------------------------------------
.../api/configuration/Configuration.java | 7 +++++--
.../JavaxJsonSerializationAssembler.java | 1 +
.../JavaxXmlSerializationAssembler.java | 1 +
...avaxXmlConfigurationDeserializationTest.java | 21 ++++++++++++++++++++
.../src/test/resources/configtest.xml | 1 +
5 files changed, 29 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/3d4805fa/core/api/src/main/java/org/apache/polygene/api/configuration/Configuration.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/configuration/Configuration.java b/core/api/src/main/java/org/apache/polygene/api/configuration/Configuration.java
index 21eb05f..1cd32cf 100644
--- a/core/api/src/main/java/org/apache/polygene/api/configuration/Configuration.java
+++ b/core/api/src/main/java/org/apache/polygene/api/configuration/Configuration.java
@@ -49,6 +49,8 @@ import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
import org.apache.polygene.api.usecase.Usecase;
import org.apache.polygene.api.usecase.UsecaseBuilder;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
/**
* Provide Configurations for Services. A Service that wants to be configurable
* should inject a reference to Configuration with the Configuration type:
@@ -403,8 +405,9 @@ public interface Configuration<T>
{
if( asStream != null )
{
- V configObject = serializerRef.get().deserialize( uow.module(), configType,
- new InputStreamReader( asStream ) );
+ Deserializer deserializer = serializerRef.get();
+ V configObject = deserializer.deserialize( uow.module(), configType,
+ new InputStreamReader( asStream, UTF_8 ) );
return uow.toEntity( configType, configObject );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/3d4805fa/extensions/serialization-javaxjson/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializationAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxjson/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializationAssembler.java b/extensions/serialization-javaxjson/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializationAssembler.java
index 36b84d6..84022e1 100644
--- a/extensions/serialization-javaxjson/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializationAssembler.java
+++ b/extensions/serialization-javaxjson/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializationAssembler.java
@@ -45,6 +45,7 @@ public class JavaxJsonSerializationAssembler extends Assemblers.VisibilityIdenti
Serializer.class, Deserializer.class,
JsonSerialization.class,
JsonSerializer.class, JsonDeserializer.class )
+ .taggedWith( Serialization.Formats.JSON )
.visibleIn( visibility() );
if( hasIdentity() )
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/3d4805fa/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializationAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializationAssembler.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializationAssembler.java
index b97bf12..e402a9f 100644
--- a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializationAssembler.java
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializationAssembler.java
@@ -45,6 +45,7 @@ public class JavaxXmlSerializationAssembler extends Assemblers.VisibilityIdentit
Serializer.class, Deserializer.class,
XmlSerialization.class,
XmlSerializer.class, XmlDeserializer.class )
+ .taggedWith( Serialization.Formats.XML )
.visibleIn( visibility() );
if( hasIdentity() )
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/3d4805fa/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlConfigurationDeserializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlConfigurationDeserializationTest.java b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlConfigurationDeserializationTest.java
new file mode 100644
index 0000000..f87c396
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlConfigurationDeserializationTest.java
@@ -0,0 +1,21 @@
+package org.apache.polygene.serialization.javaxxml;
+
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.test.entity.AbstractConfigurationDeserializationTest;
+import org.junit.Test;
+
+public class JavaxXmlConfigurationDeserializationTest extends AbstractConfigurationDeserializationTest
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ new JavaxXmlSerializationAssembler().assemble( module );
+ super.assemble( module );
+ }
+
+ @Test
+ public void givenServiceWhenInitializingExpectCorrectDeserialization()
+ {
+ super.givenServiceWhenInitializingExpectCorrectDeserialization();
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/3d4805fa/extensions/serialization-javaxxml/src/test/resources/configtest.xml
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/test/resources/configtest.xml b/extensions/serialization-javaxxml/src/test/resources/configtest.xml
new file mode 100644
index 0000000..0f6bc4c
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/test/resources/configtest.xml
@@ -0,0 +1 @@
+<?xml version="1.1" encoding="UTF-8" standalone="yes"?><state><value><identity>configtest</identity><host><value _type="org.apache.polygene.test.entity.AbstractConfigurationDeserializationTest$Host"><ip>12.23.34.45</ip><port>1234</port></value></host><name>main</name></value></state>
[49/50] [abbrv] polygene-java git commit: POLYGENE-191 Remove dead
code, fix TODOs and other minor cleanups
Posted by pa...@apache.org.
POLYGENE-191 Remove dead code, fix TODOs and other minor cleanups
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/d7cd08da
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/d7cd08da
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/d7cd08da
Branch: refs/heads/serialization-3.0
Commit: d7cd08da21240c9cd8ab65a121502a11d190deac
Parents: e3f025e
Author: Paul Merlin <pa...@apache.org>
Authored: Mon Feb 27 15:00:06 2017 +0100
Committer: Paul Merlin <pa...@apache.org>
Committed: Mon Mar 13 11:24:42 2017 +0100
----------------------------------------------------------------------
.../polygene/api/serialization/Serializer.java | 1 -
.../spi/serialization/JsonSerializer.java | 1 -
.../AbstractDateFormatSerializationTest.java | 142 -------------------
...AbstractValueCompositeSerializationTest.java | 3 +
.../entitystore/sql/SQLMapEntityStoreMixin.java | 1 -
.../JavaxJsonDateFormatSerializationTest.java | 24 ----
.../javaxxml/JavaxXmlDeserializer.java | 1 -
.../javaxxml/JavaxXmlSettings.java | 2 +-
.../javaxxml/JavaxXmlDateFormatTest.java | 33 -----
...JavaxXmlValueCompositeSerializationTest.java | 73 ++++++++++
.../javaxxml/JavaxXmlValueCompositeTest.java | 68 ---------
.../msgpack/MessagePackDeserializer.java | 1 -
.../MessagePackDateFormatSerializationTest.java | 33 -----
13 files changed, 77 insertions(+), 306 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/d7cd08da/core/api/src/main/java/org/apache/polygene/api/serialization/Serializer.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/serialization/Serializer.java b/core/api/src/main/java/org/apache/polygene/api/serialization/Serializer.java
index 9f9f47d..bdbe482 100644
--- a/core/api/src/main/java/org/apache/polygene/api/serialization/Serializer.java
+++ b/core/api/src/main/java/org/apache/polygene/api/serialization/Serializer.java
@@ -26,7 +26,6 @@ import java.util.function.Function;
import java.util.stream.Stream;
import org.apache.polygene.api.common.Optional;
-// TODO QUID Remove Optional?
public interface Serializer
{
void serialize( Options options, Writer writer, @Optional Object object );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/d7cd08da/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerializer.java
index b64f240..54dd92b 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerializer.java
@@ -86,7 +86,6 @@ public interface JsonSerializer extends Serializer
}
try
{
- // TODO FIX ThIS SHIT of "out of structure" value (de)serialization
// We want plain Strings to be serialized without quotes which is non JSON compliant
// See https://java.net/jira/browse/JSON_PROCESSING_SPEC-65
if( jsonValue.getValueType() == JsonValue.ValueType.STRING )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/d7cd08da/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractDateFormatSerializationTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractDateFormatSerializationTest.java b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractDateFormatSerializationTest.java
deleted file mode 100644
index 27b5289..0000000
--- a/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractDateFormatSerializationTest.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.test.serialization;
-
-import java.time.Duration;
-import java.time.Instant;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.LocalTime;
-import java.time.OffsetDateTime;
-import java.time.Period;
-import java.time.ZoneId;
-import java.time.ZoneOffset;
-import java.time.ZonedDateTime;
-import java.util.List;
-import org.apache.polygene.api.injection.scope.Service;
-import org.apache.polygene.api.serialization.Serialization;
-import org.apache.polygene.api.type.CollectionType;
-import org.apache.polygene.api.type.ValueType;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.AbstractPolygeneTest;
-import org.junit.Test;
-
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertThat;
-
-/**
- * Assert that a serialization support various date formats.
- */
-@SuppressWarnings( "ProtectedField" )
-public class AbstractDateFormatSerializationTest
- extends AbstractPolygeneTest
-{
- @Override
- public void assemble( ModuleAssembly module )
- {
- }
-
- @Service
- protected Serialization stateSerialization;
-
- @Test
- public void givenLocalDateTimeFormatWhenConvertingFromSerializedStateExpectValidDate()
- throws Exception
- {
- CollectionType collectionType = CollectionType.listOf( ValueType.LOCAL_DATE_TIME );
- List<LocalDateTime> value = stateSerialization.deserialize( module, collectionType,
- "[\"2009-08-12T14:54:27\"]" );
- LocalDateTime expected = LocalDateTime.of( 2009, 8, 12, 14, 54, 27 );
- assertThat( value.get( 0 ), equalTo( expected ) );
- }
-
- @Test
- public void givenLocalDateFormatWhenConvertingFromSerializedStateExpectValidDate()
- throws Exception
- {
- CollectionType collectionType = CollectionType.listOf( ValueType.LOCAL_DATE );
- List<LocalDate> value = stateSerialization.deserialize( module, collectionType, "[\"2009-08-12\"]" );
- LocalDate expected = LocalDate.of( 2009, 8, 12 );
- assertThat( value.get( 0 ), equalTo( expected ) );
- }
-
- @Test
- public void givenLocalTimeFormatWhenConvertingFromSerializedStateExpectValidDate()
- throws Exception
- {
- CollectionType collectionType = CollectionType.listOf( ValueType.LOCAL_TIME );
- List<LocalTime> value = stateSerialization.deserialize( module, collectionType, "[\"14:54:27\"]" );
- LocalTime expected = LocalTime.of( 14, 54, 27 );
- assertThat( value.get( 0 ), equalTo( expected ) );
- }
-
- @Test
- public void givenOffsetDateTimeFormatWhenConvertingFromSerializedStateExpectValidDate()
- throws Exception
- {
- CollectionType collectionType = CollectionType.listOf( ValueType.OFFSET_DATE_TIME );
- List<OffsetDateTime> value = stateSerialization.deserialize( module, collectionType,
- "[\"2009-08-12T14:54:27.895+08:00\"]" );
- OffsetDateTime expected = OffsetDateTime.of( 2009, 8, 12, 14, 54, 27, 895000000, ZoneOffset.ofHours( 8 ) );
- assertThat( value.get( 0 ), equalTo( expected ) );
- }
-
- @Test
- public void givenZonedDateTimeFormatWhenConvertingFromSerializedStateExpectValidDate()
- throws Exception
- {
- CollectionType collectionType = CollectionType.listOf( ValueType.ZONED_DATE_TIME );
- List<ZonedDateTime> value = stateSerialization.deserialize( module, collectionType,
- "[\"2009-08-12T14:54:27.895+02:00[CET]\"]" );
- ZonedDateTime expected = ZonedDateTime.of( 2009, 8, 12, 14, 54, 27, 895000000, ZoneId.of( "CET" ) );
- assertThat( value.get( 0 ), equalTo( expected ) );
- }
-
- @Test
- public void givenInstantFormatWhenConvertingFromSerializedStateExpectValidDate()
- throws Exception
- {
- CollectionType collectionType = CollectionType.listOf( ValueType.INSTANT );
- List<Instant> value = stateSerialization.deserialize( module, collectionType,
- "[\"2016-06-11T08:47:12.620Z\"]" );
- Instant expected = Instant.parse( "2016-06-11T08:47:12.620Z" );
- assertThat( value.get( 0 ), equalTo( expected ) );
- }
-
- @Test
- public void givenDurationFormatWhenConvertingFromSerializedStateExpectValidDate()
- throws Exception
- {
- CollectionType collectionType = CollectionType.listOf( ValueType.DURATION );
- List<Duration> value = stateSerialization.deserialize( module, collectionType, "[\"PT3.5S\"]" );
- Duration expected = Duration.ofMillis( 3500 );
- assertThat( value.get( 0 ), equalTo( expected ) );
- }
-
- @Test
- public void givenPeriodFormatWhenConvertingFromSerializedStateExpectValidDate()
- throws Exception
- {
- CollectionType collectionType = CollectionType.listOf( ValueType.PERIOD );
- List<Period> value = stateSerialization.deserialize( module, collectionType, "[\"P3Y5M13D\"]" );
- Period expected = Period.of( 3, 5, 13 );
- assertThat( value.get( 0 ), equalTo( expected ) );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/d7cd08da/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
index 121fe21..6c10776 100644
--- a/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
+++ b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractValueCompositeSerializationTest.java
@@ -71,6 +71,9 @@ import static org.junit.Assert.assertThat;
*/
// TODO Assert Arrays behaviour!
// TODO Assert Generics behaviour!
+// TODO Assert deserialization using a value super type that has less properties/associations (e.g. ignore spurious state)
+// TODO Assert deserialization from state missing optional values (e.g. do not fail on missing optional values)
+// TODO Assert deserialization from state with different properties/associations order (e.g. do not fail on unordered values)
public abstract class AbstractValueCompositeSerializationTest
extends AbstractPolygeneTest
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/d7cd08da/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java
index 77a7640..f1a852f 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java
@@ -55,7 +55,6 @@ import org.jooq.Table;
import org.jooq.conf.Settings;
import org.jooq.impl.DSL;
-// TODO Remove old SQL ES Code and spurious dependencies
public class SQLMapEntityStoreMixin
implements ServiceActivation, MapEntityStore
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/d7cd08da/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDateFormatSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDateFormatSerializationTest.java b/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDateFormatSerializationTest.java
deleted file mode 100644
index 7c0f510..0000000
--- a/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDateFormatSerializationTest.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.polygene.serialization.javaxjson;
-
-import org.apache.polygene.test.serialization.AbstractDateFormatSerializationTest;
-
-public class JavaxJsonDateFormatSerializationTest extends AbstractDateFormatSerializationTest
-{
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/d7cd08da/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
index 6488457..d556f09 100644
--- a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
@@ -62,7 +62,6 @@ import static java.util.Collections.unmodifiableMap;
import static java.util.Collections.unmodifiableSet;
import static org.apache.polygene.api.util.Collectors.toMapWithNullValues;
-// TODO Support deserialization from formatted XML, whitespaces are a problem ATM
public class JavaxXmlDeserializer extends AbstractTextDeserializer implements XmlDeserializer
{
private static final String NULL_ELEMENT_NAME = "null";
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/d7cd08da/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSettings.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSettings.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSettings.java
index b5c5702..775f941 100644
--- a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSettings.java
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSettings.java
@@ -26,7 +26,7 @@ import org.apache.polygene.api.type.ValueType;
*
* Must be registered as meta-info at assembly time.
*/
-// TODO javax.xml properties
+// TODO javax.xml properties?
public class JavaxXmlSettings
{
public static final JavaxXmlSettings DEFAULT = new JavaxXmlSettings();
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/d7cd08da/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDateFormatTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDateFormatTest.java b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDateFormatTest.java
deleted file mode 100644
index 6f69bbe..0000000
--- a/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDateFormatTest.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.polygene.serialization.javaxxml;
-
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.serialization.AbstractDateFormatSerializationTest;
-import org.junit.Ignore;
-
-@Ignore( "Super test assume JSON" )
-public class JavaxXmlDateFormatTest extends AbstractDateFormatSerializationTest
-{
- @Override
- public void assemble( ModuleAssembly module )
- {
- new JavaxXmlSerializationAssembler().assemble( module );
- super.assemble( module );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/d7cd08da/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeSerializationTest.java b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeSerializationTest.java
new file mode 100644
index 0000000..27bebc2
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeSerializationTest.java
@@ -0,0 +1,73 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxxml;
+
+import org.apache.polygene.api.injection.scope.Service;
+import org.apache.polygene.api.unitofwork.UnitOfWork;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.spi.serialization.XmlSerialization;
+import org.apache.polygene.test.serialization.AbstractValueCompositeSerializationTest;
+import org.junit.Test;
+import org.xmlunit.diff.DefaultNodeMatcher;
+import org.xmlunit.diff.ElementSelectors;
+
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertThat;
+import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
+
+// TODO Assert deserialization from formatted XML, whitespaces are a problem ATM
+public class JavaxXmlValueCompositeSerializationTest extends AbstractValueCompositeSerializationTest
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ new JavaxXmlSerializationAssembler().assemble( module );
+ super.assemble( module );
+ }
+
+ // START SNIPPET: xml-serialization
+ @Service
+ XmlSerialization xmlSerialization;
+ // END SNIPPET: xml-serialization
+
+ @Test
+ public void valueCompositeXmlEquality()
+ {
+ // START SNIPPET: xml-serialization
+ try( UnitOfWork uow = unitOfWorkFactory.newUnitOfWork() )
+ {
+ Some some = buildSomeValue( moduleInstance, uow, "23" );
+
+ // Serialize using injected service
+ String stateString = serialization.serialize( some );
+ System.out.println( stateString );
+
+ // Deserialize using Module API
+ Some some2 = moduleInstance.newValueFromSerializedState( Some.class, stateString );
+
+ assertThat( "Deserialized Value equality", some, equalTo( some2 ) );
+
+ // Need to loosely compare because of HashMaps not retaining order
+ assertThat( "value.toString() XML equality",
+ stateString,
+ isSimilarTo( some2.toString() )
+ .withNodeMatcher( new DefaultNodeMatcher( ElementSelectors.byNameAndAllAttributes ) ) );
+ }
+ // END SNIPPET: xml-serialization
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/d7cd08da/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeTest.java b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeTest.java
deleted file mode 100644
index 59d0e3e..0000000
--- a/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeTest.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.polygene.serialization.javaxxml;
-
-import org.apache.polygene.api.injection.scope.Service;
-import org.apache.polygene.api.unitofwork.UnitOfWork;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.spi.serialization.XmlSerialization;
-import org.apache.polygene.test.serialization.AbstractValueCompositeSerializationTest;
-import org.junit.Test;
-import org.xmlunit.diff.DefaultNodeMatcher;
-import org.xmlunit.diff.ElementSelectors;
-
-import static org.hamcrest.Matchers.equalTo;
-import static org.junit.Assert.assertThat;
-import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
-
-public class JavaxXmlValueCompositeTest extends AbstractValueCompositeSerializationTest
-{
- @Override
- public void assemble( ModuleAssembly module )
- {
- new JavaxXmlSerializationAssembler().assemble( module );
- super.assemble( module );
- }
-
- @Service
- XmlSerialization xmlSerialization;
-
- @Test
- public void valueCompositeXmlEquality()
- {
- try( UnitOfWork uow = unitOfWorkFactory.newUnitOfWork() )
- {
- Some some = buildSomeValue( moduleInstance, uow, "23" );
-
- // Serialize using injected service
- String stateString = serialization.serialize( some );
- System.out.println( stateString );
-
- // Deserialize using Module API
- Some some2 = moduleInstance.newValueFromSerializedState( Some.class, stateString );
-
- assertThat( "Value equality", some, equalTo( some2 ) );
-
- // Need to loosely compare because of HashMaps not retaining order
- assertThat( "XML equality",
- stateString,
- isSimilarTo( some2.toString() )
- .withNodeMatcher( new DefaultNodeMatcher( ElementSelectors.byNameAndAllAttributes ) ) );
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/d7cd08da/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
index 84508a4..caba249 100644
--- a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
+++ b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
@@ -62,7 +62,6 @@ import static java.util.Collections.unmodifiableMap;
import static java.util.Collections.unmodifiableSet;
import static org.apache.polygene.api.util.Collectors.toMap;
-// TODO Test all deserializations for: missing & spurious entries
@Mixins( MessagePackDeserializer.Mixin.class )
public interface MessagePackDeserializer extends Deserializer
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/d7cd08da/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackDateFormatSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackDateFormatSerializationTest.java b/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackDateFormatSerializationTest.java
deleted file mode 100644
index 083d418..0000000
--- a/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackDateFormatSerializationTest.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.polygene.serialization.msgpack;
-
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.serialization.AbstractDateFormatSerializationTest;
-import org.junit.Ignore;
-
-@Ignore( "Super test assume text" )
-public class MessagePackDateFormatSerializationTest extends AbstractDateFormatSerializationTest
-{
- @Override
- public void assemble( ModuleAssembly module )
- {
- new MessagePackSerializationAssembler().assemble( module );
- super.assemble( module );
- }
-}
[36/50] [abbrv] polygene-java git commit: Unify handling of primitive
value types and their boxed counterparts
Posted by pa...@apache.org.
Unify handling of primitive value types and their boxed counterparts
More coverage for plain values (de)serialization on json/xml/msgpack
POLYGENE-191
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/86d01692
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/86d01692
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/86d01692
Branch: refs/heads/serialization-3.0
Commit: 86d01692489040167e8c870b35fae562c0cb7c90
Parents: c9dd722
Author: Paul Merlin <pa...@apache.org>
Authored: Sun Feb 26 23:43:29 2017 +0100
Committer: Paul Merlin <pa...@apache.org>
Committed: Mon Mar 13 11:24:03 2017 +0100
----------------------------------------------------------------------
.../org/apache/polygene/api/type/ValueType.java | 56 +++++-
.../AbstractPlainValueSerializationTest.java | 176 ++++++++++++++-----
extensions/entitystore-sql/build.gradle | 3 +
.../entitystore/sql/SQLMapEntityStoreMixin.java | 4 +-
.../apache/polygene/index/rdf/ContainsTest.java | 2 +-
.../JavaxJsonPlainValueSerializationTest.java | 5 +
.../javaxxml/JavaxXmlDeserializer.java | 6 +-
.../JavaxXmlPlainValueSerializationTest.java | 58 ++++++
.../javaxxml/JavaxXmlPlainValueTest.java | 35 ----
.../MessagePackPlainValueSerializationTest.java | 11 +-
10 files changed, 267 insertions(+), 89 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/86d01692/core/api/src/main/java/org/apache/polygene/api/type/ValueType.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/type/ValueType.java b/core/api/src/main/java/org/apache/polygene/api/type/ValueType.java
index d457d81..6c45db2 100644
--- a/core/api/src/main/java/org/apache/polygene/api/type/ValueType.java
+++ b/core/api/src/main/java/org/apache/polygene/api/type/ValueType.java
@@ -29,6 +29,7 @@ import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.Period;
import java.time.ZonedDateTime;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
@@ -48,8 +49,8 @@ public class ValueType implements HasTypes
public static final ValueType CHARACTER = ValueType.of( Character.class, char.class );
public static final ValueType BOOLEAN = ValueType.of( Boolean.class, boolean.class );
public static final ValueType INTEGER = ValueType.of( Integer.class, int.class );
- public static final ValueType LONG = ValueType.of( Long.class, long.class );
public static final ValueType SHORT = ValueType.of( Short.class, short.class );
+ public static final ValueType LONG = ValueType.of( Long.class, long.class );
public static final ValueType BYTE = ValueType.of( Byte.class, byte.class );
public static final ValueType FLOAT = ValueType.of( Float.class, float.class );
public static final ValueType DOUBLE = ValueType.of( Double.class, double.class );
@@ -80,7 +81,56 @@ public class ValueType implements HasTypes
protected ValueType( List<Class<?>> types )
{
- this.types = types;
+ this.types = applyPrimitiveAndBoxedTypes( types );
+ }
+
+ private List<Class<?>> applyPrimitiveAndBoxedTypes( List<Class<?>> types )
+ {
+ int charPrimitiveIndex = types.indexOf( char.class );
+ int charBoxedIndex = types.indexOf( Character.class );
+ int boolPrimitiveIndex = types.indexOf( boolean.class );
+ int boolBoxedIndex = types.indexOf( Boolean.class );
+ int intPrimitiveIndex = types.indexOf( int.class );
+ int intBoxedIndex = types.indexOf( Integer.class );
+ int shortPrimitiveIndex = types.indexOf( short.class );
+ int shortBoxedIndex = types.indexOf( Short.class );
+ int longPrimitiveIndex = types.indexOf( long.class );
+ int longBoxedIndex = types.indexOf( Long.class );
+ int bytePrimitiveIndex = types.indexOf( byte.class );
+ int byteBoxedIndex = types.indexOf( Byte.class );
+ int floatPrimitiveIndex = types.indexOf( float.class );
+ int floatBoxedIndex = types.indexOf( Float.class );
+ int doublePrimitiveIndex = types.indexOf( double.class );
+ int doubleBoxedIndex = types.indexOf( Double.class );
+ if( charPrimitiveIndex == -1 && charBoxedIndex == -1
+ && boolPrimitiveIndex == -1 && boolBoxedIndex == -1
+ && intPrimitiveIndex == -1 && intBoxedIndex == -1
+ && shortPrimitiveIndex == -1 && shortBoxedIndex == -1
+ && longPrimitiveIndex == -1 && longBoxedIndex == -1
+ && bytePrimitiveIndex == -1 && byteBoxedIndex == -1
+ && floatPrimitiveIndex == -1 && floatBoxedIndex == -1
+ && doublePrimitiveIndex == -1 && doubleBoxedIndex == -1 )
+ {
+ return types;
+ }
+ List<Class<?>> allTypes = new ArrayList<>( types );
+ if( charPrimitiveIndex >= 0 && charBoxedIndex == -1 ) { allTypes.add( Character.class ); }
+ if( charPrimitiveIndex == -1 && charBoxedIndex >= 0 ) { allTypes.add( char.class ); }
+ if( boolPrimitiveIndex >= 0 && boolBoxedIndex == -1 ) { allTypes.add( Boolean.class ); }
+ if( boolPrimitiveIndex == -1 && boolBoxedIndex >= 0 ) { allTypes.add( boolean.class ); }
+ if( intPrimitiveIndex >= 0 && intBoxedIndex == -1 ) { allTypes.add( Integer.class ); }
+ if( intPrimitiveIndex == -1 && intBoxedIndex >= 0 ) { allTypes.add( int.class ); }
+ if( shortPrimitiveIndex >= 0 && shortBoxedIndex == -1 ) { allTypes.add( Short.class ); }
+ if( shortPrimitiveIndex == -1 && shortBoxedIndex >= 0 ) { allTypes.add( short.class ); }
+ if( longPrimitiveIndex >= 0 && longBoxedIndex == -1 ) { allTypes.add( Long.class ); }
+ if( longPrimitiveIndex == -1 && longBoxedIndex >= 0 ) { allTypes.add( long.class ); }
+ if( bytePrimitiveIndex >= 0 && byteBoxedIndex == -1 ) { allTypes.add( Byte.class ); }
+ if( bytePrimitiveIndex == -1 && byteBoxedIndex >= 0 ) { allTypes.add( byte.class ); }
+ if( floatPrimitiveIndex >= 0 && floatBoxedIndex == -1 ) { allTypes.add( Float.class ); }
+ if( floatPrimitiveIndex == -1 && floatBoxedIndex >= 0 ) { allTypes.add( float.class ); }
+ if( doublePrimitiveIndex >= 0 && doubleBoxedIndex == -1 ) { allTypes.add( Double.class ); }
+ if( doublePrimitiveIndex == -1 && doubleBoxedIndex >= 0 ) { allTypes.add( double.class ); }
+ return allTypes;
}
public Class<?> primaryType()
@@ -115,7 +165,7 @@ public class ValueType implements HasTypes
String name = types.stream().map( Class::getName ).collect( joining( "," ) );
if( name.contains( "," ) )
{
- name = "{" + name + "}";
+ name = '{' + name + '}';
}
return name;
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/86d01692/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractPlainValueSerializationTest.java
----------------------------------------------------------------------
diff --git a/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractPlainValueSerializationTest.java b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractPlainValueSerializationTest.java
index 7e72ff1..8f3ad6a 100644
--- a/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractPlainValueSerializationTest.java
+++ b/core/testsupport/src/main/java/org/apache/polygene/test/serialization/AbstractPlainValueSerializationTest.java
@@ -21,9 +21,14 @@ package org.apache.polygene.test.serialization;
import java.math.BigDecimal;
import java.math.BigInteger;
+import java.time.Duration;
+import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
+import java.time.LocalTime;
import java.time.OffsetDateTime;
+import java.time.Period;
+import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import org.apache.polygene.api.entity.EntityReference;
@@ -44,8 +49,7 @@ import static org.junit.Assert.assertThat;
/**
* Assert that ValueSerialization behaviour on plain values is correct.
*/
-public abstract class AbstractPlainValueSerializationTest
- extends AbstractPolygeneTest
+public abstract class AbstractPlainValueSerializationTest extends AbstractPolygeneTest
{
@Service
protected Serialization stateSerialization;
@@ -55,61 +59,83 @@ public abstract class AbstractPlainValueSerializationTest
{
}
- @Test
- public void givenEmptyStateStringWhenDeserializingExpectSuccesses()
- {
- assertThat( stateSerialization.deserialize( module, ValueType.of( Integer.class ), "" ), is( 0 ) );
- assertThat( stateSerialization.deserialize( module, ValueType.of( String.class ), "" ), equalTo( "" ) );
- }
+ protected abstract String getSingleStringRawState( String state ) throws Exception;
@Test
public void givenNullValueWhenSerializingAndDeserializingExpectNull()
{
String output = stateSerialization.serialize( null );
System.out.println( output );
+
assertThat( stateSerialization.deserialize( module, ValueType.of( Integer.class ), output ), nullValue() );
assertThat( stateSerialization.deserialize( module, ValueType.of( String.class ), output ), nullValue() );
assertThat( stateSerialization.deserialize( module, ValueType.of( SomeEnum.class ), output ), nullValue() );
}
@Test
- public void givenEnumValueWhenSerializingAndDeserializingExpectEquals()
+ public void givenEnumValueWhenSerializingAndDeserializingExpectEquals() throws Exception
{
String output = stateSerialization.serialize( SomeEnum.B�R );
System.out.println( output );
+ assertThat( getSingleStringRawState( output ), equalTo( "B�R" ) );
+
SomeEnum value = stateSerialization.deserialize( module, EnumType.of( SomeEnum.class ), output );
assertThat( value, is( SomeEnum.B�R ) );
}
@Test
- public void givenCharacterValueWhenSerializingAndDeserializingExpectEquals()
+ public void givenPrimitiveValueWhenSerializingAndDeserializingUsingPrimitiveAndBoxedTypesExpectEquals()
+ {
+ assertPrimitiveBoxedDeserializationEquals( char.class, Character.class, '\u20ac' );
+ assertPrimitiveBoxedDeserializationEquals( boolean.class, Boolean.class, true );
+ assertPrimitiveBoxedDeserializationEquals( short.class, Short.class, (short) 23 );
+ assertPrimitiveBoxedDeserializationEquals( int.class, Integer.class, 23 );
+ assertPrimitiveBoxedDeserializationEquals( byte.class, Byte.class, (byte) 23 );
+ assertPrimitiveBoxedDeserializationEquals( long.class, Long.class, 23L );
+ assertPrimitiveBoxedDeserializationEquals( float.class, Float.class, 23F );
+ assertPrimitiveBoxedDeserializationEquals( double.class, Double.class, 23D );
+ }
+
+ private <P, B> void assertPrimitiveBoxedDeserializationEquals( Class<P> primitiveType, Class<B> boxedType, P value )
+ {
+ String serialized = stateSerialization.serialize( value );
+ System.out.println( serialized );
+
+ B boxed = stateSerialization.deserialize( module, boxedType, serialized );
+ P primitive = stateSerialization.deserialize( module, primitiveType, serialized );
+ assertThat( "Primitive/Boxed", boxed, equalTo( primitive ) );
+ }
+
+ @Test
+ public void givenCharacterValueWhenSerializingAndDeserializingExpectEquals() throws Exception
{
String serialized = stateSerialization.serialize( '\u222b' );
- System.out.println(serialized);
- assertThat( "Serialized", serialized, equalTo( "\u222b" ) );
+ System.out.println( serialized );
Character deserialized = stateSerialization.deserialize( module, Character.class, serialized );
assertThat( "Deserialized", deserialized, equalTo( '\u222b' ) );
deserialized = stateSerialization.deserialize( module, char.class, serialized );
- assertThat( "Deserialized", deserialized, equalTo( '\u222b' ) );
+ assertThat( "Deserialized", deserialized, is( '\u222b' ) );
}
@Test
- public void givenEmptyStringValueWhenSerializingAndDeserializingExpectEquals()
+ public void givenEmptyStringValueWhenSerializingAndDeserializingExpectEquals() throws Exception
{
String serialized = stateSerialization.serialize( "" );
- assertThat( "Serialized", serialized, equalTo( "" ) );
+ System.out.println( serialized );
+ assertThat( getSingleStringRawState( serialized ), equalTo( "" ) );
String deserialized = stateSerialization.deserialize( module, String.class, serialized );
assertThat( "Deserialized", deserialized, equalTo( "" ) );
}
@Test
- public void givenStringValueWhenSerializingAndDeserializingExpectEquals()
+ public void givenStringValueWhenSerializingAndDeserializingExpectEquals() throws Exception
{
String serialized = stateSerialization.serialize( "�\u222b" );
- assertThat( serialized, equalTo( "�\u222b" ) );
+ System.out.println( serialized );
+ assertThat( getSingleStringRawState( serialized ), equalTo( "�\u222b" ) );
String deserialized = stateSerialization.deserialize( module, String.class, serialized );
assertThat( deserialized, equalTo( "�\u222b" ) );
@@ -119,7 +145,7 @@ public abstract class AbstractPlainValueSerializationTest
public void givenBooleanValueWhenSerializingAndDeserializingExpectEquals()
{
String serialized = stateSerialization.serialize( true );
- assertThat( serialized, equalTo( "true" ) );
+ System.out.println( serialized );
Boolean deserialized = stateSerialization.deserialize( module, Boolean.class, serialized );
assertThat( deserialized, equalTo( Boolean.TRUE ) );
@@ -129,7 +155,8 @@ public abstract class AbstractPlainValueSerializationTest
public void givenIntegerValueWhenSerializingAndDeserializingExpectEquals()
{
String serialized = stateSerialization.serialize( 42 );
- assertThat( serialized, equalTo( "42" ) );
+ System.out.println( serialized );
+
Integer deserialized = stateSerialization.deserialize( module, Integer.class, serialized );
assertThat( deserialized, equalTo( 42 ) );
}
@@ -138,7 +165,7 @@ public abstract class AbstractPlainValueSerializationTest
public void givenLongValueWhenSerializingAndDeserializingExpectEquals()
{
String serialized = stateSerialization.serialize( 42L );
- assertThat( serialized, equalTo( "42" ) );
+ System.out.println( serialized );
Long deserialized = stateSerialization.deserialize( module, Long.class, serialized );
assertThat( deserialized, equalTo( 42L ) );
@@ -148,7 +175,7 @@ public abstract class AbstractPlainValueSerializationTest
public void givenShortValueWhenSerializingAndDeserializingExpectEquals()
{
String serialized = stateSerialization.serialize( (short) 42 );
- assertThat( serialized, equalTo( "42" ) );
+ System.out.println( serialized );
Short deserialized = stateSerialization.deserialize( module, Short.class, serialized );
assertThat( deserialized, equalTo( (short) 42 ) );
@@ -158,7 +185,8 @@ public abstract class AbstractPlainValueSerializationTest
public void givenByteValueWhenSerializingAndDeserializingExpectEquals()
{
String serialized = stateSerialization.serialize( (byte) 42 );
- assertThat( serialized, equalTo( "42" ) );
+ System.out.println( serialized );
+
Byte deserialized = stateSerialization.deserialize( module, Byte.class, serialized );
assertThat( deserialized, equalTo( (byte) 42 ) );
}
@@ -167,7 +195,7 @@ public abstract class AbstractPlainValueSerializationTest
public void givenFloatValueWhenSerializingAndDeserializingExpectEquals()
{
String serialized = stateSerialization.serialize( 42F );
- assertThat( serialized, equalTo( "42.0" ) );
+ System.out.println( serialized );
Float deserialized = stateSerialization.deserialize( module, Float.class, serialized );
assertThat( deserialized, equalTo( 42F ) );
@@ -177,7 +205,7 @@ public abstract class AbstractPlainValueSerializationTest
public void givenDoubleValueWhenSerializingAndDeserializingExpectEquals()
{
String serialized = stateSerialization.serialize( 42D );
- assertThat( serialized, equalTo( "42.0" ) );
+ System.out.println( serialized );
Double deserialized = stateSerialization.deserialize( module, Double.class, serialized );
assertThat( deserialized, equalTo( 42D ) );
@@ -190,7 +218,7 @@ public abstract class AbstractPlainValueSerializationTest
assertThat( bigInteger, not( equalTo( BigInteger.valueOf( bigInteger.longValue() ) ) ) );
String serialized = stateSerialization.serialize( bigInteger );
- assertThat( serialized, equalTo( "42424242424242424242424242" ) );
+ System.out.println( serialized );
BigInteger deserialized = stateSerialization.deserialize( module, BigInteger.class, serialized );
assertThat( deserialized, equalTo( bigInteger ) );
@@ -203,49 +231,111 @@ public abstract class AbstractPlainValueSerializationTest
assertThat( bigDecimal.doubleValue(), equalTo( Double.POSITIVE_INFINITY ) );
String serialized = stateSerialization.serialize( bigDecimal );
- assertThat( serialized, equalTo( "4.22376931348623157E+310" ) );
+ System.out.println( serialized );
BigDecimal deserialized = stateSerialization.deserialize( module, BigDecimal.class, serialized );
assertThat( deserialized, equalTo( bigDecimal ) );
}
@Test
- public void givenDateTimeValueWhenSerializingAndDeserializingExpectEquals()
- {
- String serialized = stateSerialization.serialize(
- OffsetDateTime.of( 2020, 3, 4, 13, 24, 35, 123000000, ZoneOffset.ofHours( 1 ) ) );
- assertThat( serialized, equalTo( "2020-03-04T13:24:35.123+01:00" ) );
- ZonedDateTime deserialized = stateSerialization.deserialize( module, ZonedDateTime.class, serialized );
- assertThat( deserialized,
- equalTo( ZonedDateTime.of( 2020, 3, 4, 13, 24, 35, 123000000, ZoneOffset.ofHours( 1 ) ) ) );
- }
-
- @Test
- public void givenLocalDateTimeValueWhenSerializingAndDeserializingExpectEquals()
+ public void givenLocalDateTimeValueWhenSerializingAndDeserializingExpectEquals() throws Exception
{
// Serialized without TimeZone
String serialized = stateSerialization.serialize( LocalDateTime.of( 2020, 3, 4, 13, 23, 12 ) );
- assertThat( serialized, equalTo( "2020-03-04T13:23:12" ) );
+ System.out.println( serialized );
+ assertThat( getSingleStringRawState( serialized ), equalTo( "2020-03-04T13:23:12" ) );
LocalDateTime deserialized = stateSerialization.deserialize( module, LocalDateTime.class, serialized );
assertThat( deserialized, equalTo( LocalDateTime.of( 2020, 3, 4, 13, 23, 12 ) ) );
}
@Test
- public void givenLocalDateValueWhenSerializingAndDeserializingExpectEquals()
+ public void givenLocalDateValueWhenSerializingAndDeserializingExpectEquals() throws Exception
{
String serialized = stateSerialization.serialize( LocalDate.of( 2020, 3, 4 ) );
- assertThat( serialized, equalTo( "2020-03-04" ) );
+ System.out.println( serialized );
+ assertThat( getSingleStringRawState( serialized ), equalTo( "2020-03-04" ) );
LocalDate deserialized = stateSerialization.deserialize( module, LocalDate.class, serialized );
assertThat( deserialized, equalTo( LocalDate.of( 2020, 3, 4 ) ) );
}
@Test
- public void givenEntityReferenceValueWhenSerializingAndDeserializingExpectEquals()
+ public void givenLocalTimeValueWhenSerializingAndDeserializingExpectEquals() throws Exception
+ {
+ String serialized = stateSerialization.serialize( LocalTime.of( 14, 54, 27 ) );
+ System.out.println( serialized );
+ assertThat( getSingleStringRawState( serialized ), equalTo( "14:54:27" ) );
+
+ LocalTime deserialized = stateSerialization.deserialize( module, LocalTime.class, serialized );
+ assertThat( deserialized, equalTo( LocalTime.of( 14, 54, 27 ) ) );
+ }
+
+ @Test
+ public void givenOffsetDateTimeValueWhenSerializingAndDeserializingExpectEquals() throws Exception
+ {
+ String serialized = stateSerialization.serialize( OffsetDateTime.of( 2009, 8, 12, 14, 54, 27, 895000000,
+ ZoneOffset.ofHours( 8 ) ) );
+ System.out.println( serialized );
+ assertThat( getSingleStringRawState( serialized ), equalTo( "2009-08-12T14:54:27.895+08:00" ) );
+
+ OffsetDateTime deserialized = stateSerialization.deserialize( module, OffsetDateTime.class, serialized );
+ assertThat( deserialized, equalTo( OffsetDateTime.of( 2009, 8, 12, 14, 54, 27, 895000000,
+ ZoneOffset.ofHours( 8 ) ) ) );
+ }
+
+ @Test
+ public void givenZonedDateTimeValueWhenSerializingAndDeserializingExpectEquals() throws Exception
+ {
+ String serialized = stateSerialization.serialize( ZonedDateTime.of( 2009, 8, 12, 14, 54, 27, 895000000,
+ ZoneId.of( "CET" ) ) );
+ System.out.println( serialized );
+ assertThat( getSingleStringRawState( serialized ), equalTo( "2009-08-12T14:54:27.895+02:00[CET]" ) );
+
+ ZonedDateTime deserialized = stateSerialization.deserialize( module, ZonedDateTime.class, serialized );
+ assertThat( deserialized, equalTo( ZonedDateTime.of( 2009, 8, 12, 14, 54, 27, 895000000,
+ ZoneId.of( "CET" ) ) ) );
+ }
+
+ @Test
+ public void givenInstantValueWhenSerializingAndDeserializingExpectEquals() throws Exception
+ {
+ String serialized = stateSerialization.serialize( Instant.parse( "2016-06-11T08:47:12.620Z" ) );
+ System.out.println( serialized );
+ assertThat( getSingleStringRawState( serialized ), equalTo( "2016-06-11T08:47:12.620Z" ) );
+
+ Instant deserialized = stateSerialization.deserialize( module, Instant.class, serialized );
+ assertThat( deserialized, equalTo( Instant.parse( "2016-06-11T08:47:12.620Z" ) ) );
+ }
+
+ @Test
+ public void givenDurationValueWhenSerializingAndDeserializingExpectEquals() throws Exception
+ {
+ String serialized = stateSerialization.serialize( Duration.ofMillis( 3500 ) );
+ System.out.println( serialized );
+ assertThat( getSingleStringRawState( serialized ), equalTo( "PT3.5S" ) );
+
+ Duration deserialized = stateSerialization.deserialize( module, Duration.class, serialized );
+ assertThat( deserialized, equalTo( Duration.ofMillis( 3500 ) ) );
+ }
+
+ @Test
+ public void givenPeriodValueWhenSerializingAndDeserializingExpectEquals() throws Exception
+ {
+ String serialized = stateSerialization.serialize( Period.of( 3, 5, 13 ) );
+ System.out.println( serialized );
+ assertThat( getSingleStringRawState( serialized ), equalTo( "P3Y5M13D" ) );
+
+ Period deserialized = stateSerialization.deserialize( module, Period.class, serialized );
+ assertThat( deserialized, equalTo( Period.of( 3, 5, 13 ) ) );
+ }
+
+ @Test
+ public void givenEntityReferenceValueWhenSerializingAndDeserializingExpectEquals() throws Exception
{
String serialized = stateSerialization.serialize( EntityReference.parseEntityReference( "ABCD-1234" ) );
- assertThat( serialized, equalTo( "ABCD-1234" ) );
+ System.out.println( serialized );
+ assertThat( getSingleStringRawState( serialized ), equalTo( "ABCD-1234" ) );
EntityReference deserialized = stateSerialization.deserialize( module, EntityReference.class, serialized );
assertThat( deserialized, equalTo( EntityReference.parseEntityReference( "ABCD-1234" ) ) );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/86d01692/extensions/entitystore-sql/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/build.gradle b/extensions/entitystore-sql/build.gradle
index 8ab34f8..15553dc 100644
--- a/extensions/entitystore-sql/build.gradle
+++ b/extensions/entitystore-sql/build.gradle
@@ -29,7 +29,10 @@ dependencies {
api polygene.library( 'sql' )
api libraries.jooq
+ implementation libraries.slf4j_api
implementation polygene.library( 'sql-liquibase' )
+
+ // TODO Remove java SQL generator dependency
implementation libraries.javaSqlGenerator
implementation( libraries.javaSqlGeneratorImpl ) {
exclude group: 'junit'
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/86d01692/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java
index 95c9c5e..7e08daf 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java
@@ -54,7 +54,9 @@ import org.jooq.impl.DSL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-// TODO Implement optimistic locking! Maybe as a SPI helper
+// TODO Implement optimistic locking! Maybe as a SPI helper (in-progress)
+// TODO Add schema version data into the DB, check it
+// TODO Remove old SQL ES Code
public class SQLMapEntityStoreMixin
implements ServiceActivation, MapEntityStore
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/86d01692/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/ContainsTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/ContainsTest.java b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/ContainsTest.java
index 0cde1a7..cf33cca 100644
--- a/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/ContainsTest.java
+++ b/extensions/indexing-rdf/src/test/java/org/apache/polygene/index/rdf/ContainsTest.java
@@ -99,7 +99,7 @@ public class ContainsTest extends AbstractPolygeneTest
}
@Test( expected = NullPointerException.class )
- public void simplecontainsNullTest() throws Exception
+ public void simpleContainsNullTest() throws Exception
{
this.performContainsStringTest(
setOf( TEST_STRING_1, TEST_STRING_2, TEST_STRING_3 ),
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/86d01692/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonPlainValueSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonPlainValueSerializationTest.java b/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonPlainValueSerializationTest.java
index 00391e7..8be807f 100644
--- a/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonPlainValueSerializationTest.java
+++ b/extensions/serialization-javaxjson/src/test/java/org/apache/polygene/serialization/javaxjson/JavaxJsonPlainValueSerializationTest.java
@@ -23,4 +23,9 @@ import org.apache.polygene.test.serialization.AbstractPlainValueSerializationTes
public class JavaxJsonPlainValueSerializationTest extends AbstractPlainValueSerializationTest
{
+ @Override
+ protected String getSingleStringRawState( String state )
+ {
+ return state;
+ }
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/86d01692/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
index 992e000..6488457 100644
--- a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
@@ -62,6 +62,7 @@ import static java.util.Collections.unmodifiableMap;
import static java.util.Collections.unmodifiableSet;
import static org.apache.polygene.api.util.Collectors.toMapWithNullValues;
+// TODO Support deserialization from formatted XML, whitespaces are a problem ATM
public class JavaxXmlDeserializer extends AbstractTextDeserializer implements XmlDeserializer
{
private static final String NULL_ELEMENT_NAME = "null";
@@ -79,10 +80,7 @@ public class JavaxXmlDeserializer extends AbstractTextDeserializer implements Xm
if( stateElement.isPresent() )
{
Optional<Node> stateNode = JavaxXml.firstStateChildNode( stateElement.get() );
- if( stateNode.isPresent() )
- {
- return doDeserialize( module, valueType, stateNode.get() );
- }
+ return doDeserialize( module, valueType, stateNode.orElse( null ) );
}
return null;
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/86d01692/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlPlainValueSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlPlainValueSerializationTest.java b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlPlainValueSerializationTest.java
new file mode 100644
index 0000000..11979a2
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlPlainValueSerializationTest.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.serialization.javaxxml;
+
+import java.io.StringReader;
+import java.util.Optional;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.test.serialization.AbstractPlainValueSerializationTest;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.xml.sax.InputSource;
+
+public class JavaxXmlPlainValueSerializationTest extends AbstractPlainValueSerializationTest
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ new JavaxXmlSerializationAssembler().assemble( module );
+ super.assemble( module );
+ }
+
+ @Override
+ protected String getSingleStringRawState( String state ) throws Exception
+ {
+ JavaxXmlSettings settings = serviceFinder.findService( JavaxXmlSerialization.class )
+ .metaInfo( JavaxXmlSettings.class );
+ settings = JavaxXmlSettings.orDefault( settings );
+ DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
+ Document doc = docBuilder.parse( new InputSource( new StringReader( state ) ) );
+ Optional<Element> stateElement = JavaxXml.firstChildElementNamed( doc, settings.getRootTagName() );
+ if( stateElement.isPresent() )
+ {
+ Optional<Node> stateNode = JavaxXml.firstStateChildNode( stateElement.get() );
+ return stateNode.map( Node::getNodeValue ).orElse( "" );
+ }
+ return null;
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/86d01692/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlPlainValueTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlPlainValueTest.java b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlPlainValueTest.java
deleted file mode 100644
index 51d8e8a..0000000
--- a/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlPlainValueTest.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.serialization.javaxxml;
-
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.serialization.AbstractPlainValueSerializationTest;
-import org.junit.Ignore;
-
-@Ignore( "Super test assume JSON" )
-public class JavaxXmlPlainValueTest extends AbstractPlainValueSerializationTest
-{
- @Override
- public void assemble( ModuleAssembly module )
- {
- new JavaxXmlSerializationAssembler().assemble( module );
- super.assemble( module );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/86d01692/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackPlainValueSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackPlainValueSerializationTest.java b/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackPlainValueSerializationTest.java
index 3940b64..48ad8f8 100644
--- a/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackPlainValueSerializationTest.java
+++ b/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackPlainValueSerializationTest.java
@@ -19,11 +19,11 @@
*/
package org.apache.polygene.serialization.msgpack;
+import java.util.Base64;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.test.serialization.AbstractPlainValueSerializationTest;
-import org.junit.Ignore;
+import org.msgpack.core.MessagePack;
-@Ignore( "Super test assume text" )
public class MessagePackPlainValueSerializationTest extends AbstractPlainValueSerializationTest
{
@Override
@@ -32,4 +32,11 @@ public class MessagePackPlainValueSerializationTest extends AbstractPlainValueSe
new MessagePackSerializationAssembler().assemble( module );
super.assemble( module );
}
+
+ @Override
+ protected String getSingleStringRawState( String state ) throws Exception
+ {
+ return MessagePack.newDefaultUnpacker( Base64.getDecoder().decode( state ) )
+ .unpackValue().asStringValue().asString();
+ }
}
[32/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/test/java/org/apache/polygene/runtime/mixin/JDKMixinTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/polygene/runtime/mixin/JDKMixinTest.java b/core/runtime/src/test/java/org/apache/polygene/runtime/mixin/JDKMixinTest.java
index 116e82c..fc4937a 100644
--- a/core/runtime/src/test/java/org/apache/polygene/runtime/mixin/JDKMixinTest.java
+++ b/core/runtime/src/test/java/org/apache/polygene/runtime/mixin/JDKMixinTest.java
@@ -26,6 +26,9 @@ import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;
+import javax.json.Json;
+import javax.json.JsonObject;
+import javax.json.JsonObjectBuilder;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.api.concern.Concerns;
import org.apache.polygene.api.concern.GenericConcern;
@@ -36,7 +39,6 @@ import org.apache.polygene.api.service.ServiceReference;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.test.AbstractPolygeneTest;
-import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
@@ -46,56 +48,46 @@ import static org.junit.Assert.assertThat;
/**
* Assert that JDK classes are usable as Mixins.
*/
-public class JDKMixinTest
- extends AbstractPolygeneTest
+public class JDKMixinTest extends AbstractPolygeneTest
{
-
@Concerns( JDKMixinConcern.class )
- public interface JSONSerializableMap
- extends Map<String, String>
+ public interface JSONSerializableMap extends Map<String, String>
{
-
- JSONObject toJSON();
-
+ JsonObject toJSON();
}
@SuppressWarnings( "serial" )
- public static class ExtendsJDKMixin
- extends HashMap<String, String>
+ public static class ExtendsJDKMixin extends HashMap<String, String>
implements JSONSerializableMap
{
-
@Override
- public JSONObject toJSON()
+ public JsonObject toJSON()
{
System.out.println( ">>>> Call ExtendsJDKMixin.toJSON()" );
- // Copy the Map before handing it to JSONObject so that the JSONObject do not use the Composite
- return new JSONObject( new HashMap<String, String>( this ) );
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ entrySet().forEach( entry -> builder.add( entry.getKey(), entry.getValue() ) );
+ return builder.build();
}
-
}
public static abstract class ComposeWithJDKMixin
implements JSONSerializableMap
{
-
@This
private Map<String, String> map;
@Override
- public JSONObject toJSON()
+ public JsonObject toJSON()
{
System.out.println( ">>>> Call ComposeWithJDKMixin.toJSON()" );
- // Copy the Map before handing it to JSONObject so that the JSONObject do not use the Composite
- return new JSONObject( new HashMap<String, String>( map ) );
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ map.entrySet().forEach( entry -> builder.add( entry.getKey(), entry.getValue() ) );
+ return builder.build();
}
-
}
- public static class JDKMixinConcern
- extends GenericConcern
+ public static class JDKMixinConcern extends GenericConcern
{
-
@Override
public Object invoke( Object proxy, Method method, Object[] args )
throws Throwable
@@ -104,13 +96,14 @@ public class JDKMixinTest
CONCERN_RECORDS.add( method.getName() );
return next.invoke( proxy, method, args );
}
-
}
private static final Identity EXTENDS_IDENTITY = new StringIdentity( ExtendsJDKMixin.class.getName() );
private static final Identity COMPOSE_IDENTITY = new StringIdentity( ComposeWithJDKMixin.class.getName() );
- private static final Predicate<ServiceReference<?>> EXTENDS_IDENTITY_SPEC = new ServiceIdentitySpec( EXTENDS_IDENTITY );
- private static final Predicate<ServiceReference<?>> COMPOSE_IDENTITY_SPEC = new ServiceIdentitySpec( COMPOSE_IDENTITY );
+ private static final Predicate<ServiceReference<?>> EXTENDS_IDENTITY_SPEC = new ServiceIdentitySpec(
+ EXTENDS_IDENTITY );
+ private static final Predicate<ServiceReference<?>> COMPOSE_IDENTITY_SPEC = new ServiceIdentitySpec(
+ COMPOSE_IDENTITY );
private static final List<String> CONCERN_RECORDS = new ArrayList<String>();
@Before
@@ -123,16 +116,16 @@ public class JDKMixinTest
public void assemble( ModuleAssembly module )
throws AssemblyException
{
- module.services( JSONSerializableMap.class ).
- identifiedBy( EXTENDS_IDENTITY.toString() ).
- withMixins( ExtendsJDKMixin.class ).
- instantiateOnStartup();
-
- module.layer().module( "compose" ).services( JSONSerializableMap.class ).
- visibleIn( Visibility.layer ).
- identifiedBy( COMPOSE_IDENTITY.toString() ).
- withMixins( HashMap.class, ComposeWithJDKMixin.class ).
- instantiateOnStartup();
+ module.services( JSONSerializableMap.class )
+ .identifiedBy( EXTENDS_IDENTITY.toString() )
+ .withMixins( ExtendsJDKMixin.class )
+ .instantiateOnStartup();
+
+ module.layer().module( "compose" ).services( JSONSerializableMap.class )
+ .visibleIn( Visibility.layer )
+ .identifiedBy( COMPOSE_IDENTITY.toString() )
+ .withMixins( HashMap.class, ComposeWithJDKMixin.class )
+ .instantiateOnStartup();
}
@Test
@@ -147,12 +140,12 @@ public class JDKMixinTest
JSONSerializableMap extending = services.get( 0 ).get();
extending.put( "foo", "bar" ); // Concern trigger #1 (put)
- JSONObject json = extending.toJSON(); // Concern trigger #2, #3 and #4 (toJSON, size, entrySet)
+ JsonObject json = extending.toJSON(); // Concern trigger #2 and #3 (toJSON, entrySet)
- assertThat( json.length(), equalTo( 1 ) );
- assertThat( json.optString( "foo" ), equalTo( "bar" ) );
+ assertThat( json.size(), equalTo( 1 ) );
+ assertThat( json.getString( "foo" ), equalTo( "bar" ) );
- assertThat( CONCERN_RECORDS.size(), equalTo( 4 ) );
+ assertThat( CONCERN_RECORDS.size(), equalTo( 3 ) );
}
@Test
@@ -167,21 +160,20 @@ public class JDKMixinTest
JSONSerializableMap composing = services.get( 0 ).get();
composing.put( "foo", "bar" ); // Concern trigger #1 (put)
- JSONObject json = composing.toJSON(); // Concern trigger #2, #3 and #4 (toJSON, size, entrySet)
+ JsonObject json = composing.toJSON(); // Concern trigger #2 and #3 (toJSON, entrySet)
- assertThat( json.length(), equalTo( 1 ) );
- assertThat( json.optString( "foo" ), equalTo( "bar" ) );
+ assertThat( json.size(), equalTo( 1 ) );
+ assertThat( json.getString( "foo" ), equalTo( "bar" ) );
- assertThat( CONCERN_RECORDS.size(), equalTo( 4 ) );
+ assertThat( CONCERN_RECORDS.size(), equalTo( 3 ) );
}
private static class ServiceIdentitySpec
implements Predicate<ServiceReference<?>>
{
-
private final Identity identity;
- ServiceIdentitySpec(Identity identity)
+ ServiceIdentitySpec( Identity identity )
{
this.identity = identity;
}
@@ -191,7 +183,5 @@ public class JDKMixinTest
{
return item.identity().equals( identity );
}
-
}
-
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/test/java/org/apache/polygene/runtime/property/ValueNestedBuilderTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/polygene/runtime/property/ValueNestedBuilderTest.java b/core/runtime/src/test/java/org/apache/polygene/runtime/property/ValueNestedBuilderTest.java
index caad29d..026cb13 100644
--- a/core/runtime/src/test/java/org/apache/polygene/runtime/property/ValueNestedBuilderTest.java
+++ b/core/runtime/src/test/java/org/apache/polygene/runtime/property/ValueNestedBuilderTest.java
@@ -30,13 +30,11 @@ import org.apache.polygene.api.value.ValueComposite;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.test.AbstractPolygeneTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
import org.junit.Test;
public class ValueNestedBuilderTest
extends AbstractPolygeneTest
{
-
private interface InnerValue
extends ValueComposite
{
@@ -75,7 +73,6 @@ public class ValueNestedBuilderTest
public void assemble( ModuleAssembly module )
throws AssemblyException
{
- module.services( OrgJsonValueSerializationService.class );
module.values( InnerValue.class, InnerDefaultedValue.class, OuterValue.class, OuterDefaultedValue.class );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/test/java/org/apache/polygene/runtime/value/AssociationToValueTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/polygene/runtime/value/AssociationToValueTest.java b/core/runtime/src/test/java/org/apache/polygene/runtime/value/AssociationToValueTest.java
index 370883f..18b6935 100644
--- a/core/runtime/src/test/java/org/apache/polygene/runtime/value/AssociationToValueTest.java
+++ b/core/runtime/src/test/java/org/apache/polygene/runtime/value/AssociationToValueTest.java
@@ -35,12 +35,10 @@ import org.apache.polygene.api.unitofwork.UnitOfWork;
import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
import org.apache.polygene.api.unitofwork.concern.UnitOfWorkConcern;
import org.apache.polygene.api.unitofwork.concern.UnitOfWorkPropagation;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
import org.apache.polygene.test.AbstractPolygeneTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
import org.junit.Test;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
@@ -102,7 +100,6 @@ public class AssociationToValueTest extends AbstractPolygeneTest
module.entities( Person.class );
module.values( Person.class );
module.services( PersonRepository.class ).withConcerns( UnitOfWorkConcern.class );
- module.services( OrgJsonValueSerializationService.class ).taggedWith( ValueSerialization.Formats.JSON );
module.services( MemoryEntityStoreService.class );
module.services( Runnable.class )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/test/java/org/apache/polygene/runtime/value/NestedValueBuilderTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/polygene/runtime/value/NestedValueBuilderTest.java b/core/runtime/src/test/java/org/apache/polygene/runtime/value/NestedValueBuilderTest.java
index 55196cb..45859de 100644
--- a/core/runtime/src/test/java/org/apache/polygene/runtime/value/NestedValueBuilderTest.java
+++ b/core/runtime/src/test/java/org/apache/polygene/runtime/value/NestedValueBuilderTest.java
@@ -23,8 +23,6 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
-import org.junit.Test;
import org.apache.polygene.api.common.UseDefaults;
import org.apache.polygene.api.property.Property;
import org.apache.polygene.api.value.ValueBuilder;
@@ -32,6 +30,7 @@ import org.apache.polygene.api.value.ValueComposite;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.test.AbstractPolygeneTest;
+import org.junit.Test;
import static org.junit.Assert.fail;
@@ -78,7 +77,6 @@ public class NestedValueBuilderTest
public void assemble( ModuleAssembly module )
throws AssemblyException
{
- module.services( OrgJsonValueSerializationService.class );
module.values( InnerValue.class, InnerDefaultedValue.class, OuterValue.class, OuterDefaultedValue.class );
}
@@ -87,8 +85,8 @@ public class NestedValueBuilderTest
{
ValueBuilder<InnerValue> innerBuilder = valueBuilderFactory.newValueBuilder( InnerValue.class );
InnerValue inner = innerBuilder.prototype();
- inner.listProp().set( new ArrayList<String>() );
- inner.mapProp().set( new HashMap<String, String>() );
+ inner.listProp().set( new ArrayList<>() );
+ inner.mapProp().set( new HashMap<>() );
inner = innerBuilder.newInstance();
// If we reach this point, value creation went well
try
@@ -116,12 +114,12 @@ public class NestedValueBuilderTest
{
ValueBuilder<InnerValue> innerBuilder = valueBuilderFactory.newValueBuilder( InnerValue.class );
InnerValue innerPrototype = innerBuilder.prototype();
- innerPrototype.listProp().set( new ArrayList<String>() );
- innerPrototype.mapProp().set( new HashMap<String, String>() );
+ innerPrototype.listProp().set( new ArrayList<>() );
+ innerPrototype.mapProp().set( new HashMap<>() );
InnerValue innerInstance = innerBuilder.newInstance();
ValueBuilder<OuterValue> outerBuilder = valueBuilderFactory.newValueBuilder( OuterValue.class );
OuterValue outerPrototype = outerBuilder.prototype();
- List<InnerValue> inners = new ArrayList<InnerValue>();
+ List<InnerValue> inners = new ArrayList<>();
inners.add( innerInstance );
outerPrototype.innerListProp().set( inners );
OuterValue outerInstance = outerBuilder.newInstance();
@@ -171,7 +169,7 @@ public class NestedValueBuilderTest
InnerDefaultedValue innerInstance = innerBuilder.newInstance();
ValueBuilder<OuterDefaultedValue> outerBuilder = valueBuilderFactory.newValueBuilder( OuterDefaultedValue.class );
OuterDefaultedValue outerPrototype = outerBuilder.prototype();
- List<InnerDefaultedValue> inners = new ArrayList<InnerDefaultedValue>();
+ List<InnerDefaultedValue> inners = new ArrayList<>();
inners.add( innerInstance );
outerPrototype.innerListPropDefault().set( inners );
OuterDefaultedValue outerInstance = outerBuilder.newInstance();
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/test/java/org/apache/polygene/runtime/value/ValueCompositeBasicsTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/polygene/runtime/value/ValueCompositeBasicsTest.java b/core/runtime/src/test/java/org/apache/polygene/runtime/value/ValueCompositeBasicsTest.java
index 2ad6db4..bc538f1 100644
--- a/core/runtime/src/test/java/org/apache/polygene/runtime/value/ValueCompositeBasicsTest.java
+++ b/core/runtime/src/test/java/org/apache/polygene/runtime/value/ValueCompositeBasicsTest.java
@@ -19,15 +19,14 @@
*/
package org.apache.polygene.runtime.value;
-import org.apache.polygene.test.AbstractPolygeneTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
-import org.junit.Test;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.property.Property;
import org.apache.polygene.api.value.ValueBuilder;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.test.AbstractPolygeneTest;
+import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -39,7 +38,6 @@ public class ValueCompositeBasicsTest
public void assemble( ModuleAssembly module )
throws AssemblyException
{
- module.services( OrgJsonValueSerializationService.class );
module.values( SomeValue.class );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/test/java/org/apache/polygene/runtime/value/ValueSerializationRegressionTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/polygene/runtime/value/ValueSerializationRegressionTest.java b/core/runtime/src/test/java/org/apache/polygene/runtime/value/ValueSerializationRegressionTest.java
index 5143909..fe8cdd8 100644
--- a/core/runtime/src/test/java/org/apache/polygene/runtime/value/ValueSerializationRegressionTest.java
+++ b/core/runtime/src/test/java/org/apache/polygene/runtime/value/ValueSerializationRegressionTest.java
@@ -19,21 +19,19 @@
*/
package org.apache.polygene.runtime.value;
-import org.apache.polygene.api.identity.HasIdentity;
-import org.apache.polygene.api.identity.StringIdentity;
-import org.junit.Test;
import org.apache.polygene.api.association.Association;
import org.apache.polygene.api.association.ManyAssociation;
import org.apache.polygene.api.association.NamedAssociation;
+import org.apache.polygene.api.identity.HasIdentity;
+import org.apache.polygene.api.identity.StringIdentity;
import org.apache.polygene.api.property.Property;
import org.apache.polygene.api.unitofwork.UnitOfWorkCompletionException;
import org.apache.polygene.api.value.ValueBuilder;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
import org.apache.polygene.test.AbstractPolygeneTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
+import org.junit.Test;
public class ValueSerializationRegressionTest extends AbstractPolygeneTest
{
@@ -45,7 +43,6 @@ public class ValueSerializationRegressionTest extends AbstractPolygeneTest
module.entities( DualFaced.class );
module.values( DualFaced.class );
module.services( MemoryEntityStoreService.class );
- module.services( OrgJsonValueSerializationService.class ).taggedWith( ValueSerialization.Formats.JSON );
}
@Test
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/test/java/org/apache/polygene/runtime/value/ValueWithAssociationTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/polygene/runtime/value/ValueWithAssociationTest.java b/core/runtime/src/test/java/org/apache/polygene/runtime/value/ValueWithAssociationTest.java
index 175e116..4441a76 100644
--- a/core/runtime/src/test/java/org/apache/polygene/runtime/value/ValueWithAssociationTest.java
+++ b/core/runtime/src/test/java/org/apache/polygene/runtime/value/ValueWithAssociationTest.java
@@ -19,10 +19,6 @@
*/
package org.apache.polygene.runtime.value;
-import org.apache.polygene.api.identity.HasIdentity;
-import org.apache.polygene.api.identity.Identity;
-import org.apache.polygene.api.identity.StringIdentity;
-import org.junit.Test;
import org.apache.polygene.api.association.Association;
import org.apache.polygene.api.association.AssociationStateHolder;
import org.apache.polygene.api.association.ManyAssociation;
@@ -31,16 +27,18 @@ import org.apache.polygene.api.common.Optional;
import org.apache.polygene.api.entity.EntityBuilder;
import org.apache.polygene.api.entity.EntityComposite;
import org.apache.polygene.api.entity.EntityReference;
+import org.apache.polygene.api.identity.HasIdentity;
+import org.apache.polygene.api.identity.Identity;
+import org.apache.polygene.api.identity.StringIdentity;
import org.apache.polygene.api.property.Property;
import org.apache.polygene.api.unitofwork.UnitOfWork;
import org.apache.polygene.api.unitofwork.UnitOfWorkCompletionException;
import org.apache.polygene.api.value.ValueBuilder;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
import org.apache.polygene.test.AbstractPolygeneTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
+import org.junit.Test;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
@@ -56,7 +54,6 @@ public class ValueWithAssociationTest extends AbstractPolygeneTest
module.values( SimpleName.class );
module.values( DualFaced.class );
module.services( MemoryEntityStoreService.class );
- module.services( OrgJsonValueSerializationService.class ).taggedWith( ValueSerialization.Formats.JSON );
}
@Test
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/test/java/org/apache/polygene/runtime/visibility/VisibilityInUnitOfWorkTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/polygene/runtime/visibility/VisibilityInUnitOfWorkTest.java b/core/runtime/src/test/java/org/apache/polygene/runtime/visibility/VisibilityInUnitOfWorkTest.java
index b7dfe66..66c4bc8 100644
--- a/core/runtime/src/test/java/org/apache/polygene/runtime/visibility/VisibilityInUnitOfWorkTest.java
+++ b/core/runtime/src/test/java/org/apache/polygene/runtime/visibility/VisibilityInUnitOfWorkTest.java
@@ -30,7 +30,6 @@ import org.apache.polygene.api.structure.Application;
import org.apache.polygene.api.structure.Module;
import org.apache.polygene.api.unitofwork.UnitOfWork;
import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.ApplicationAssembly;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.Energy4Java;
@@ -38,7 +37,6 @@ import org.apache.polygene.bootstrap.LayerAssembly;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.bootstrap.unitofwork.DefaultUnitOfWorkAssembler;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
import org.junit.Test;
public class VisibilityInUnitOfWorkTest
@@ -155,9 +153,6 @@ public class VisibilityInUnitOfWorkTest
yourModule.services( YourService.class ).visibleIn( Visibility.layer );
new DefaultUnitOfWorkAssembler().assemble( yourModule );
infraModule.services( MemoryEntityStoreService.class ).visibleIn( Visibility.layer );
- infraModule.services( OrgJsonValueSerializationService.class )
- .visibleIn( Visibility.layer )
- .taggedWith( ValueSerialization.Formats.JSON );
new DefaultUnitOfWorkAssembler().assemble( infraModule );
return appAssembly;
} );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/runtime/src/test/java/org/apache/polygene/test/performance/entitystore/memory/MemoryEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/core/runtime/src/test/java/org/apache/polygene/test/performance/entitystore/memory/MemoryEntityStoreTest.java b/core/runtime/src/test/java/org/apache/polygene/test/performance/entitystore/memory/MemoryEntityStoreTest.java
index ce4b878..25c4a1b 100644
--- a/core/runtime/src/test/java/org/apache/polygene/test/performance/entitystore/memory/MemoryEntityStoreTest.java
+++ b/core/runtime/src/test/java/org/apache/polygene/test/performance/entitystore/memory/MemoryEntityStoreTest.java
@@ -20,14 +20,12 @@
package org.apache.polygene.test.performance.entitystore.memory;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
import org.apache.polygene.spi.entity.EntityState;
import org.apache.polygene.spi.entitystore.StateChangeListener;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
import static org.apache.polygene.bootstrap.ImportedServiceDeclaration.NEW_OBJECT;
@@ -44,7 +42,6 @@ public class MemoryEntityStoreTest
super.assemble( module );
module.services( MemoryEntityStoreService.class );
- module.services( OrgJsonValueSerializationService.class ).taggedWith( ValueSerialization.Formats.JSON );
module.importedServices( StatePrinter.class ).importedBy( NEW_OBJECT );
module.objects( StatePrinter.class );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/build.gradle
----------------------------------------------------------------------
diff --git a/core/spi/build.gradle b/core/spi/build.gradle
index b6240e9..605d3c7 100644
--- a/core/spi/build.gradle
+++ b/core/spi/build.gradle
@@ -24,7 +24,9 @@ jar { manifest { name = "Apache Polygene\u2122 Core SPI" } }
dependencies {
api polygene.core.api
- api libraries.org_json
+ api libraries.javax_json
+
+ runtimeOnly libraries.johnzon
testImplementation polygene.core.testsupport
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/docs/serialization.txt
----------------------------------------------------------------------
diff --git a/core/spi/src/docs/serialization.txt b/core/spi/src/docs/serialization.txt
new file mode 100644
index 0000000..dca8955
--- /dev/null
+++ b/core/spi/src/docs/serialization.txt
@@ -0,0 +1,83 @@
+///////////////////////////////////////////////////////////////
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+///////////////////////////////////////////////////////////////
+
+[[core-spi-serialization,Serialization SPI]]
+= Serialization SPI =
+
+== Overview ==
+
+The Polygene\u2122 Core Runtime use Serialization to provide string representation of ValueComposites via their `toString()`
+method, and, their instantiation from the very same representation via the `newValueFromSerializedState(..)` method of
+the ValueBuilderFactory API.
+
+In each Module, if no Serialization service is assembled, a default one supporting the JSON format is used.
+
+// TODO Add sample usage of the Serialization service
+
+== Implementation notes ==
+
+Simply implement Serialization to create an extension for the Serialization SPI.
+The Core SPI module provides adapters to create pull-parsing capable Serializers and pull-parsing and tree-parsing
+capable Deserializers.
+
+The behaviour described here apply to all Serialization services implemented using the Core SPI adapters. Note that
+nothing stops you from implementing an extension for the Serialization SPI without relying on theses adapters.
+
+Theses adapters are tailored for serialization mechanisms that support the following two structures that can be nested:
+
+ * a collection of name/value pairs. In various languages, this is realized as an object, record, struct,
+ dictionary, hash table, keyed list, or associative array,
+ * an ordered list of values. In most languages, this is realized as an array, vector, list, or sequence ;
+
+in other words, a JSON-like structure.
+
+Special attention is taken when dealing with Maps. They are serialized as an ordered list of collections of
+name/value pairs to keep the Map order for least surprise. That way, even when the underlying serialization mechanism
+do not keep the collection of name/value pairs order we can rely on it being kept.
+
+Here is a sample Map with two entries in JSON notation to make things clear:
+
+[source,javascript]
+----
+[
+ { "key": "foo", "value": "bar" },
+ { "key": "cathedral", "value": "bazar" }
+]
+----
+
+Among Plain Values (see the <<core-api-value,Serialization API>> section) some are considered primitives to
+underlying serialization mechanisms and by so handed/come without conversion to/from implementations.
+
+Primitive values can be one of:
+
+ * String,
+ * Boolean or boolean,
+ * Integer or int,
+ * Long or long,
+ * Short or short,
+ * Byte or byte,
+ * Float or float,
+ * Double or double.
+
+Serialization is always done in a streaming manner using a pull-parsing based approach.
+
+Deserialization is done in a streaming manner using a pull-parsing based approach except when encountering a
+ValueComposite. ValueComposite types are deserialized using a tree-parsing based approach.
+
+All this means that you can serialize and deserialize large collections of values without filling the heap.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/docs/spi.txt
----------------------------------------------------------------------
diff --git a/core/spi/src/docs/spi.txt b/core/spi/src/docs/spi.txt
index 3980412..9371827 100644
--- a/core/spi/src/docs/spi.txt
+++ b/core/spi/src/docs/spi.txt
@@ -32,7 +32,7 @@ include::../../build/docs/buildinfo/artifact.txt[]
There are currently 5 Core SPI extensions;
- * <<core-spi-valueserialization>>
+ * <<core-spi-serialization>>
* <<core-spi-entitystore>>
* <<core-spi-cache>>
* <<core-spi-indexing>>
@@ -45,7 +45,7 @@ can be solved in a support manner, or that we need to extend the Core API to sup
:leveloffset: {level3}
-include::valueserialization.txt[]
+include::serialization.txt[]
:leveloffset: {level3}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/docs/valueserialization.txt
----------------------------------------------------------------------
diff --git a/core/spi/src/docs/valueserialization.txt b/core/spi/src/docs/valueserialization.txt
deleted file mode 100644
index 9f76b73..0000000
--- a/core/spi/src/docs/valueserialization.txt
+++ /dev/null
@@ -1,83 +0,0 @@
-///////////////////////////////////////////////////////////////
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
-///////////////////////////////////////////////////////////////
-
-[[core-spi-valueserialization,ValueSerialization SPI]]
-= ValueSerialization SPI =
-
-== Overview ==
-
-The Polygene\u2122 Core Runtime use ValueSerialization to provide string representation of ValueComposites via their `toString()`
-method, and, their instanciation from the very same representation via the `newValueFromSerializedState(..)` method of
-the ValueBuilderFactory API.
-
-If no ValueSerialization service is visible, a default implementation supporting the JSON format used but note that it
-won't be available as a Service. So, in order to use the full ValueSerialization API a ValueSerialization service must
-be explicitely assembled in the Application. See the <<extensions>> documentation for details.
-
-== Implementation notes ==
-
-Simply implement ValueSerialization to create an extension for the ValueSerialization SPI.
-The Core SPI module provides adapters to create pull-parsing capable ValueSerializers and pull-parsing and tree-parsing
-capable ValueDeserializers.
-
-The behaviour described here apply to all ValueSerialization services implemented using the Core SPI adapters. Note that
-nothing stops you from implementing an extension for the ValueSerialization SPI without relying on theses adapters.
-
-Theses adapters are tailored for serialization mechanisms that support the following two structures that can be nested:
-
- * a collection of name/value pairs. In various languages, this is realized as an object, record, struct,
- dictionary, hash table, keyed list, or associative array,
- * an ordered list of values. In most languages, this is realized as an array, vector, list, or sequence ;
-
-in other words, a JSON-like structure.
-
-Special attention is taken when dealing with Maps. They are serialized as an ordered list of collections of
-name/value pairs to keep the Map order for least surprise. That way, even when the underlying serialization mechanism
-do not keep the collection of name/value pairs order we can rely on it being kept.
-
-Here is a sample Map with two entries in JSON notation to make things clear:
-
-[source,javascript]
-----
-[
- { "key": "foo", "value": "bar" },
- { "key": "cathedral", "value": "bazar" }
-]
-----
-
-Among Plain Values (see the <<core-api-value,ValueSerialization API>> section) some are considered primitives to
-underlying serialization mechanisms and by so handed/come without conversion to/from implementations.
-
-Primitive values can be one of:
-
- * String,
- * Boolean or boolean,
- * Integer or int,
- * Long or long,
- * Short or short,
- * Byte or byte,
- * Float or float,
- * Double or double.
-
-Serialization is always done in a streaming manner using a pull-parsing based approach.
-
-Deserialization is done in a streaming manner using a pull-parsing based approach except when encountering a
-ValueComposite. ValueComposite types are deserialized using a tree-parsing based approach.
-
-All this means that you can serialize and deserialize large collections of values without filling the heap.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/entitystore/memory/MemoryMapEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/entitystore/memory/MemoryMapEntityStoreMixin.java b/core/spi/src/main/java/org/apache/polygene/entitystore/memory/MemoryMapEntityStoreMixin.java
index 7c343fa..98b4f8c 100644
--- a/core/spi/src/main/java/org/apache/polygene/entitystore/memory/MemoryMapEntityStoreMixin.java
+++ b/core/spi/src/main/java/org/apache/polygene/entitystore/memory/MemoryMapEntityStoreMixin.java
@@ -23,11 +23,11 @@ import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
-import java.io.UncheckedIOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
+import javax.json.Json;
import org.apache.polygene.api.entity.EntityDescriptor;
import org.apache.polygene.api.entity.EntityReference;
import org.apache.polygene.spi.entitystore.BackupRestore;
@@ -37,9 +37,6 @@ import org.apache.polygene.spi.entitystore.EntityStoreException;
import org.apache.polygene.spi.entitystore.helpers.JSONKeys;
import org.apache.polygene.spi.entitystore.helpers.MapEntityStore;
import org.apache.polygene.spi.entitystore.helpers.MapEntityStoreActivation;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.json.JSONTokener;
/**
* In-memory implementation of MapEntityStore.
@@ -55,21 +52,15 @@ public class MemoryMapEntityStoreMixin
}
@Override
- public void activateMapEntityStore()
- throws Exception
- {
- // NOOP
- }
+ public void activateMapEntityStore() {}
- public boolean contains( EntityReference entityReference, EntityDescriptor descriptor )
- throws EntityStoreException
+ public boolean contains( EntityReference entityReference, EntityDescriptor descriptor ) throws EntityStoreException
{
return store.containsKey( entityReference );
}
@Override
- public Reader get( EntityReference entityReference )
- throws EntityStoreException
+ public Reader get( EntityReference entityReference ) throws EntityStoreException
{
String state = store.get( entityReference );
if( state == null )
@@ -81,8 +72,7 @@ public class MemoryMapEntityStoreMixin
}
@Override
- public void applyChanges( MapEntityStore.MapChanges changes )
- throws IOException
+ public void applyChanges( MapEntityStore.MapChanges changes ) throws Exception
{
changes.visitMap( new MemoryMapChanger() );
}
@@ -100,29 +90,23 @@ public class MemoryMapEntityStoreMixin
}
@Override
- public void restore( final Stream<String> stream )
+ public void restore( Stream<String> stream )
{
store.clear();
- stream.forEach( item -> {
- try
+ stream.forEach(
+ item ->
{
- JSONTokener tokener = new JSONTokener( item );
- JSONObject entity = (JSONObject) tokener.nextValue();
- String id = entity.getString( JSONKeys.IDENTITY );
+ String id = Json.createReader( new StringReader( item ) )
+ .readObject().getString( JSONKeys.IDENTITY );
store.put( EntityReference.parseEntityReference( id ), item );
- }
- catch( JSONException e )
- {
- throw new UncheckedIOException( new IOException( e ) );
- }
- } );
+ } );
}
private class MemoryMapChanger
implements MapChanger
{
@Override
- public Writer newEntity( final EntityReference ref, EntityDescriptor descriptor )
+ public Writer newEntity( EntityReference ref, EntityDescriptor descriptor )
{
return new StringWriter( 1000 )
{
@@ -142,7 +126,7 @@ public class MemoryMapEntityStoreMixin
}
@Override
- public Writer updateEntity( final EntityReference ref, EntityDescriptor descriptor )
+ public Writer updateEntity( MapChange mapChange )
throws IOException
{
return new StringWriter( 1000 )
@@ -152,11 +136,12 @@ public class MemoryMapEntityStoreMixin
throws IOException
{
super.close();
- String old = store.put( ref, toString() );
+ EntityReference reference = mapChange.reference();
+ String old = store.put( reference, toString() );
if( old == null )
{
- store.remove( ref );
- throw new EntityNotFoundException( ref );
+ store.remove( reference );
+ throw new EntityNotFoundException( reference );
}
}
};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJson.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJson.java b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJson.java
new file mode 100644
index 0000000..3c44864
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJson.java
@@ -0,0 +1,139 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxjson;
+
+import java.util.Map;
+import javax.json.Json;
+import javax.json.JsonArray;
+import javax.json.JsonArrayBuilder;
+import javax.json.JsonException;
+import javax.json.JsonObject;
+import javax.json.JsonObjectBuilder;
+import javax.json.JsonString;
+import javax.json.JsonStructure;
+import javax.json.JsonValue;
+
+/**
+ * javax.json utilities.
+ */
+public class JavaxJson
+{
+ /**
+ * Create a {@link JsonObjectBuilder} populated with the state of a {@link JsonObject}.
+ *
+ * @param jo the JsonObject
+ * @return the builder
+ */
+ public static JsonObjectBuilder toBuilder( JsonObject jo )
+ {
+ JsonObjectBuilder job = Json.createObjectBuilder();
+ for( Map.Entry<String, JsonValue> entry : jo.entrySet() )
+ {
+ job.add( entry.getKey(), entry.getValue() );
+ }
+ return job;
+ }
+
+ /**
+ * Create a {@link JsonArrayBuilder} populated with the state of a {@link JsonArray}.
+ *
+ * @param ja the JsonArray
+ * @return the builder
+ */
+ public static JsonArrayBuilder toBuilder( JsonArray ja )
+ {
+ JsonArrayBuilder job = Json.createArrayBuilder();
+ for( JsonValue value : ja )
+ {
+ job.add( value );
+ }
+ return job;
+ }
+
+ /**
+ * Create a {@link JsonString} from {@link Object#toString()}.
+ *
+ * @param object the Object
+ * @return the JsonString
+ */
+ public static JsonString toJsonString( Object object )
+ {
+ return Json.createObjectBuilder().add( "value", object.toString() ).build().getJsonString( "value" );
+ }
+
+ /**
+ * Get a {@link String} out of a {@link JsonValue}.
+ *
+ * @param jsonValue the JSON value
+ * @return the String
+ */
+ public static String asString( JsonValue jsonValue )
+ {
+ return jsonValue instanceof JsonString ? ( (JsonString) jsonValue ).getString() : jsonValue.toString();
+ }
+
+ /**
+ * Require a {@link JsonValue} to be a {@link JsonStructure}.
+ *
+ * @param json the JSON value
+ * @return the JSON structure
+ * @throws JsonException if it is not
+ */
+ public static JsonStructure requireJsonStructure( JsonValue json )
+ {
+ if( json.getValueType() != JsonValue.ValueType.OBJECT && json.getValueType() != JsonValue.ValueType.ARRAY )
+ {
+ throw new JsonException( "Expected a JSON object or array but got " + json );
+ }
+ return (JsonStructure) json;
+ }
+
+ /**
+ * Require a {@link JsonValue} to be a {@link JsonObject}.
+ *
+ * @param json the JSON value
+ * @return the JSON object
+ * @throws JsonException if it is not
+ */
+ public static JsonObject requireJsonObject( JsonValue json )
+ {
+ if( json.getValueType() != JsonValue.ValueType.OBJECT )
+ {
+ throw new JsonException( "Expected a JSON object but got " + json );
+ }
+ return (JsonObject) json;
+ }
+
+ /**
+ * Require a {@link JsonValue} to be a {@link JsonArray}.
+ *
+ * @param json the JSON value
+ * @return the JSON array
+ * @throws JsonException if it is not
+ */
+ public static JsonArray requireJsonArray( JsonValue json )
+ {
+ if( json.getValueType() != JsonValue.ValueType.ARRAY )
+ {
+ throw new JsonException( "Expected a JSON array but got " + json );
+ }
+ return (JsonArray) json;
+ }
+
+ private JavaxJson() {}
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonAdapter.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonAdapter.java b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonAdapter.java
new file mode 100644
index 0000000..d8ffcfa
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonAdapter.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxjson;
+
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import javax.json.JsonValue;
+import org.apache.polygene.api.type.ValueType;
+
+/**
+ * Adapter for JSON (de)serialization.
+ *
+ * @param <T> the adapted type
+ */
+public interface JavaxJsonAdapter<T>
+{
+ /**
+ * @return the adapted type
+ */
+ Class<T> type();
+
+ /**
+ * Serialize.
+ *
+ * @param object Object to serialize, never null
+ * @param serializeFunction Serialization function for nested structure serialization
+ * @return Serialized JSON representation
+ */
+ JsonValue serialize( Object object, Function<Object, JsonValue> serializeFunction );
+
+ /**
+ * Deserialize.
+ *
+ * @param json JSON to deserialize from, never null
+ * @param deserializeFunction Deserialization function for nested structure deserialization
+ * @return Deserialized object
+ */
+ T deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction );
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonAdapters.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonAdapters.java b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonAdapters.java
new file mode 100644
index 0000000..fdc9d27
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonAdapters.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxjson;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.type.ValueType;
+
+import static org.apache.polygene.api.type.HasTypesCollectors.closestType;
+
+@Mixins( JavaxJsonAdapters.Mixin.class )
+public interface JavaxJsonAdapters
+{
+ void registerAdapter( ValueType valueType, JavaxJsonAdapter<?> adapter );
+
+ <T> JavaxJsonAdapter<T> adapterFor( ValueType valueType );
+
+ default <T> JavaxJsonAdapter<T> adapterFor( Class<T> type )
+ {
+ return adapterFor( ValueType.of( type ) );
+ }
+
+ class Mixin implements JavaxJsonAdapters
+ {
+ private Map<ValueType, JavaxJsonAdapter<?>> adapters = new LinkedHashMap<>();
+
+ @Override
+ public void registerAdapter( ValueType valueType, JavaxJsonAdapter<?> adapter )
+ {
+ adapters.put( valueType, adapter );
+ }
+
+ @Override
+ public <T> JavaxJsonAdapter<T> adapterFor( ValueType valueType )
+ {
+ return castAdapter( adapters.keySet().stream()
+ .collect( closestType( valueType ) )
+ .map( adapters::get )
+ .orElse( null ) );
+ }
+
+ @SuppressWarnings( "unchecked" )
+ private <T> JavaxJsonAdapter<T> castAdapter( JavaxJsonAdapter<?> adapter )
+ {
+ return (JavaxJsonAdapter<T>) adapter;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java
new file mode 100644
index 0000000..721c884
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java
@@ -0,0 +1,273 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxjson;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.util.AbstractMap;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.Collection;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Stream;
+import javax.json.JsonArray;
+import javax.json.JsonObject;
+import javax.json.JsonStructure;
+import javax.json.JsonValue;
+import org.apache.polygene.api.association.AssociationDescriptor;
+import org.apache.polygene.api.entity.EntityReference;
+import org.apache.polygene.api.injection.scope.This;
+import org.apache.polygene.api.injection.scope.Uses;
+import org.apache.polygene.api.property.PropertyDescriptor;
+import org.apache.polygene.api.serialization.SerializationException;
+import org.apache.polygene.api.service.ServiceDescriptor;
+import org.apache.polygene.api.structure.ModuleDescriptor;
+import org.apache.polygene.api.type.CollectionType;
+import org.apache.polygene.api.type.EnumType;
+import org.apache.polygene.api.type.MapType;
+import org.apache.polygene.api.type.ValueCompositeType;
+import org.apache.polygene.api.type.ValueType;
+import org.apache.polygene.api.value.ValueBuilder;
+import org.apache.polygene.api.value.ValueDescriptor;
+import org.apache.polygene.spi.serialization.AbstractTextDeserializer;
+import org.apache.polygene.spi.serialization.JsonDeserializer;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static java.util.Collections.unmodifiableList;
+import static java.util.Collections.unmodifiableMap;
+import static java.util.Collections.unmodifiableSet;
+import static java.util.stream.Collectors.toCollection;
+import static org.apache.polygene.api.util.Collectors.toMapWithNullValues;
+import static org.apache.polygene.serialization.javaxjson.JavaxJson.asString;
+import static org.apache.polygene.serialization.javaxjson.JavaxJson.requireJsonArray;
+import static org.apache.polygene.serialization.javaxjson.JavaxJson.requireJsonObject;
+import static org.apache.polygene.serialization.javaxjson.JavaxJson.requireJsonStructure;
+
+public class JavaxJsonDeserializer extends AbstractTextDeserializer implements JsonDeserializer
+{
+ @This
+ private JavaxJsonAdapters adapters;
+
+ @Uses
+ private ServiceDescriptor descriptor;
+
+ @Override
+ public <T> T fromJson( ModuleDescriptor module, ValueType valueType, JsonValue state )
+ {
+ return doDeserialize( module, valueType, state );
+ }
+
+ @SuppressWarnings( "unchecked" )
+ private <T> T doDeserialize( ModuleDescriptor module, ValueType valueType, JsonValue json )
+ {
+ if( json == null || JsonValue.NULL.equals( json ) )
+ {
+ return null;
+ }
+ JavaxJsonAdapter<?> adapter = adapters.adapterFor( valueType );
+ if( adapter != null )
+ {
+ return (T) adapter.deserialize( json, ( jsonValue, type ) -> doDeserialize( module, type, jsonValue ) );
+ }
+ Class<? extends ValueType> valueTypeClass = valueType.getClass();
+ if( EnumType.class.isAssignableFrom( valueTypeClass ) )
+ {
+ return (T) Enum.valueOf( (Class) valueType.primaryType(), asString( json ) );
+ }
+ if( CollectionType.class.isAssignableFrom( valueTypeClass ) )
+ {
+ return (T) deserializeCollection( module, (CollectionType) valueType, requireJsonArray( json ) );
+ }
+ if( MapType.class.isAssignableFrom( valueTypeClass ) )
+ {
+ return (T) deserializeMap( module, (MapType) valueType, requireJsonStructure( json ) );
+ }
+ if( ValueCompositeType.class.isAssignableFrom( valueTypeClass ) )
+ {
+ return (T) deserializeValueComposite( module, (ValueCompositeType) valueType, requireJsonObject( json ) );
+ }
+ return doGuessDeserialize( module, valueType, json );
+ }
+
+ @SuppressWarnings( "unchecked" )
+ private <T> T doGuessDeserialize( ModuleDescriptor module, ValueType valueType, JsonValue json )
+ {
+ switch( json.getValueType() )
+ {
+ case OBJECT:
+ JsonObject object = (JsonObject) json;
+ String typeInfo = object.getString( getTypeInfoPropertyName(), valueType.primaryType().getName() );
+ ValueDescriptor valueDescriptor = module.valueDescriptor( typeInfo );
+ if( valueDescriptor != null )
+ {
+ return (T) deserializeValueComposite( module, valueDescriptor.valueType(), object );
+ }
+ case STRING:
+ return (T) deserializeBase64( asString( json ) );
+ default:
+ throw new SerializationException( "Don't know how to deserialize " + valueType + " from " + json );
+ }
+ }
+
+ private <T> Collection<T> deserializeCollection( ModuleDescriptor module, CollectionType collectionType,
+ JsonArray json )
+ {
+ return (Collection<T>) json.stream()
+ .map( item -> doDeserialize( module, collectionType.collectedType(), item ) )
+ .collect( toCollection(
+ () -> collectionType.isSet() ? new LinkedHashSet<>() : new ArrayList<>() ) );
+ }
+
+ /**
+ * Map deserialization.
+ *
+ * {@literal JsonObject}s are deserialized to {@literal Map<String, ?>}.
+ * {@literal JsonArray}s of key/value {@literal JsonObject}s are deserialized to {@literal Map<?, ?>}.
+ */
+ private Map<?, ?> deserializeMap( ModuleDescriptor module, MapType mapType, JsonStructure json )
+ {
+ if( json.getValueType() == JsonValue.ValueType.OBJECT )
+ {
+ JsonObject object = (JsonObject) json;
+ return object.entrySet().stream()
+ .map( entry -> new AbstractMap.SimpleImmutableEntry<>(
+ entry.getKey(),
+ doDeserialize( module, mapType.valueType(), entry.getValue() ) ) )
+ .collect( toMapWithNullValues( LinkedHashMap::new ) );
+ }
+ if( json.getValueType() == JsonValue.ValueType.ARRAY )
+ {
+ JsonArray array = (JsonArray) json;
+ return array.stream()
+ .map( JsonObject.class::cast )
+ .map( entry -> new AbstractMap.SimpleImmutableEntry<>(
+ doDeserialize( module, mapType.keyType(), entry.get( "key" ) ),
+ doDeserialize( module, mapType.valueType(), entry.get( "value" ) )
+ ) )
+ .collect( toMapWithNullValues( LinkedHashMap::new ) );
+ }
+ throw new SerializationException( "Don't know how to deserialize " + mapType + " from " + json );
+ }
+
+ private Object deserializeValueComposite( ModuleDescriptor module, ValueCompositeType valueType, JsonObject json )
+ {
+ String typeInfoName = getTypeInfoPropertyName();
+ String typeInfo = json.getString( typeInfoName, null );
+ if( typeInfo != null )
+ {
+ ValueDescriptor descriptor = module.valueDescriptor( typeInfo );
+ if( descriptor == null )
+ {
+ throw new SerializationException(
+ typeInfoName + ": " + typeInfo + " could not be resolved while deserializing " + json );
+ }
+ valueType = descriptor.valueType();
+ }
+ ValueBuilder builder = module.instance().newValueBuilderWithState(
+ valueType.primaryType(),
+ propertyFunction( module, json ),
+ associationFunction( module, json ),
+ manyAssociationFunction( module, json ),
+ namedAssociationFunction( module, json ) );
+ return builder.newInstance();
+ }
+
+ private Function<PropertyDescriptor, Object> propertyFunction( ModuleDescriptor module, JsonObject object )
+ {
+ return property ->
+ {
+ JsonValue jsonValue = object.get( property.qualifiedName().name() );
+ if( jsonValue != null )
+ {
+ Object value = doDeserialize( module, property.valueType(), jsonValue );
+ if( property.isImmutable() )
+ {
+ if( value instanceof Set )
+ {
+ return unmodifiableSet( (Set<?>) value );
+ }
+ else if( value instanceof List )
+ {
+ return unmodifiableList( (List<?>) value );
+ }
+ else if( value instanceof Map )
+ {
+ return unmodifiableMap( (Map<?, ?>) value );
+ }
+ }
+ return value;
+ }
+ return property.resolveInitialValue( module );
+ };
+ }
+
+ private Function<AssociationDescriptor, EntityReference> associationFunction( ModuleDescriptor module,
+ JsonObject object )
+ {
+ return association -> doDeserialize( module, ValueType.ENTITY_REFERENCE,
+ object.get( association.qualifiedName().name() ) );
+ }
+
+ private Function<AssociationDescriptor, Stream<EntityReference>> manyAssociationFunction( ModuleDescriptor module,
+ JsonObject object )
+ {
+ return association ->
+ {
+ List<EntityReference> list = doDeserialize( module, ENTITY_REF_LIST_VALUE_TYPE,
+ object.get( association.qualifiedName().name() ) );
+ return list == null ? Stream.empty() : list.stream();
+ };
+ }
+
+ private Function<AssociationDescriptor, Stream<Map.Entry<String, EntityReference>>> namedAssociationFunction(
+ ModuleDescriptor module, JsonObject object )
+ {
+ return association ->
+ {
+ Map<String, EntityReference> map = doDeserialize( module, ENTITY_REF_MAP_VALUE_TYPE,
+ object.get( association.qualifiedName().name() ) );
+ return map == null ? Stream.empty() : map.entrySet().stream();
+ };
+ }
+
+ private Object deserializeBase64( String inputString )
+ {
+ byte[] bytes = inputString.getBytes( UTF_8 );
+ bytes = Base64.getDecoder().decode( bytes );
+ try( ObjectInputStream oin = new ObjectInputStream( new ByteArrayInputStream( bytes ) ) )
+ {
+ return oin.readObject();
+ }
+ catch( IOException | ClassNotFoundException ex )
+ {
+ throw new SerializationException( "Unable to deserialize Base64 serialized " + inputString, ex );
+ }
+ }
+
+ private String getTypeInfoPropertyName()
+ {
+ return JavaxJsonSettings.orDefault( descriptor.metaInfo( JavaxJsonSettings.class ) )
+ .getTypeInfoPropertyName();
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerialization.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerialization.java b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerialization.java
new file mode 100644
index 0000000..2e034b0
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerialization.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxjson;
+
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.spi.serialization.JsonSerialization;
+
+@Mixins( { JavaxJsonSerializer.class, JavaxJsonDeserializer.class } )
+public interface JavaxJsonSerialization extends JsonSerialization
+{
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializationService.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializationService.java b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializationService.java
new file mode 100644
index 0000000..2b662ea
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializationService.java
@@ -0,0 +1,533 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxjson;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.OffsetDateTime;
+import java.time.Period;
+import java.time.ZonedDateTime;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import javax.json.Json;
+import javax.json.JsonNumber;
+import javax.json.JsonString;
+import javax.json.JsonValue;
+import org.apache.polygene.api.entity.EntityReference;
+import org.apache.polygene.api.identity.Identity;
+import org.apache.polygene.api.identity.StringIdentity;
+import org.apache.polygene.api.injection.scope.This;
+import org.apache.polygene.api.injection.scope.Uses;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.serialization.SerializationException;
+import org.apache.polygene.api.service.ServiceActivation;
+import org.apache.polygene.api.service.ServiceDescriptor;
+import org.apache.polygene.api.type.ValueType;
+
+// TODO Move into JavaxJsonSerialization
+// TODO Do the same on XML & MessagePack
+@Mixins( JavaxJsonSerializationService.Activation.class )
+public interface JavaxJsonSerializationService extends JavaxJsonSerialization, ServiceActivation
+{
+ class Activation implements ServiceActivation
+ {
+ @Uses
+ private ServiceDescriptor descriptor;
+
+ @This
+ private JavaxJsonAdapters adapters;
+
+ private boolean registrationDone = false;
+
+ @Override
+ public void activateService()
+ {
+ if( !registrationDone )
+ {
+ registerCustomAdapters();
+ registerBaseAdapters();
+ registrationDone = true;
+ }
+ }
+
+ @Override
+ public void passivateService() {}
+
+ private void registerCustomAdapters()
+ {
+ JavaxJsonSettings.orDefault( descriptor.metaInfo( JavaxJsonSettings.class ) )
+ .getAdapters()
+ .forEach( ( valueType, adapter ) -> adapters.registerAdapter( valueType, adapter ) );
+ }
+
+ private void registerBaseAdapters()
+ {
+ // Primitive Value types
+ adapters.registerAdapter( ValueType.STRING, new StringAdapter() );
+ adapters.registerAdapter( ValueType.CHARACTER, new CharacterAdapter() );
+ adapters.registerAdapter( ValueType.BOOLEAN, new BooleanAdapter() );
+ adapters.registerAdapter( ValueType.INTEGER, new IntegerAdapter() );
+ adapters.registerAdapter( ValueType.LONG, new LongAdapter() );
+ adapters.registerAdapter( ValueType.SHORT, new ShortAdapter() );
+ adapters.registerAdapter( ValueType.BYTE, new ByteAdapter() );
+ adapters.registerAdapter( ValueType.FLOAT, new FloatAdapter() );
+ adapters.registerAdapter( ValueType.DOUBLE, new DoubleAdapter() );
+
+ // Number types
+ adapters.registerAdapter( ValueType.BIG_DECIMAL, new BigDecimalAdapter() );
+ adapters.registerAdapter( ValueType.BIG_INTEGER, new BigIntegerAdapter() );
+
+ // Date types
+ adapters.registerAdapter( ValueType.INSTANT, new InstantAdapter() );
+ adapters.registerAdapter( ValueType.ZONED_DATE_TIME, new ZonedDateTimeAdapter() );
+ adapters.registerAdapter( ValueType.OFFSET_DATE_TIME, new OffsetDateTimeAdapter() );
+ adapters.registerAdapter( ValueType.LOCAL_DATE_TIME, new LocalDateTimeAdapter() );
+ adapters.registerAdapter( ValueType.LOCAL_DATE, new LocalDateAdapter() );
+ adapters.registerAdapter( ValueType.LOCAL_TIME, new LocalTimeAdapter() );
+ adapters.registerAdapter( ValueType.DURATION, new DurationAdapter() );
+ adapters.registerAdapter( ValueType.PERIOD, new PeriodAdapter() );
+
+ // Other supported types
+ adapters.registerAdapter( ValueType.IDENTITY, new IdentityAdapter() );
+ adapters.registerAdapter( ValueType.ENTITY_REFERENCE, new EntityReferenceAdapter() );
+ }
+
+ private static abstract class ToJsonStringAdapter<T> implements JavaxJsonAdapter<T>
+ {
+ @Override
+ public JsonValue serialize( Object object, Function<Object, JsonValue> serializeFunction )
+ {
+ return JavaxJson.toJsonString( object );
+ }
+ }
+
+ private static class StringAdapter extends ToJsonStringAdapter<String>
+ {
+ @Override
+ public Class<String> type() { return String.class; }
+
+ @Override
+ public String deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ return JavaxJson.asString( json );
+ }
+ }
+
+ private static class CharacterAdapter extends ToJsonStringAdapter<Character>
+ {
+ @Override
+ public Class<Character> type() { return Character.class; }
+
+ @Override
+ public Character deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ String string = JavaxJson.asString( json );
+ return string.isEmpty() ? null : string.charAt( 0 );
+ }
+ }
+
+ private static class BooleanAdapter implements JavaxJsonAdapter<Boolean>
+ {
+ @Override
+ public Class<Boolean> type() { return Boolean.class; }
+
+ @Override
+ public JsonValue serialize( Object object, Function<Object, JsonValue> serializeFunction )
+ {
+ return type().cast( object ) ? JsonValue.TRUE : JsonValue.FALSE;
+ }
+
+ @Override
+ public Boolean deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ switch( json.getValueType() )
+ {
+ case TRUE:
+ return true;
+ case FALSE:
+ return false;
+ case NULL:
+ return null;
+ case NUMBER:
+ return ( (JsonNumber) json ).doubleValue() > 0;
+ case STRING:
+ return Boolean.valueOf( ( (JsonString) json ).getString() );
+ default:
+ throw new SerializationException( "Don't know how to deserialize Boolean from " + json );
+ }
+ }
+ }
+
+ private static class IntegerAdapter implements JavaxJsonAdapter<Integer>
+ {
+ @Override
+ public Class<Integer> type() { return Integer.class; }
+
+ @Override
+ public JsonValue serialize( Object object, Function<Object, JsonValue> serializeFunction )
+ {
+ return Json.createObjectBuilder().add( "value", type().cast( object ) ).build()
+ .getJsonNumber( "value" );
+ }
+
+ @Override
+ public Integer deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ switch( json.getValueType() )
+ {
+ case NULL:
+ return null;
+ case NUMBER:
+ return ( (JsonNumber) json ).intValueExact();
+ case STRING:
+ String string = ( (JsonString) json ).getString();
+ return string.isEmpty() ? 0 : Integer.parseInt( string );
+ default:
+ throw new SerializationException( "Don't know how to deserialize Integer from " + json );
+ }
+ }
+ }
+
+ private static class LongAdapter implements JavaxJsonAdapter<Long>
+ {
+ @Override
+ public Class<Long> type() { return Long.class; }
+
+ @Override
+ public JsonValue serialize( Object object, Function<Object, JsonValue> serializeFunction )
+ {
+ return Json.createObjectBuilder().add( "value", type().cast( object ) ).build().getJsonNumber(
+ "value" );
+ }
+
+ @Override
+ public Long deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ switch( json.getValueType() )
+ {
+ case NULL:
+ return null;
+ case NUMBER:
+ return ( (JsonNumber) json ).longValueExact();
+ case STRING:
+ String string = ( (JsonString) json ).getString();
+ return string.isEmpty() ? 0L : Long.parseLong( string );
+ default:
+ throw new SerializationException( "Don't know how to deserialize Long from " + json );
+ }
+ }
+ }
+
+ private static class ShortAdapter implements JavaxJsonAdapter<Short>
+ {
+ @Override
+ public Class<Short> type() { return Short.class; }
+
+ @Override
+ public JsonValue serialize( Object object, Function<Object, JsonValue> serializeFunction )
+ {
+ return Json.createObjectBuilder().add( "value", type().cast( object ) ).build()
+ .getJsonNumber( "value" );
+ }
+
+ @Override
+ public Short deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ switch( json.getValueType() )
+ {
+ case NULL:
+ return null;
+ case NUMBER:
+ return (short) ( (JsonNumber) json ).intValueExact();
+ case STRING:
+ String string = ( (JsonString) json ).getString();
+ return string.isEmpty() ? 0 : Short.parseShort( string );
+ default:
+ throw new SerializationException( "Don't know how to deserialize Short from " + json );
+ }
+ }
+ }
+
+ private static class ByteAdapter implements JavaxJsonAdapter<Byte>
+ {
+ @Override
+ public Class<Byte> type() { return Byte.class; }
+
+ @Override
+ public JsonValue serialize( Object object, Function<Object, JsonValue> serializeFunction )
+ {
+ return Json.createObjectBuilder().add( "value", type().cast( object ) ).build()
+ .getJsonNumber( "value" );
+ }
+
+ @Override
+ public Byte deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ switch( json.getValueType() )
+ {
+ case NULL:
+ return null;
+ case NUMBER:
+ return (byte) ( (JsonNumber) json ).intValueExact();
+ case STRING:
+ String string = ( (JsonString) json ).getString();
+ return string.isEmpty() ? 0 : Byte.parseByte( string );
+ default:
+ throw new SerializationException( "Don't know how to deserialize Byte from " + json );
+ }
+ }
+ }
+
+ private static class FloatAdapter implements JavaxJsonAdapter<Float>
+ {
+ @Override
+ public Class<Float> type() { return Float.class; }
+
+ @Override
+ public JsonValue serialize( Object object, Function<Object, JsonValue> serializeFunction )
+ {
+ return Json.createObjectBuilder().add( "value", type().cast( object ) ).build()
+ .getJsonNumber( "value" );
+ }
+
+ @Override
+ public Float deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ switch( json.getValueType() )
+ {
+ case NULL:
+ return null;
+ case NUMBER:
+ return (float) ( (JsonNumber) json ).doubleValue();
+ case STRING:
+ String string = ( (JsonString) json ).getString();
+ return string.isEmpty() ? 0F : Float.parseFloat( string );
+ default:
+ throw new SerializationException( "Don't know how to deserialize Float from " + json );
+ }
+ }
+ }
+
+ private static class DoubleAdapter implements JavaxJsonAdapter<Double>
+ {
+ @Override
+ public Class<Double> type() { return Double.class; }
+
+ @Override
+ public JsonValue serialize( Object object, Function<Object, JsonValue> serializeFunction )
+ {
+ return Json.createObjectBuilder().add( "value", type().cast( object ) ).build()
+ .getJsonNumber( "value" );
+ }
+
+ @Override
+ public Double deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ switch( json.getValueType() )
+ {
+ case NULL:
+ return null;
+ case NUMBER:
+ return ( (JsonNumber) json ).doubleValue();
+ case STRING:
+ String string = ( (JsonString) json ).getString();
+ return string.isEmpty() ? 0D : Double.parseDouble( string );
+ default:
+ throw new SerializationException( "Don't know how to deserialize Double from " + json );
+ }
+ }
+ }
+
+ private static class BigDecimalAdapter extends ToJsonStringAdapter<BigDecimal>
+ {
+ @Override
+ public Class<BigDecimal> type() { return BigDecimal.class; }
+
+ @Override
+ public BigDecimal deserialize( JsonValue json,
+ BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ switch( json.getValueType() )
+ {
+ case NULL:
+ return null;
+ case NUMBER:
+ return new BigDecimal( json.toString() );
+ case STRING:
+ return new BigDecimal( ( (JsonString) json ).getString() );
+ default:
+ throw new SerializationException(
+ "Don't know how to deserialize BigDecimal from " + json );
+ }
+ }
+ }
+
+ private static class BigIntegerAdapter extends ToJsonStringAdapter<BigInteger>
+ {
+ @Override
+ public Class<BigInteger> type() { return BigInteger.class; }
+
+ @Override
+ public BigInteger deserialize( JsonValue json,
+ BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ switch( json.getValueType() )
+ {
+ case NULL:
+ return null;
+ case NUMBER:
+ return new BigInteger( json.toString() );
+ case STRING:
+ return new BigInteger( ( (JsonString) json ).getString() );
+ default:
+ throw new SerializationException(
+ "Don't know how to deserialize BigInteger from " + json );
+ }
+ }
+ }
+
+ private static class PeriodAdapter extends ToJsonStringAdapter<Period>
+ {
+ @Override
+ public Class<Period> type() { return Period.class; }
+
+ @Override
+ public Period deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ return Period.parse( JavaxJson.asString( json ) );
+ }
+ }
+
+ private static class DurationAdapter extends ToJsonStringAdapter<Duration>
+ {
+ @Override
+ public Class<Duration> type() { return Duration.class; }
+
+ @Override
+ public Duration deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ return Duration.parse( JavaxJson.asString( json ) );
+ }
+ }
+
+ private static class LocalTimeAdapter extends ToJsonStringAdapter<LocalTime>
+ {
+ @Override
+ public Class<LocalTime> type() { return LocalTime.class; }
+
+ @Override
+ public LocalTime deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ return LocalTime.parse( JavaxJson.asString( json ) );
+ }
+ }
+
+ private static class LocalDateAdapter extends ToJsonStringAdapter<LocalDate>
+ {
+ @Override
+ public Class<LocalDate> type() { return LocalDate.class; }
+
+ @Override
+ public LocalDate deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ return LocalDate.parse( JavaxJson.asString( json ) );
+ }
+ }
+
+ private static class LocalDateTimeAdapter extends ToJsonStringAdapter<LocalDateTime>
+ {
+ @Override
+ public Class<LocalDateTime> type() { return LocalDateTime.class; }
+
+ @Override
+ public LocalDateTime deserialize( JsonValue json,
+ BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ return LocalDateTime.parse( JavaxJson.asString( json ) );
+ }
+ }
+
+ private static class OffsetDateTimeAdapter extends ToJsonStringAdapter<OffsetDateTime>
+ {
+ @Override
+ public Class<OffsetDateTime> type() { return OffsetDateTime.class; }
+
+ @Override
+ public OffsetDateTime deserialize( JsonValue json,
+ BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ return OffsetDateTime.parse( JavaxJson.asString( json ) );
+ }
+ }
+
+ private static class ZonedDateTimeAdapter extends ToJsonStringAdapter<ZonedDateTime>
+ {
+ @Override
+ public Class<ZonedDateTime> type() { return ZonedDateTime.class; }
+
+ @Override
+ public ZonedDateTime deserialize( JsonValue json,
+ BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ return ZonedDateTime.parse( JavaxJson.asString( json ) );
+ }
+ }
+
+ private static class InstantAdapter extends ToJsonStringAdapter<Instant>
+ {
+ @Override
+ public Class<Instant> type() { return Instant.class; }
+
+ @Override
+ public Instant deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ return Instant.parse( JavaxJson.asString( json ) );
+ }
+ }
+
+ private static class IdentityAdapter extends ToJsonStringAdapter<Identity>
+ {
+ @Override
+ public Class<Identity> type() { return Identity.class; }
+
+ @Override
+ public Identity deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ return StringIdentity.fromString( JavaxJson.asString( json ) );
+ }
+ }
+
+ private static class EntityReferenceAdapter extends ToJsonStringAdapter<EntityReference>
+ {
+ @Override
+ public Class<EntityReference> type() { return EntityReference.class; }
+
+ @Override
+ public EntityReference deserialize( JsonValue json,
+ BiFunction<JsonValue, ValueType, Object> deserializeFunction )
+ {
+ return EntityReference.parseEntityReference( JavaxJson.asString( json ) );
+ }
+ }
+ }
+}
[29/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/type/ValueTypeFactory.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/type/ValueTypeFactory.java b/core/spi/src/main/java/org/apache/polygene/spi/type/ValueTypeFactory.java
new file mode 100644
index 0000000..73f79eb
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/spi/type/ValueTypeFactory.java
@@ -0,0 +1,11 @@
+package org.apache.polygene.spi.type;
+
+import org.apache.polygene.api.structure.ModuleDescriptor;
+import org.apache.polygene.api.type.ValueType;
+
+public interface ValueTypeFactory
+{
+ ValueType valueTypeOf( ModuleDescriptor module, Object object );
+
+ ValueType valueTypeOf( ModuleDescriptor module, Class<?> type );
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/value/ValueDeserializerAdapter.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/value/ValueDeserializerAdapter.java b/core/spi/src/main/java/org/apache/polygene/spi/value/ValueDeserializerAdapter.java
deleted file mode 100644
index c586498..0000000
--- a/core/spi/src/main/java/org/apache/polygene/spi/value/ValueDeserializerAdapter.java
+++ /dev/null
@@ -1,1001 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.spi.value;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.io.ObjectInputStream;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.time.Duration;
-import java.time.Instant;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.LocalTime;
-import java.time.OffsetDateTime;
-import java.time.Period;
-import java.time.ZonedDateTime;
-import java.util.ArrayList;
-import java.util.Base64;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Scanner;
-import java.util.Set;
-import java.util.function.Function;
-import java.util.stream.Stream;
-import java.util.stream.StreamSupport;
-import org.apache.polygene.api.entity.EntityReference;
-import org.apache.polygene.api.identity.Identity;
-import org.apache.polygene.api.identity.StringIdentity;
-import org.apache.polygene.api.property.Property;
-import org.apache.polygene.api.structure.ModuleDescriptor;
-import org.apache.polygene.api.type.CollectionType;
-import org.apache.polygene.api.type.EnumType;
-import org.apache.polygene.api.type.MapType;
-import org.apache.polygene.api.type.Serialization;
-import org.apache.polygene.api.type.ValueCompositeType;
-import org.apache.polygene.api.type.ValueType;
-import org.apache.polygene.api.value.ValueBuilder;
-import org.apache.polygene.api.value.ValueDescriptor;
-import org.apache.polygene.api.value.ValueDeserializer;
-import org.apache.polygene.api.value.ValueSerializationException;
-
-/**
- * Adapter for pull-parsing and tree-parsing capable ValueDeserializers.
- *
- * <p>
- * Among Plain values (see {@link ValueDeserializer}) some are considered primitives to underlying serialization
- * mechanisms and by so handed/come without conversion to/from implementations. Primitive values can be one of:
- * </p>
- * <ul>
- * <li>String,</li>
- * <li>Character or char,</li>
- * <li>Boolean or boolean,</li>
- * <li>Integer or int,</li>
- * <li>Long or long,</li>
- * <li>Short or short,</li>
- * <li>Byte or byte,</li>
- * <li>Float or float,</li>
- * <li>Double or double.</li>
- * </ul>
- * <p>
- * Some other Plain values are expected in given formats:
- * </p>
- * <ul>
- * <li>BigInteger and BigDecimal depends on {@link org.apache.polygene.api.value.ValueSerializer.Options};</li>
- * <li>Date as String in ISO-8601, {@literal @millis@} or {@literal /Date(..)} Microsoft format;</li>
- * <li>DateTime (JodaTime) as a ISO-8601 String with optional timezone offset;</li>
- * <li>LocalDateTime (JodaTime) as whatever {@link LocalDateTime#parse} accept as {@literal instant};</li>
- * <li>LocalDate (JodaTime) as whatever {@link LocalDate#parse} accept as {@literal instant};</li>
- * </ul>
- *
- * @param <InputType> Implementor pull-parser type
- * @param <InputNodeType> Implementor tree-parser node type
- */
-public abstract class ValueDeserializerAdapter<InputType, InputNodeType>
- implements ValueDeserializer
-{
- public interface ComplexDeserializer<T, InputType, InputNodeType>
- {
- T deserializePull( InputType input )
- throws Exception;
-
- T deserializeTree( InputNodeType inputNode )
- throws Exception;
- }
-
- private static final String UTF_8 = "UTF-8";
- private final Map<Class<?>, Function<Object, Object>> deserializers = new HashMap<>( 16 );
- private final Map<Class<?>, ComplexDeserializer<Object, InputType, InputNodeType>> complexDeserializers = new HashMap<>( 2 );
-
- /**
- * Register a Plain Value type deserialization Function.
- *
- * @param <T> Plain Value parametrized Type
- * @param type Plain Value Type
- * @param deserializer Deserialization Function
- */
- @SuppressWarnings( "unchecked" )
- protected final <T> void registerDeserializer( Class<T> type, Function<Object, T> deserializer )
- {
- deserializers.put( type, (Function<Object, Object>) deserializer );
- }
-
- @SuppressWarnings( { "UnusedDeclaration", "unchecked" } )
- protected final <T> void registerComplexDeserializer( Class<T> type,
- ComplexDeserializer<T, InputType, InputNodeType> deserializer
- )
- {
- complexDeserializers.put( type, (ComplexDeserializer<Object, InputType, InputNodeType>) deserializer );
- }
-
- protected ValueDeserializerAdapter()
- {
-
- // Primitive Value types
- registerDeserializer( String.class, Object::toString );
- registerDeserializer( Character.class, input -> input.toString().charAt( 0 ) );
- registerDeserializer( Boolean.class, input -> ( input instanceof String )
- ? Boolean.parseBoolean( (String) input )
- : (Boolean) input );
- registerDeserializer( Integer.class, input -> ( input instanceof String )
- ? Integer.parseInt( (String) input )
- : ( (Number) input ).intValue() );
- registerDeserializer( Long.class, input -> ( input instanceof String )
- ? Long.parseLong( (String) input )
- : ( (Number) input ).longValue() );
- registerDeserializer( Short.class, input -> ( input instanceof String )
- ? Short.parseShort( (String) input )
- : ( (Number) input ).shortValue() );
- registerDeserializer( Byte.class, input -> ( input instanceof String )
- ? Byte.parseByte( (String) input )
- : ( (Number) input ).byteValue() );
- registerDeserializer( Float.class, input -> ( input instanceof String )
- ? Float.parseFloat( (String) input )
- : ( (Number) input ).floatValue() );
- registerDeserializer( Double.class, input -> ( input instanceof String )
- ? Double.parseDouble( (String) input )
- : ( (Number) input ).doubleValue() );
-
- // Number types
- registerDeserializer( BigDecimal.class, input -> new BigDecimal( input.toString() ) );
- registerDeserializer( BigInteger.class, input -> new BigInteger( input.toString() ) );
- registerDeserializer( Identity.class, input -> StringIdentity.fromString( input.toString() ) );
-
- // Date types
- registerDeserializer( Instant.class, input -> Instant.parse( input.toString() ) );
- registerDeserializer( ZonedDateTime.class, input -> ZonedDateTime.parse( input.toString() ) );
- registerDeserializer( OffsetDateTime.class, input -> OffsetDateTime.parse( input.toString() ) );
- registerDeserializer( LocalDateTime.class, input -> LocalDateTime.parse( input.toString() ) );
- registerDeserializer( LocalDate.class, input -> LocalDate.parse( input.toString() ));
- registerDeserializer( LocalTime.class, input -> LocalTime.parse( input.toString() ));
- registerDeserializer( Duration.class, input -> Duration.parse( input.toString() ));
- registerDeserializer( Period.class, input -> Period.parse( input.toString() ));
-
- // Other supported types
- registerDeserializer( EntityReference.class, input -> EntityReference.parseEntityReference( input.toString() ) );
- }
-
- @Override
- public <T> Function<String, T> deserialize( ModuleDescriptor module, Class<T> type )
- {
- if( CollectionType.isCollection( type ) )
- {
- ValueType objectValueType = new ValueType( Object.class );
- return deserialize( module, new CollectionType( type, objectValueType ) );
- }
- if( MapType.isMap( type ) )
- {
- ValueType objectValueType = new ValueType( Object.class );
- return deserialize( module, new MapType( type, objectValueType, objectValueType ) );
- }
- return deserialize( module, new ValueType( type ) );
- }
-
- @Override
- public final <T> Function<String, T> deserialize( ModuleDescriptor module, ValueType valueType )
- {
- return input -> deserialize( module, valueType, input );
- }
-
- @Override
- public final <T> T deserialize( ModuleDescriptor module, Class<?> type, String input )
- throws ValueSerializationException
- {
- if( CollectionType.isCollection( type ) )
- {
- ValueType objectValueType = new ValueType( Object.class );
- return deserialize( module, new CollectionType( type, objectValueType ), input );
- }
- if( MapType.isMap( type ) )
- {
- ValueType objectValueType = new ValueType( Object.class );
- return deserialize( module, new MapType( type, objectValueType, objectValueType ), input );
- }
- return deserialize( module, new ValueType( type ), input );
- }
-
- @Override
- public final <T> T deserialize( ModuleDescriptor module, ValueType valueType, String input )
- throws ValueSerializationException
- {
- try
- {
- return deserializeRoot( module, valueType, new ByteArrayInputStream( input.getBytes( UTF_8 ) ) );
- }
- catch( ValueSerializationException ex )
- {
- throw ex;
- }
- catch( Exception ex )
- {
- throw new ValueSerializationException( "Could not deserialize value", ex );
- }
- }
-
- @Override
- public final <T> T deserialize( ModuleDescriptor module, Class<?> type, InputStream input )
- throws ValueSerializationException
- {
- if( CollectionType.isCollection( type ) )
- {
- ValueType objectValueType = new ValueType( Object.class );
- return deserialize( module, new CollectionType( type, objectValueType ), input );
- }
- if( MapType.isMap( type ) )
- {
- ValueType objectValueType = new ValueType( Object.class );
- return deserialize( module, new MapType( type, objectValueType, objectValueType ), input );
- }
- return deserialize( module, new ValueType( type ), input );
- }
-
- @Override
- public final <T> T deserialize( ModuleDescriptor module, ValueType valueType, InputStream input )
- throws ValueSerializationException
- {
- try
- {
- return deserializeRoot( module, valueType, input );
- }
- catch( ValueSerializationException ex )
- {
- throw ex;
- }
- catch( Exception ex )
- {
- throw new ValueSerializationException( "Could not deserialize value", ex );
- }
- }
-
- @SuppressWarnings( "unchecked" )
- private <T> T deserializeRoot( ModuleDescriptor module, ValueType valueType, InputStream input )
- throws Exception
- {
- Class<?> type = valueType.types().findFirst().orElse( null );
-
- if( Identity.class.isAssignableFrom( type ) )
- {
- type = Identity.class;
- }
-
- // Plain ValueType
- Function<Object, Object> deserializationFunction = deserializers.get( type );
- if( deserializationFunction != null )
- {
- Scanner scanner = new Scanner( input, UTF_8 ).useDelimiter( "\\A" );
- if( !scanner.hasNext() )
- {
- return String.class.equals( type ) ? (T) "" : null;
- }
- String string = scanner.next();
- return (T) deserializationFunction.apply( string );
- }
- else // Array ValueType
- if( type.isArray() )
- {
- Scanner scanner = new Scanner( input, UTF_8 ).useDelimiter( "\\A" );
- if( !scanner.hasNext() )
- {
- return null;
- }
- String string = scanner.next();
- return (T) deserializeBase64Serialized( module, string );
- }
- else if( type.isEnum() )
- {
- Scanner scanner = new Scanner( input, UTF_8 ).useDelimiter( "\\A" );
- if( !scanner.hasNext() )
- {
- return String.class.equals( type ) ? (T) "" : null;
- }
- String string = scanner.next();
- return (T) Enum.valueOf( (Class) type, string );
- }
- else // Complex ValueType
- {
- InputType adaptedInput = adaptInput( module, input );
- onDeserializationStart( module, valueType, adaptedInput );
- T deserialized = doDeserialize( module, valueType, adaptedInput );
- onDeserializationEnd( module, valueType, adaptedInput );
- return deserialized;
- }
- }
-
- @SuppressWarnings( "unchecked" )
- private <T> T doDeserialize( ModuleDescriptor module, ValueType valueType, InputType input )
- throws Exception
- {
- final Class<?> type = valueType.types().findFirst().orElse( null );
- // Registered deserializers
- if( deserializers.get( type ) != null )
- {
- Object value = readPlainValue( module, input );
- if( value == null )
- {
- return null;
- }
- return (T) deserializers.get( type ).apply( value );
- }
- else if( complexDeserializers.get( type ) != null )
- {
- return (T) complexDeserializers.get( type ).deserializePull( input );
- }
- else // Explicit ValueComposite
- if( ValueCompositeType.class.isAssignableFrom( valueType.getClass() ) )
- {
- return (T) deserializeValueComposite( module, valueType, input );
- }
- else // Explicit Collections
- if( CollectionType.class.isAssignableFrom( valueType.getClass() ) )
- {
- return (T) deserializeCollection( module, (CollectionType) valueType, input );
- }
- else // Explicit Map
- if( MapType.class.isAssignableFrom( valueType.getClass() ) )
- {
- return (T) deserializeMap( module, (MapType) valueType, input );
- }
- else // Enum
- if( EnumType.class.isAssignableFrom( valueType.getClass() ) || type.isEnum() )
- {
- return (T) Enum.valueOf( (Class) type, readPlainValue( module, input ).toString() );
- }
- else // Array
- if( type.isArray() )
- {
- return (T) deserializeBase64Serialized( module, readPlainValue( module, input ).toString() );
- }
- // Guessed Deserialization
- return (T) deserializeGuessed( module, valueType, input );
- }
-
- private <T> Function<InputType, T> buildDeserializeInputFunction( ModuleDescriptor module, ValueType valueType )
- {
- return input -> {
- try
- {
- return doDeserialize( module, valueType, input );
- }
- catch( ValueSerializationException ex )
- {
- throw ex;
- }
- catch( Exception ex )
- {
- throw new ValueSerializationException( ex );
- }
- };
- }
-
- private <T> Collection<T> deserializeCollection( ModuleDescriptor module, CollectionType collectionType, InputType input )
- throws Exception
- {
- Collection<T> collection;
- Class<?> collectionMainType = collectionType.types().findFirst().orElse( null );
- if( Set.class.equals( collectionMainType ) )
- {
- collection = new LinkedHashSet<>();
- }
- else
- {
- collection = new ArrayList<>();
- }
- return readArrayInCollection( module,
- input,
- this.buildDeserializeInputFunction( module, collectionType.collectedType() ),
- collection );
- }
-
- private <K, V> Map<K, V> deserializeMap( ModuleDescriptor module, MapType mapType, InputType input )
- throws Exception
- {
- return readMapInMap( module,
- input,
- this.<K>buildDeserializeInputFunction( module, mapType.keyType() ),
- this.<V>buildDeserializeInputFunction( module, mapType.valueType() ),
- new HashMap<>() );
- }
-
- private <T> T deserializeValueComposite( ModuleDescriptor module, ValueType valueType, InputType input )
- throws Exception
- {
- InputNodeType inputNode = readObjectTree( module, input );
- if( inputNode == null )
- {
- return null;
- }
- return deserializeNodeValueComposite( module, valueType, inputNode );
- }
-
- private <T> T deserializeNodeValueComposite( ModuleDescriptor module, ValueType valueType, InputNodeType inputNode )
- throws Exception
- {
- ValueCompositeType valueCompositeType = (ValueCompositeType) valueType;
- Class<?> valueBuilderType = valueCompositeType.types().findFirst().orElse( null );
- String typeInfo = this.getObjectFieldValue(
- module,
- inputNode,
- "_type",
- this.<String>buildDeserializeInputNodeFunction( module, new ValueType( String.class ) ) );
- if( typeInfo != null )
- {
- ValueDescriptor valueDescriptor = module.valueDescriptor( typeInfo );
- if( valueDescriptor == null )
- {
- throw new ValueSerializationException( "Specified value type could not be resolved: " + typeInfo );
- }
- valueCompositeType = valueDescriptor.valueType();
- valueBuilderType = Class.forName( typeInfo );
- }
- return deserializeValueComposite( module, valueCompositeType, valueBuilderType, inputNode );
- }
-
- @SuppressWarnings( "unchecked" )
- private <T> T deserializeValueComposite( ModuleDescriptor module,
- ValueCompositeType valueCompositeType,
- Class<?> valueBuilderType,
- InputNodeType inputNode
- )
- throws Exception
- {
- final Map<String, Object> stateMap = new HashMap<>();
-
- // Properties
- valueCompositeType.properties().forEach( propertyDescriptor -> {
- String propertyName = null;
- Object value;
- try
- {
- propertyName = propertyDescriptor.qualifiedName().name();
- if( objectHasField( module, inputNode, propertyName ) )
- {
- value = getObjectFieldValue(
- module,
- inputNode,
- propertyName,
- buildDeserializeInputNodeFunction( module, propertyDescriptor.valueType() ) );
- if( propertyDescriptor.isImmutable() )
- {
- if( value instanceof Set )
- {
- value = Collections.unmodifiableSet( (Set<?>) value );
- }
- else if( value instanceof List )
- {
- value = Collections.unmodifiableList( (List<?>) value );
- }
- else if( value instanceof Map )
- {
- value = Collections.unmodifiableMap( (Map<?, ?>) value );
- }
- }
- }
- else
- {
- // Serialized object does not contain the field, try to default it
- value = propertyDescriptor.resolveInitialValue(module);
- }
- }
- catch( Exception e )
- {
- throw new ValueSerializationException( "Unable to deserialize property " + propertyDescriptor, e );
- }
- stateMap.put( propertyName, value );
- } );
-
- // Associations
- valueCompositeType.associations().forEach( association -> {
- try
- {
- String associationName = association.qualifiedName().name();
- if( objectHasField( module, inputNode, associationName ) )
- {
- Object value = getObjectFieldValue(
- module,
- inputNode,
- associationName,
- buildDeserializeInputNodeFunction( module, new ValueType( EntityReference.class ) ) );
- stateMap.put( associationName, value );
- }
- }
- catch( Exception e )
- {
- throw new ValueSerializationException( "Unable to deserialize association " + association, e );
- }
- } );
-
- // ManyAssociations
- valueCompositeType.manyAssociations().forEach( manyAssociation -> {
- try
- {
- String manyAssociationName = manyAssociation.qualifiedName().name();
- if( objectHasField( module, inputNode, manyAssociationName ) )
- {
- Object value = getObjectFieldValue(
- module,
- inputNode,
- manyAssociationName,
- buildDeserializeInputNodeFunction(
- module,
- new CollectionType(
- Collection.class,
- new ValueType( EntityReference.class ) ) ) );
- stateMap.put( manyAssociationName, value );
- }
- }
- catch( Exception e )
- {
- throw new ValueSerializationException( "Unable to deserialize manyassociation " + manyAssociation, e );
- }
- } );
-
- // NamedAssociations
- valueCompositeType.namedAssociations().forEach( namedAssociation -> {
- try
- {
- String namedAssociationName = namedAssociation.qualifiedName().name();
- if( objectHasField( module, inputNode, namedAssociationName ) )
- {
- Object value = getObjectFieldValue(
- module,
- inputNode,
- namedAssociationName,
- buildDeserializeInputNodeFunction( module, MapType.of( String.class, EntityReference.class, Serialization.Variant.object ) ) );
- stateMap.put( namedAssociationName, value );
- }
- }
- catch( Exception e )
- {
- throw new ValueSerializationException( "Unable to deserialize namedassociation " + namedAssociation, e );
- }
- } );
-
- ValueBuilder<?> valueBuilder = buildNewValueBuilderWithState( module, valueBuilderType, stateMap );
- return (T) valueBuilder.newInstance(); // Unchecked cast because the builder could use a type != T
- }
-
- private <T> Function<InputNodeType, T> buildDeserializeInputNodeFunction( ModuleDescriptor module, final ValueType valueType )
- {
- return inputNode -> {
- try
- {
- return doDeserializeInputNodeValue( module, valueType, inputNode );
- }
- catch( ValueSerializationException ex )
- {
- throw ex;
- }
- catch( Exception ex )
- {
- throw new ValueSerializationException( ex );
- }
- };
- }
-
- @SuppressWarnings( "unchecked" )
- private <T> T doDeserializeInputNodeValue( ModuleDescriptor module, ValueType valueType, InputNodeType inputNode )
- throws Exception
- {
- if( inputNode == null )
- {
- return null;
- }
- final Class<?> type = valueType.types().findFirst().orElse( null );
- // Registered deserializers
- if( deserializers.get( type ) != null )
- {
- Object value = asSimpleValue( module, inputNode );
- if( value == null )
- {
- return null;
- }
- return (T) deserializers.get( type ).apply( value );
- }
- else if( complexDeserializers.get( type ) != null )
- {
- return (T) complexDeserializers.get( type ).deserializeTree( inputNode );
- }
- else // Explicit ValueComposite
- if( ValueCompositeType.class.isAssignableFrom( valueType.getClass() ) )
- {
- return (T) deserializeNodeValueComposite( module, valueType, inputNode );
- }
- else // Explicit Collections
- if( CollectionType.class.isAssignableFrom( valueType.getClass() ) )
- {
- return (T) deserializeNodeCollection( module, (CollectionType) valueType, inputNode );
- }
- else // Explicit Map
- if( MapType.class.isAssignableFrom( valueType.getClass() ) )
- {
- MapType mapType = (MapType) valueType;
- if( mapType.variant().equals( Serialization.Variant.entry ) )
- {
- return (T) deserializeNodeEntryMap( module, (MapType) valueType, inputNode );
- }
- else
- {
- return (T) deserializeNodeObjectMap( module, (MapType) valueType, inputNode );
- }
- }
- else // Enum
- if( EnumType.class.isAssignableFrom( valueType.getClass() ) || type.isEnum() )
- {
- Object value = asSimpleValue( module, inputNode );
- if( value == null )
- {
- return null;
- }
- return (T) Enum.valueOf( (Class) type, value.toString() );
- }
- // Guessed deserialization
- return (T) deserializeNodeGuessed( module, valueType, inputNode );
- }
-
- private ValueBuilder<?> buildNewValueBuilderWithState( ModuleDescriptor module,
- Class<?> type,
- final Map<String, Object> stateMap
- )
- {
- return module.instance().newValueBuilderWithState(
- type,
- property -> stateMap.get( property.qualifiedName().name() ),
- association -> {
- Object entityRef = stateMap.get( association.qualifiedName().name() );
- if( entityRef == null )
- {
- return null;
- }
- return (EntityReference) entityRef;
- },
- manyAssociation -> {
- Object entityRefs = stateMap.get( manyAssociation.qualifiedName().name() );
- if( entityRefs == null )
- {
- return Stream.empty();
- }
- //noinspection unchecked
- return StreamSupport.stream( ( (Iterable<EntityReference>) entityRefs ).spliterator(), false );
- },
- namedAssociation -> {
- Object entityRefs = stateMap.get( namedAssociation.qualifiedName().name() );
- if( entityRefs == null )
- {
- return Stream.empty();
- }
- //noinspection unchecked
- return ( (Map<String, EntityReference>) entityRefs ).entrySet().stream();
- } );
- }
-
- @SuppressWarnings( "unchecked" )
- private <T> T deserializeGuessed( ModuleDescriptor module, ValueType valueType, InputType input )
- throws Exception
- {
- InputNodeType inputNode = readObjectTree( module, input );
- if( inputNode == null )
- {
- return null;
- }
- return deserializeNodeGuessed( module, valueType, inputNode );
- }
-
- private <T> Collection<T> deserializeNodeCollection( ModuleDescriptor module,
- CollectionType collectionType,
- InputNodeType inputNode
- )
- throws Exception
- {
- Collection<T> collection;
- Class<?> collectionMainType = collectionType.types().findFirst().orElse( null );
- if( Set.class.equals( collectionMainType ) )
- {
- collection = new LinkedHashSet<>();
- }
- else
- {
- collection = new ArrayList<>();
- }
- putArrayNodeInCollection( module,
- inputNode,
- this.buildDeserializeInputNodeFunction( module, collectionType.collectedType() ),
- collection );
- return collection;
- }
-
- private <K, V> Map<K, V> deserializeNodeEntryMap( ModuleDescriptor module, MapType mapType, InputNodeType inputNode )
- throws Exception
- {
- Map<K, V> map = new HashMap<>();
- putArrayNodeInMap( module,
- inputNode,
- this.buildDeserializeInputNodeFunction( module, mapType.keyType() ),
- this.buildDeserializeInputNodeFunction( module, mapType.valueType() ),
- map );
- return map;
- }
-
- private <V> Map<String, V> deserializeNodeObjectMap( ModuleDescriptor module, MapType mapType, InputNodeType inputNode )
- throws Exception
- {
- Map<String, V> map = new HashMap<>();
- putObjectNodeInMap( module,
- inputNode,
- this.buildDeserializeInputNodeFunction( module, mapType.valueType() ),
- map );
- return map;
- }
-
- @SuppressWarnings( "unchecked" )
- private <T> T deserializeNodeGuessed( ModuleDescriptor module, ValueType valueType, InputNodeType inputNode )
- throws Exception
- {
- if( isObjectValue( module, inputNode ) )
- {
- // Attempt ValueComposite deserialization
- ValueCompositeType valueCompositeType;
- if( objectHasField( module, inputNode, "_type" ) ) // with _type info
- {
- String typeInfo = this.getObjectFieldValue(
- module,
- inputNode,
- "_type",
- this.<String>buildDeserializeInputNodeFunction( module, new ValueType( String.class ) ) );
- ValueDescriptor valueDescriptor = module.valueDescriptor( typeInfo );
- if( valueDescriptor == null )
- {
- throw new ValueSerializationException( "Specified value type could not be resolved: " + typeInfo );
- }
- valueCompositeType = valueDescriptor.valueType();
- }
- else // without _type info
- {
- ValueDescriptor valueDescriptor = module.valueDescriptor( valueType.types()
- .findFirst()
- .get()
- .getName() );
- if( valueDescriptor == null )
- {
- throw new ValueSerializationException( "Don't know how to deserialize " + inputNode );
- }
- valueCompositeType = valueDescriptor.valueType();
- }
- Class<?> valueBuilderType = valueCompositeType.types().findFirst().orElse( null );
- return deserializeValueComposite( module, valueCompositeType, valueBuilderType, inputNode );
- }
- // Last resort : base64 java deserialization
- return (T) deserializeBase64Serialized( module, inputNode );
- }
-
- @SuppressWarnings( "unchecked" )
- private <T> T deserializeBase64Serialized( ModuleDescriptor module, InputNodeType inputNode )
- throws Exception
- {
- Object value = asSimpleValue( module, inputNode );
- if( value == null )
- {
- return null;
- }
- String base64 = value.toString();
- return deserializeBase64Serialized( module, base64 );
- }
-
- @SuppressWarnings( "unchecked" )
- private <T> T deserializeBase64Serialized( ModuleDescriptor module, String inputString )
- throws Exception
- {
- byte[] bytes = inputString.getBytes( UTF_8 );
- bytes = Base64.getDecoder().decode( bytes );
- Object result;
- try (ObjectInputStream oin = new ObjectInputStream( new ByteArrayInputStream( bytes ) ))
- {
- result = oin.readObject();
- }
- return (T) result;
- }
-
- //
- // Deserialization Extension Points
- //
-
- /**
- * Called by the adapter on deserialization start, after {@link #adaptInput(ModuleDescriptor, java.io.InputStream)}.
- *
- * @param module Module descriptor
- * @param valueType ValueType
- * @param input Input
- *
- * @throws Exception that will be wrapped in a {@link ValueSerializationException}
- */
- @SuppressWarnings( "UnusedParameters" )
- protected void onDeserializationStart( ModuleDescriptor module, ValueType valueType, InputType input )
- throws Exception
- {
- // NOOP
- }
-
- /**
- * Called by the adapter on deserialization end.
- *
- * @param module Module descriptor
- * @param valueType ValueType
- * @param input Input
- *
- * @throws Exception that will be wrapped in a {@link ValueSerializationException}
- */
- protected void onDeserializationEnd( ModuleDescriptor module, ValueType valueType, InputType input )
- throws Exception
- {
- // NOOP
- }
-
- //
- // Pull Parsing Deserialization
- //
-
- /**
- * This method is always called first, this is a chance to wrap the input type.
- *
- * @param module Module descriptor
- * @param input InputStream to adapt
- *
- * @return Adapted input
- *
- * @throws Exception that will be wrapped in a {@link ValueSerializationException}
- */
- protected abstract InputType adaptInput( ModuleDescriptor module, InputStream input )
- throws Exception;
-
- /**
- * @param module Module descriptor
- * @param input Input
- *
- * @return a Plain Value read from the input
- *
- * @throws Exception that will be wrapped in a {@link ValueSerializationException}
- */
- protected abstract Object readPlainValue( ModuleDescriptor module, InputType input )
- throws Exception;
-
- /**
- * @param module Module descriptor
- * @param input Input
- * @param deserializer Deserialization function
- * @param collection Collection
- * @param <T> Parameterized collection type
- *
- * @return The filled collection or null if no array
- *
- * @throws Exception that will be wrapped in a {@link ValueSerializationException}
- */
- protected abstract <T> Collection<T> readArrayInCollection( ModuleDescriptor module,
- InputType input,
- Function<InputType, T> deserializer,
- Collection<T> collection
- )
- throws Exception;
-
- /**
- * A Map<K,V> is serialized in an array of entries objects.
- *
- * <p>Here is an example in JSON:</p>
- * <pre>
- * [
- * { "key": "foo", "value": "bar" },
- * { "key": "cathedral", "value": "bazar" }
- * ]
- * </pre>
- * <p>And an empty Map:</p>
- * <pre>[]</pre>
- * <p>
- * This allow to use any type as keys and values while keeping the Map order at the cost of having
- * non-predictible order of key/value inside an entry object.
- * </p>
- *
- * @param module Module descriptor
- * @param input Input
- * @param keyDeserializer Map key deserialization function
- * @param valueDeserializer Map value deserialization function
- * @param map Map
- * @param <K> Parameterized map key type
- * @param <V> Parameterized map value type
- *
- * @return The filled map or null if no array
- *
- * @throws Exception that will be wrapped in a {@link ValueSerializationException}
- */
- protected abstract <K, V> Map<K, V> readMapInMap( ModuleDescriptor module,
- InputType input,
- Function<InputType, K> keyDeserializer,
- Function<InputType, V> valueDeserializer,
- Map<K, V> map
- )
- throws Exception;
-
- /**
- * @param module Module descriptor
- * @param input Input
- *
- * @return an InputNodeType or null if the value was null
- *
- * @throws Exception that will be wrapped in a {@link ValueSerializationException}
- */
- protected abstract InputNodeType readObjectTree( ModuleDescriptor module, InputType input )
- throws Exception;
-
- //
- // Tree Parsing Deserialization
- //
- protected abstract Object asSimpleValue( ModuleDescriptor module, InputNodeType inputNode )
- throws Exception;
-
- protected abstract boolean isObjectValue( ModuleDescriptor module, InputNodeType inputNode )
- throws Exception;
-
- protected abstract boolean objectHasField( ModuleDescriptor module, InputNodeType inputNode, String key )
- throws Exception;
-
- /**
- * Return null if the field do not exists.
- *
- * @param module Module descriptor
- * @param inputNode Input Node
- * @param key Object key
- * @param valueDeserializer Deserialization function
- * @param <T> Parameterized object field value type
- *
- * @return The value of the field.
- *
- * @throws Exception that will be wrapped in a {@link ValueSerializationException}
- */
- protected abstract <T> T getObjectFieldValue( ModuleDescriptor module,
- InputNodeType inputNode,
- String key,
- Function<InputNodeType, T> valueDeserializer
- )
- throws Exception;
-
- protected abstract <T> void putArrayNodeInCollection( ModuleDescriptor module,
- InputNodeType inputNode,
- Function<InputNodeType, T> deserializer,
- Collection<T> collection
- )
- throws Exception;
-
- protected abstract <K, V> void putArrayNodeInMap( ModuleDescriptor module,
- InputNodeType inputNode,
- Function<InputNodeType, K> keyDeserializer,
- Function<InputNodeType, V> valueDeserializer,
- Map<K, V> map
- )
- throws Exception;
-
- protected abstract <V> void putObjectNodeInMap( ModuleDescriptor module,
- InputNodeType inputNode,
- Function<InputNodeType, V> valueDeserializer,
- Map<String, V> map
- )
- throws Exception;
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/value/ValueSerializerAdapter.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/value/ValueSerializerAdapter.java b/core/spi/src/main/java/org/apache/polygene/spi/value/ValueSerializerAdapter.java
deleted file mode 100644
index e9313b5..0000000
--- a/core/spi/src/main/java/org/apache/polygene/spi/value/ValueSerializerAdapter.java
+++ /dev/null
@@ -1,570 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.spi.value;
-
-import java.io.ByteArrayOutputStream;
-import java.io.ObjectOutputStream;
-import java.io.OutputStream;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.time.Duration;
-import java.time.Instant;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.LocalTime;
-import java.time.OffsetDateTime;
-import java.time.Period;
-import java.time.ZonedDateTime;
-import java.util.Base64;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.function.BiFunction;
-import java.util.function.Function;
-import org.apache.polygene.api.PolygeneAPI;
-import org.apache.polygene.api.association.Association;
-import org.apache.polygene.api.association.AssociationStateHolder;
-import org.apache.polygene.api.association.ManyAssociation;
-import org.apache.polygene.api.association.NamedAssociation;
-import org.apache.polygene.api.composite.CompositeInstance;
-import org.apache.polygene.api.entity.EntityComposite;
-import org.apache.polygene.api.entity.EntityReference;
-import org.apache.polygene.api.identity.Identity;
-import org.apache.polygene.api.property.Property;
-import org.apache.polygene.api.value.ValueComposite;
-import org.apache.polygene.api.value.ValueDescriptor;
-import org.apache.polygene.api.value.ValueSerializationException;
-import org.apache.polygene.api.value.ValueSerializer;
-
-/**
- * Adapter for pull-parsing capable ValueSerializers.
- *
- * <p>
- * Among Plain values (see {@link ValueSerializer}) some are considered primitives to underlying serialization
- * mechanisms and by so handed/come without conversion to/from implementations. Primitive values can be one of:
- * </p>
- * <ul>
- * <li>String,</li>
- * <li>Character or char,</li>
- * <li>Boolean or boolean,</li>
- * <li>Integer or int,</li>
- * <li>Long or long,</li>
- * <li>Short or short,</li>
- * <li>Byte or byte,</li>
- * <li>Float or float,</li>
- * <li>Double or double.</li>
- * </ul>
- * <p>
- * Some other Plain values are transformed before being handed to implementations:
- * </p>
- * <ul>
- * <li>BigInteger and BigDecimal depends on ValueSerializer.{@link org.apache.polygene.api.value.ValueSerializer.Options};</li>
- * <li>Date as a ISO-8601 UTC String;</li>
- * <li>DateTime (JodaTime) as a ISO-8601 String with timezone offset or Z for UTC;</li>
- * <li>LocalDateTime (JodaTime) as a ISO-8601 String with no timezone offset;</li>
- * <li>LocalDate (JodaTime) as a ISO-8601 String with no time info;</li>
- * </ul>
- *
- * @param <OutputType> Implementor output type
- */
-public abstract class ValueSerializerAdapter<OutputType>
- implements ValueSerializer
-{
-
- public interface ComplexSerializer<T, OutputType>
- {
- void serialize( Options options, T object, OutputType output )
- throws Exception;
- }
-
- private static final String UTF_8 = "UTF-8";
-
- private static <TO, FROM extends TO> BiFunction<Options, FROM, TO> identitySerializer()
- {
- return ( options, from ) -> from;
- }
-
- private final Map<Class<?>, BiFunction<Options, Object, Object>> serializers = new HashMap<>( 16 );
- private final Map<Class<?>, ComplexSerializer<Object, OutputType>> complexSerializers = new HashMap<>( 2 );
-
- /**
- * Register a Plain Value type serialization Function.
- *
- * @param <T> Plain Value parametrized Type
- * @param type Plain Value Type
- * @param serializer Serialization Function
- */
- @SuppressWarnings( "unchecked" )
- protected final <T> void registerSerializer( Class<T> type, BiFunction<Options, T, Object> serializer )
- {
- serializers.put( type, (BiFunction<Options, Object, Object>) serializer );
- }
-
- /**
- * Register a Complex Value type serialization Function.
- *
- * @param <T> Complex Value parametrized Type
- * @param type Complex Value Type
- * @param serializer Serialization Function
- */
- @SuppressWarnings( "unchecked" )
- protected final <T> void registerComplexSerializer( Class<T> type, ComplexSerializer<T, OutputType> serializer )
- {
- complexSerializers.put( type, (ComplexSerializer<Object, OutputType>) serializer );
- }
-
- public ValueSerializerAdapter()
- {
- // Primitive Value types
- registerSerializer( String.class, ValueSerializerAdapter.identitySerializer() );
- registerSerializer( Character.class, ValueSerializerAdapter.identitySerializer() );
- registerSerializer( Boolean.class, ValueSerializerAdapter.identitySerializer() );
- registerSerializer( Integer.class, ValueSerializerAdapter.identitySerializer() );
- registerSerializer( Long.class, ValueSerializerAdapter.identitySerializer() );
- registerSerializer( Short.class, ValueSerializerAdapter.identitySerializer() );
- registerSerializer( Byte.class, ValueSerializerAdapter.identitySerializer() );
- registerSerializer( Float.class, ValueSerializerAdapter.identitySerializer() );
- registerSerializer( Double.class, ValueSerializerAdapter.identitySerializer() );
-
- // Number types
- registerSerializer( BigDecimal.class, ( options, bigDecimal ) -> bigDecimal.toString() );
- registerSerializer( BigInteger.class, ( options, bigInteger ) -> bigInteger.toString() );
- registerSerializer( Identity.class, ( options, identity ) -> identity.toString() );
-
- // Date types
- registerSerializer( Instant.class, ( options, date ) -> date.toString() );
- registerSerializer( Duration.class, ( options, date ) -> date.toString() );
- registerSerializer( Period.class, ( options, date ) -> date.toString() );
- registerSerializer( ZonedDateTime.class, ( options, date ) -> date.toString() );
- registerSerializer( OffsetDateTime.class, ( options, date ) -> date.toString() );
- registerSerializer( LocalDateTime.class, ( options, date ) -> date.toString() );
- registerSerializer( LocalDate.class, ( options, date ) -> date.toString() );
- registerSerializer( LocalTime.class, ( options, date ) -> date.toString() );
-
- // Other supported types
- registerSerializer( EntityReference.class, ( options, ref ) -> ref.toString() );
- }
-
- @Override
- public final <T> Function<T, String> serialize()
- {
- return this::serialize;
- }
-
- @Override
- public final <T> Function<T, String> serialize( final Options options )
- {
- return object -> serialize( options, object );
- }
-
- @Override
- public final String serialize( Object object )
- throws ValueSerializationException
- {
- return serialize( new Options(), object );
- }
-
- @Override
- public final String serialize( Options options, Object object )
- throws ValueSerializationException
- {
- try
- {
- ByteArrayOutputStream output = new ByteArrayOutputStream();
- serializeRoot( options, object, output );
- return output.toString( UTF_8 );
- }
- catch( ValueSerializationException ex )
- {
- throw ex;
- }
- catch( Exception ex )
- {
- throw new ValueSerializationException( "Could not serialize value", ex );
- }
- }
-
- @Override
- public final void serialize( Object object, OutputStream output )
- throws ValueSerializationException
- {
- serialize( new Options(), object, output );
- }
-
- @Override
- public final void serialize( Options options, Object object, OutputStream output )
- throws ValueSerializationException
- {
- try
- {
- serializeRoot( options, object, output );
- }
- catch( ValueSerializationException ex )
- {
- throw ex;
- }
- catch( Exception ex )
- {
- throw new ValueSerializationException( "Could not serialize value", ex );
- }
- }
-
- private void serializeRoot( Options options, Object object, OutputStream output )
- throws Exception
- {
- if( object != null )
- {
- if( serializers.get( object.getClass() ) != null )
- {
- // Plain Value
- Object serialized = serializers.get( object.getClass() ).apply( options, object );
- output.write( serialized.toString().getBytes( UTF_8 ) );
- }
- else if( object instanceof Identity )
- {
- Object serialized = serializers.get( Identity.class ).apply( options, object );
- output.write( serialized.toString().getBytes( UTF_8 ) );
- }
- else if( object.getClass().isEnum() )
- {
- // Enum Value
- output.write( object.toString().getBytes( UTF_8 ) );
- }
- else if( object.getClass().isArray() )
- {
- // Array Value
- output.write( serializeBase64Serializable( object ).getBytes( UTF_8 ) );
- }
- else
- {
- // Complex Value
- OutputType adaptedOutput = adaptOutput( output );
- onSerializationStart( object, adaptedOutput );
- doSerialize( options, object, adaptedOutput, true );
- onSerializationEnd( object, adaptedOutput );
- }
- }
- }
-
- private void doSerialize( Options options, Object object, OutputType output, boolean rootPass )
- throws Exception
- {
- // Null
- if( object == null )
- {
- onValue( output, null );
- }
- else // Registered serializer
- if( serializers.get( object.getClass() ) != null )
- {
- onValue( output, serializers.get( object.getClass() ).apply( options, object ) );
- }
- else if( complexSerializers.get( object.getClass() ) != null )
- {
- complexSerializers.get( object.getClass() ).serialize( options, object, output );
- }
- else // ValueComposite
- if( Identity.class.isAssignableFrom( object.getClass() ) )
- {
- serializeIdentity( object, output );
- }
- else if( ValueComposite.class.isAssignableFrom( object.getClass() ) )
- {
- serializeValueComposite( options, object, output, rootPass );
- }
- else // EntityComposite
- if( EntityComposite.class.isAssignableFrom( object.getClass() ) )
- {
- serializeEntityComposite( object, output );
- }
- else // Collection - Iterable
- if( Iterable.class.isAssignableFrom( object.getClass() ) )
- {
- serializeIterable( options, object, output );
- }
- else // Array - QUID Remove this and use java serialization for arrays?
- if( object.getClass().isArray() )
- {
- serializeBase64Serializable( object, output );
- }
- else // Map
- if( Map.class.isAssignableFrom( object.getClass() ) )
- {
- serializeMap( options, object, output );
- }
- else // Enum
- if( object.getClass().isEnum() )
- {
- onValue( output, object.toString() );
- }
- else // Fallback to Base64 encoded Java Serialization
- {
- serializeBase64Serializable( object, output );
- }
- }
-
- private void serializeIdentity( Object object, OutputType output )
- throws Exception
- {
- onValue( output, object.toString() );
- }
-
- private void serializeValueComposite( Options options, Object object, OutputType output, boolean rootPass )
- throws Exception
- {
- CompositeInstance valueInstance = PolygeneAPI.FUNCTION_COMPOSITE_INSTANCE_OF.apply( (ValueComposite) object );
- ValueDescriptor descriptor = (ValueDescriptor) valueInstance.descriptor();
- AssociationStateHolder state = (AssociationStateHolder) valueInstance.state();
-
- onObjectStart( output );
-
- //noinspection ConstantConditions
- if( options.getBoolean( Options.INCLUDE_TYPE_INFO ) && !rootPass )
- {
- onFieldStart( output, "_type" );
- onValueStart( output );
- onValue( output, descriptor.valueType().types().findFirst().get().getName());
- onValueEnd( output );
- onFieldEnd( output );
- }
-
- descriptor.valueType().properties().forEach( persistentProperty -> {
- Property<?> property = state.propertyFor( persistentProperty.accessor() );
- try
- {
- onFieldStart( output, persistentProperty.qualifiedName().name() );
- onValueStart( output );
- doSerialize( options, property.get(), output, false );
- onValueEnd( output );
- onFieldEnd( output );
- }
- catch( Exception e )
- {
- throw new ValueSerializationException( "Unable to serialize property " + persistentProperty, e );
- }
- } );
- descriptor.valueType().associations().forEach(associationDescriptor -> {
- Association<?> association = state.associationFor( associationDescriptor.accessor() );
- try
- {
- onFieldStart( output, associationDescriptor.qualifiedName().name() );
- onValueStart( output );
- EntityReference ref = association.reference();
- if( ref == null )
- {
- onValue( output, null );
- }
- else
- {
- onValue( output, ref.identity().toString() );
- }
- onValueEnd( output );
- onFieldEnd( output );
- }
- catch( Exception e )
- {
- throw new ValueSerializationException( "Unable to serialize association " + associationDescriptor, e );
- }
- } );
- descriptor.valueType().manyAssociations().forEach( associationDescriptor -> {
- ManyAssociation<?> manyAssociation = state.manyAssociationFor( associationDescriptor.accessor() );
- try
- {
- onFieldStart( output, associationDescriptor.qualifiedName().name() );
- onValueStart( output );
- onArrayStart( output );
- for( Iterator<EntityReference> it = manyAssociation.references().iterator(); it.hasNext(); )
- {
- onValueStart( output );
- onValue( output, it.next().identity().toString() );
- onValueEnd( output );
- }
- onArrayEnd( output );
- onValueEnd( output );
- onFieldEnd( output );
- }
- catch( Exception e )
- {
- throw new ValueSerializationException( "Unable to serialize manyassociation " + associationDescriptor, e );
- }
- });
- descriptor.valueType().namedAssociations().forEach( associationDescriptor -> {
- NamedAssociation<?> namedAssociation = state.namedAssociationFor( associationDescriptor.accessor() );
- try
- {
- onFieldStart( output, associationDescriptor.qualifiedName().name() );
- onValueStart( output );
- onObjectStart( output );
- for( String name : namedAssociation )
- {
- onFieldStart( output, name );
- onValueStart( output );
- EntityReference ref = namedAssociation.referenceOf( name );
- onValue( output, ref.identity().toString() );
- onValueEnd( output );
- onFieldEnd( output );
- }
- onObjectEnd( output );
- onValueEnd( output );
- onFieldEnd( output );
- }
- catch( Exception e )
- {
- throw new ValueSerializationException( "Unable to serialize namedassociation " + associationDescriptor, e );
- }
- } );
-
- onObjectEnd( output );
- }
-
- private void serializeEntityComposite( Object object, OutputType output )
- throws Exception
- {
- onValue( output, EntityReference.entityReferenceFor( object ) );
- }
-
- private void serializeIterable( Options options, Object object, OutputType output )
- throws Exception
- {
- @SuppressWarnings( "unchecked" )
- Iterable<Object> collection = (Iterable<Object>) object;
- onArrayStart( output );
- for( Object item : collection )
- {
- onValueStart( output );
- doSerialize( options, item, output, false );
- onValueEnd( output );
- }
- onArrayEnd( output );
- }
-
- private void serializeMap( Options options, Object object, OutputType output )
- throws Exception
- {
- @SuppressWarnings( "unchecked" )
- Map<Object, Object> map = (Map<Object, Object>) object;
- //noinspection ConstantConditions
- if( options.getBoolean( Options.MAP_ENTRIES_AS_OBJECTS ) )
- {
- onObjectStart( output );
- for( Map.Entry<Object, Object> entry : map.entrySet() )
- {
- onFieldStart( output, entry.getKey().toString() );
- onValueStart( output );
- doSerialize( options, entry.getValue(), output, false );
- onValueEnd( output );
- onFieldEnd( output );
- }
- onObjectEnd( output );
- }
- else
- {
- onArrayStart( output );
- for( Map.Entry<Object, Object> entry : map.entrySet() )
- {
- onObjectStart( output );
-
- onFieldStart( output, "key" );
- onValueStart( output );
- onValue( output, entry.getKey().toString() );
- onValueEnd( output );
- onFieldEnd( output );
-
- onFieldStart( output, "value" );
- onValueStart( output );
- doSerialize( options, entry.getValue(), output, false );
- onValueEnd( output );
- onFieldEnd( output );
-
- onObjectEnd( output );
- }
- onArrayEnd( output );
- }
- }
-
- private void serializeBase64Serializable( Object object, OutputType output )
- throws Exception
- {
- onValue( output, serializeBase64Serializable( object ) );
- }
-
- private String serializeBase64Serializable( Object object )
- throws Exception
- {
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
- try (ObjectOutputStream out = new ObjectOutputStream( bout ))
- {
- out.writeUnshared( object );
- }
- byte[] bytes = Base64.getEncoder().encode( bout.toByteArray() );
- return new String( bytes, UTF_8 );
- }
-
- protected abstract OutputType adaptOutput( OutputStream output )
- throws Exception;
-
- protected void onSerializationStart( Object object, OutputType output )
- throws Exception
- {
- // NOOP
- }
-
- protected void onSerializationEnd( Object object, OutputType output )
- throws Exception
- {
- // NOOP
- }
-
- protected abstract void onArrayStart( OutputType output )
- throws Exception;
-
- protected abstract void onArrayEnd( OutputType output )
- throws Exception;
-
- protected abstract void onObjectStart( OutputType output )
- throws Exception;
-
- protected abstract void onObjectEnd( OutputType output )
- throws Exception;
-
- protected abstract void onFieldStart( OutputType output, String fieldName )
- throws Exception;
-
- protected void onFieldEnd( OutputType output )
- throws Exception
- {
- // NOOP
- }
-
- protected void onValueStart( OutputType output )
- throws Exception
- {
- // NOOP
- }
-
- protected abstract void onValue( OutputType output, Object value )
- throws Exception;
-
- protected void onValueEnd( OutputType output )
- throws Exception
- {
- // NOOP
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/spi/value/package.html
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/value/package.html b/core/spi/src/main/java/org/apache/polygene/spi/value/package.html
deleted file mode 100644
index 936e083..0000000
--- a/core/spi/src/main/java/org/apache/polygene/spi/value/package.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one
- ~ or more contributor license agreements. See the NOTICE file
- ~ distributed with this work for additional information
- ~ regarding copyright ownership. The ASF licenses this file
- ~ to you under the Apache License, Version 2.0 (the
- ~ "License"); you may not use this file except in compliance
- ~ with the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- ~
- ~
- -->
-<html>
- <body>
- <h2>Value SPI.</h2>
- </body>
-</html>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueDeserializer.java b/core/spi/src/main/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueDeserializer.java
deleted file mode 100644
index c543b3c..0000000
--- a/core/spi/src/main/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueDeserializer.java
+++ /dev/null
@@ -1,485 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.orgjson;
-
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.function.Function;
-import org.apache.polygene.api.structure.ModuleDescriptor;
-import org.apache.polygene.api.value.ValueSerializationException;
-import org.apache.polygene.spi.value.ValueDeserializerAdapter;
-import org.json.JSONArray;
-import org.json.JSONObject;
-import org.json.JSONTokener;
-
-/**
- * ValueDeserializer reading Values from JSON documents using org.json.
- */
-public class OrgJsonValueDeserializer
- extends ValueDeserializerAdapter<JSONTokener, Object>
-{
-
- @Override
- protected JSONTokener adaptInput( ModuleDescriptor module, InputStream input )
- throws Exception
- {
- return new JSONTokener( new InputStreamReader( input, "UTF-8" ) );
- }
-
- @Override
- protected Object readPlainValue( ModuleDescriptor module, JSONTokener input )
- throws Exception
- {
- Object nextValue = input.nextValue();
- if( JSONObject.NULL.equals( nextValue ) )
- {
- return null;
- }
- else // Object or Array
- if( JSONObject.class.isAssignableFrom( nextValue.getClass() )
- || JSONArray.class.isAssignableFrom( nextValue.getClass() ) )
- {
- throw new ValueSerializationException( "Asked for a Value but found an Object or an Array." );
- }
- return nextValue;
- }
-
- @Override
- protected <T> Collection<T> readArrayInCollection( ModuleDescriptor module,
- JSONTokener input,
- Function<JSONTokener, T> deserializer,
- Collection<T> collection
- )
- throws Exception
- {
- char c = input.nextClean();
- char q;
- if( c == 'n' ) // null?
- {
- /*
- * Handle unquoted text. This could be the values true, false, or
- * null, or it can be a number. An implementation (such as this one)
- * is allowed to also accept non-standard forms.
- *
- * Accumulate characters until we reach the end of the text or a
- * formatting character.
- */
- StringBuilder sb = new StringBuilder();
- sb.setLength( 0 );
- while( c >= ' ' && ",:]}/\\\"[{;=#".indexOf( c ) < 0 )
- {
- sb.append( c );
- c = input.next();
- }
- input.back();
- String s = sb.toString().trim();
- if( !"null".equals( s ) )
- {
- input.syntaxError( "Unknown value: '" + s + "'" );
- }
- return null;
- }
- else if( c == '[' )
- {
- q = ']';
- }
- else
- {
- throw input.syntaxError( "A JSONArray text must start with '['" );
- }
- if( input.nextClean() == ']' )
- {
- return collection;
- }
- input.back();
- for(; ; )
- {
- if( input.nextClean() == ',' )
- {
- input.back();
- collection.add( null );
- }
- else
- {
- input.back();
- collection.add( deserializer.apply( input ) );
- }
- c = input.nextClean();
- switch( c )
- {
- case ';':
- case ',':
- if( input.nextClean() == ']' )
- {
- return collection;
- }
- input.back();
- break;
- case ']':
- case ')':
- if( q != c )
- {
- throw input.syntaxError( "Expected a '" + Character.valueOf( q ) + "'" );
- }
- return collection;
- default:
- throw input.syntaxError( "Expected a ',' or ']'" );
- }
- }
- }
-
- @Override
- protected <K, V> Map<K, V> readMapInMap( ModuleDescriptor module,
- JSONTokener input,
- Function<JSONTokener, K> keyDeserializer,
- Function<JSONTokener, V> valueDeserializer,
- Map<K, V> map
- )
- throws Exception
- {
- char c = input.nextClean();
- char q;
- if( c == 'n' ) // null?
- {
- /*
- * Handle unquoted text. This could be the values true, false, or
- * null, or it can be a number. An implementation (such as this one)
- * is allowed to also accept non-standard forms.
- *
- * Accumulate characters until we reach the end of the text or a
- * formatting character.
- */
- StringBuilder sb = new StringBuilder();
- sb.setLength( 0 );
- while( c >= ' ' && ",:]}/\\\"[{;=#".indexOf( c ) < 0 )
- {
- sb.append( c );
- c = input.next();
- }
- input.back();
- String s = sb.toString().trim();
- if( !"null".equals( s ) )
- {
- input.syntaxError( "Unknown value: '" + s + "'" );
- }
- return null;
- }
- else if( c == '[' )
- {
- q = ']';
- }
- else
- {
- throw input.syntaxError( "A JSONArray text must start with '['" );
- }
- if( input.nextClean() == ']' )
- {
- return map;
- }
- input.back();
-
- for(; ; )
- {
- if( input.nextClean() == ',' )
- {
- input.back();
- }
- else
- {
- input.back();
- // Map entry!
- if( input.nextClean() != '{' )
- {
- throw input.syntaxError( "A JSONObject text must begin with '{'" );
- }
-
- String objectKey;
- K key = null;
- V value = null;
-
- boolean breakIteration = false;
- while( !breakIteration )
- {
- c = input.nextClean();
- switch( c )
- {
- case 0:
- throw input.syntaxError( "A JSONObject text must end with '}'" );
- case '}':
- breakIteration = true;
- continue;
- default:
- input.back();
- objectKey = input.nextValue().toString();
- }
-
- /*
- * The key is followed by ':'. We will also tolerate '=' or '=>'.
- */
- c = input.nextClean();
- if( c == '=' )
- {
- if( input.next() != '>' )
- {
- input.back();
- }
- }
- else if( c != ':' )
- {
- throw input.syntaxError( "Expected a ':' after a key" );
- }
-
- if( "key".equals( objectKey ) )
- {
- key = keyDeserializer.apply( input );
- }
- else if( "value".equals( objectKey ) )
- {
- value = valueDeserializer.apply( input );
- }
- else
- {
- input.nextValue();
- }
-
- /*
- * Pairs are separated by ','. We will also tolerate ';'.
- */
- switch( input.nextClean() )
- {
- case ';':
- case ',':
- if( input.nextClean() == '}' )
- {
- breakIteration = true;
- continue;
- }
- input.back();
- continue;
- case '}':
- breakIteration = true;
- continue;
- default:
- throw input.syntaxError( "Expected a ',' or '}'" );
- }
- }
- if( key != null )
- {
- map.put( key, value );
- }
- }
- c = input.nextClean();
- switch( c )
- {
- case ';':
- case ',':
- if( input.nextClean() == ']' )
- {
- return map;
- }
- input.back();
- break;
- case ']':
- case ')':
- if( q != c )
- {
- throw input.syntaxError( "Expected a '" + Character.valueOf( q ) + "'" );
- }
- return map;
- default:
- throw input.syntaxError( "Expected a ',' or ']'" );
- }
- }
- }
-
- //
- // Deserialization - Tree parsing
- //
- @Override
- protected JSONObject readObjectTree( ModuleDescriptor module,
- JSONTokener input
- )
- throws Exception
- {
- Object objectTree = input.nextValue();
- if( JSONObject.NULL.equals( objectTree ) )
- {
- return null;
- }
- return (JSONObject) objectTree;
- }
-
- @Override
- protected Object asSimpleValue( ModuleDescriptor module, Object inputNode )
- throws Exception
- {
- if( JSONObject.NULL.equals( inputNode ) )
- {
- return null;
- }
- if( inputNode instanceof JSONObject || inputNode instanceof JSONArray )
- {
- throw new ValueSerializationException( "Expected a simple value but got " + inputNode );
- }
- return inputNode;
- }
-
- @Override
- protected boolean isObjectValue( ModuleDescriptor module, Object inputNode )
- throws Exception
- {
- if( JSONObject.NULL.equals( inputNode ) )
- {
- return false;
- }
- return inputNode instanceof JSONObject;
- }
-
- @Override
- protected boolean objectHasField( ModuleDescriptor module, Object inputNode, String key )
- throws Exception
- {
- if( JSONObject.NULL.equals( inputNode ) )
- {
- return false;
- }
- if( !( inputNode instanceof JSONObject ) )
- {
- throw new ValueSerializationException( "Expected an object but got " + inputNode );
- }
- JSONObject json = (JSONObject) inputNode;
- return json.has( key );
- }
-
- @Override
- protected <T> T getObjectFieldValue( ModuleDescriptor module,
- Object inputNode,
- String key,
- Function<Object, T> valueDeserializer
- )
- throws Exception
- {
- JSONObject json = (JSONObject) inputNode;
- Object valueNode = json.opt( key );
- if( JSONObject.NULL.equals( valueNode ) )
- {
- return null;
- }
- T value = valueDeserializer.apply( valueNode );
- return value;
- }
-
- @Override
- protected <T> void putArrayNodeInCollection( ModuleDescriptor module,
- Object inputNode,
- Function<Object, T> deserializer,
- Collection<T> collection
- )
- throws Exception
- {
- if( JSONObject.NULL.equals( inputNode ) )
- {
- return;
- }
- if( !( inputNode instanceof JSONArray ) )
- {
- throw new ValueSerializationException( "Expected an array but got " + inputNode );
- }
- JSONArray array = (JSONArray) inputNode;
- for( int idx = 0; idx < array.length(); idx++ )
- {
- Object item = array.get( idx );
- T value = deserializer.apply( item );
- collection.add( value );
- }
- }
-
- @Override
- protected <K, V> void putArrayNodeInMap( ModuleDescriptor module,
- Object inputNode,
- Function<Object, K> keyDeserializer,
- Function<Object, V> valueDeserializer,
- Map<K, V> map
- )
- throws Exception
- {
- if( JSONObject.NULL.equals( inputNode ) )
- {
- return;
- }
- if( !( inputNode instanceof JSONArray ) )
- {
- throw new ValueSerializationException( "Expected an array but got " + inputNode );
- }
- JSONArray array = (JSONArray) inputNode;
- for( int idx = 0; idx < array.length(); idx++ )
- {
- Object item = array.get( idx );
- if( !( item instanceof JSONObject ) )
- {
- throw new ValueSerializationException( "Expected an object but got " + inputNode );
- }
- JSONObject object = (JSONObject) item;
- Object keyNode = object.get( "key" );
- Object valueNode = object.get( "value" );
- K key = keyDeserializer.apply( keyNode );
- V value = valueDeserializer.apply( valueNode );
- if( key != null )
- {
- map.put( key, value );
- }
- }
- }
-
- @Override
- protected <V> void putObjectNodeInMap( ModuleDescriptor module,
- Object inputNode,
- Function<Object, V> valueDeserializer,
- Map<String, V> map
- )
- throws Exception
- {
- if( JSONObject.NULL.equals( inputNode ) )
- {
- return;
- }
- if( !( inputNode instanceof JSONObject ) )
- {
- throw new ValueSerializationException( "Expected an object but got " + inputNode );
- }
- JSONObject object = (JSONObject) inputNode;
-
- @SuppressWarnings( "unchecked" )
- Iterator<String> it = object.keys();
- while( it.hasNext() )
- {
- String key = it.next();
- Object item = object.get( key );
- V valueValue = valueDeserializer.apply( item );
- if( key != null )
- {
- map.put( key, valueValue );
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/core/spi/src/main/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueSerializationService.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueSerializationService.java b/core/spi/src/main/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueSerializationService.java
deleted file mode 100644
index 5bf3544..0000000
--- a/core/spi/src/main/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueSerializationService.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.orgjson;
-
-import org.apache.polygene.api.mixin.Mixins;
-import org.apache.polygene.api.value.ValueSerialization;
-
-/**
- * ValueSerialization Service producing and consuming JSON documents using org.json.
- */
-@Mixins( { OrgJsonValueSerializer.class, OrgJsonValueDeserializer.class } )
-public interface OrgJsonValueSerializationService
- extends ValueSerialization
-{
-}
[25/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java
new file mode 100644
index 0000000..95c9c5e
--- /dev/null
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreMixin.java
@@ -0,0 +1,237 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.entitystore.sql;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Stream;
+import javax.json.Json;
+import javax.sql.DataSource;
+import org.apache.polygene.api.common.Optional;
+import org.apache.polygene.api.configuration.Configuration;
+import org.apache.polygene.api.entity.EntityDescriptor;
+import org.apache.polygene.api.entity.EntityReference;
+import org.apache.polygene.api.injection.scope.Service;
+import org.apache.polygene.api.injection.scope.This;
+import org.apache.polygene.api.injection.scope.Uses;
+import org.apache.polygene.api.service.ServiceActivation;
+import org.apache.polygene.api.service.ServiceDescriptor;
+import org.apache.polygene.library.sql.common.SQLConfiguration;
+import org.apache.polygene.spi.entitystore.EntityNotFoundException;
+import org.apache.polygene.spi.entitystore.EntityStoreException;
+import org.apache.polygene.spi.entitystore.helpers.JSONKeys;
+import org.apache.polygene.spi.entitystore.helpers.MapEntityStore;
+import org.jooq.DSLContext;
+import org.jooq.Field;
+import org.jooq.Query;
+import org.jooq.Record;
+import org.jooq.SQLDialect;
+import org.jooq.Schema;
+import org.jooq.Table;
+import org.jooq.conf.Settings;
+import org.jooq.impl.DSL;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+// TODO Implement optimistic locking! Maybe as a SPI helper
+public class SQLMapEntityStoreMixin
+ implements ServiceActivation, MapEntityStore
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger( SQLMapEntityStoreService.class );
+
+ @Service
+ private DataSource dataSource;
+
+ @Uses
+ private ServiceDescriptor descriptor;
+
+ @This
+ @Optional
+ private Configuration<SQLConfiguration> configuration;
+
+ private Schema schema;
+ private Table<Record> table;
+ private Field<String> identityColumn;
+ private Field<String> versionColumn;
+ private Field<String> stateColumn;
+ private DSLContext dsl;
+
+ @Override
+ public void activateService() throws Exception
+ {
+ SQLDialect dialect = descriptor.metaInfo( SQLDialect.class );
+ Settings settings = descriptor.metaInfo( Settings.class );
+ SQLMapEntityStoreMapping mapping = descriptor.metaInfo( SQLMapEntityStoreMapping.class );
+ String schemaName = getConfiguredSchemaName( mapping.defaultSchemaName() );
+ if( schemaName == null )
+ {
+ throw new EntityStoreException( "Schema name must not be null." );
+ }
+ schema = DSL.schema( DSL.name( schemaName.toUpperCase() ) );
+ table = DSL.table(
+ dialect.equals( SQLDialect.SQLITE )
+ ? DSL.name( mapping.tableName() )
+ : DSL.name( schema.getName(), mapping.tableName() )
+ );
+ identityColumn = DSL.field( mapping.identityColumnName(), String.class );
+ versionColumn = DSL.field( mapping.versionColumnName(), String.class );
+ stateColumn = DSL.field( mapping.stateColumnName(), String.class );
+
+ dsl = DSL.using( dataSource, dialect, settings );
+
+ if( !dialect.equals( SQLDialect.SQLITE )
+ && dsl.meta().getSchemas().stream().noneMatch( s -> schema.getName().equals( s.getName() ) ) )
+ {
+ dsl.createSchema( schema ).execute();
+ }
+
+ if( dsl.meta().getTables().stream().noneMatch( t -> table.getName().equals( t.getName() ) ) )
+ {
+ dsl.createTable( table )
+ .column( identityColumn, mapping.identityDataType().nullable( false ) )
+ .column( versionColumn, mapping.versionDataType().nullable( false ) )
+ .column( stateColumn, mapping.stateDataType().nullable( false ) )
+ .constraint( DSL.constraint( "ENTITY_IDENTITY_CONSTRAINT" ).primaryKey( identityColumn ) )
+ .execute();
+ }
+ }
+
+ @Override
+ public void passivateService() throws Exception
+ {
+ dsl = null;
+ schema = null;
+ table = null;
+ identityColumn = null;
+ versionColumn = null;
+ stateColumn = null;
+ }
+
+ @Override
+ public Reader get( EntityReference entityReference )
+ {
+ String state = dsl.select( stateColumn )
+ .from( table )
+ .where( identityColumn.equal( entityReference.identity().toString() ) )
+ .fetchOptional( stateColumn )
+ .orElseThrow( () -> new EntityNotFoundException( entityReference ) );
+ return new StringReader( state );
+ }
+
+ @Override
+ public Stream<Reader> entityStates()
+ {
+ return dsl.select( stateColumn )
+ .from( table )
+ .fetch( stateColumn )
+ .stream()
+ .map( StringReader::new );
+ }
+
+ @Override
+ public void applyChanges( MapChanges changes ) throws Exception
+ {
+ List<Query> operations = new ArrayList<>();
+ changes.visitMap( new MapChanger()
+ {
+ @Override
+ public Writer newEntity( EntityReference ref, EntityDescriptor entityDescriptor )
+ {
+ return new StringWriter( 1000 )
+ {
+ @Override
+ public void close() throws IOException
+ {
+ super.close();
+ String state = toString();
+ String version = Json.createReader( new StringReader( state ) ).readObject()
+ .getString( JSONKeys.VERSION );
+ operations.add(
+ dsl.insertInto( table )
+ .columns( identityColumn, versionColumn, stateColumn )
+ .values( ref.identity().toString(), version, state )
+ );
+ }
+ };
+ }
+
+ @Override
+ public Writer updateEntity( MapChange mapChange )
+ {
+ return new StringWriter( 1000 )
+ {
+ @Override
+ public void close() throws IOException
+ {
+ super.close();
+ String state = toString();
+ operations.add(
+ dsl.update( table )
+ .set( versionColumn, mapChange.newVersion() )
+ .set( stateColumn, state )
+ .where( identityColumn.equal( mapChange.reference().identity().toString() ) )
+ .and( versionColumn.equal( mapChange.previousVersion() ) )
+ );
+ }
+ };
+ }
+
+ @Override
+ public void removeEntity( EntityReference ref, EntityDescriptor entityDescriptor )
+ {
+ operations.add(
+ dsl.deleteFrom( table )
+ .where( identityColumn.equal( ref.identity().toString() ) )
+ );
+ }
+ } );
+ dsl.batch( operations ).execute();
+ }
+
+
+ /**
+ * Configuration is optional at both assembly and runtime.
+ */
+ protected String getConfiguredSchemaName( String defaultSchemaName )
+ {
+ if( configuration == null )
+ {
+ Objects.requireNonNull( defaultSchemaName, "default schema name" );
+ LOGGER.debug( "No configuration, will use default schema name: '{}'", defaultSchemaName );
+ return defaultSchemaName;
+ }
+ String result = configuration.get().schemaName().get();
+ if( result == null )
+ {
+ Objects.requireNonNull( defaultSchemaName, "default schema name" );
+ result = defaultSchemaName;
+ LOGGER.debug( "No database schema name in configuration, will use default: '{}'", defaultSchemaName );
+ }
+ else
+ {
+ LOGGER.debug( "Will use configured database schema name: '{}'", result );
+ }
+ return result;
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreService.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreService.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreService.java
new file mode 100644
index 0000000..0ff1e59
--- /dev/null
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/SQLMapEntityStoreService.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.entitystore.sql;
+
+import org.apache.polygene.api.concern.Concerns;
+import org.apache.polygene.api.configuration.Configuration;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.service.ServiceActivation;
+import org.apache.polygene.api.service.ServiceComposite;
+import org.apache.polygene.spi.entitystore.ConcurrentModificationCheckConcern;
+import org.apache.polygene.spi.entitystore.EntityStateVersions;
+import org.apache.polygene.spi.entitystore.EntityStore;
+import org.apache.polygene.spi.entitystore.StateChangeNotificationConcern;
+import org.apache.polygene.spi.entitystore.helpers.JSONMapEntityStoreActivation;
+import org.apache.polygene.spi.entitystore.helpers.JSONMapEntityStoreMixin;
+
+/**
+ * SQL EntityStore service.
+ */
+@Concerns( { StateChangeNotificationConcern.class, ConcurrentModificationCheckConcern.class } )
+@Mixins( { JSONMapEntityStoreMixin.class, SQLMapEntityStoreMixin.class } )
+public interface SQLMapEntityStoreService
+ extends ServiceActivation,
+ JSONMapEntityStoreActivation,
+ EntityStore,
+ EntityStateVersions,
+ ServiceComposite,
+ Configuration
+{
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/AbstractSQLEntityStoreAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/AbstractSQLEntityStoreAssembler.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/AbstractSQLEntityStoreAssembler.java
deleted file mode 100644
index 1713300..0000000
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/AbstractSQLEntityStoreAssembler.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.entitystore.sql.assembly;
-
-import java.io.IOException;
-import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.api.identity.Identity;
-import org.apache.polygene.api.identity.StringIdentity;
-import org.apache.polygene.bootstrap.Assemblers;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.entitystore.sql.SQLEntityStoreService;
-import org.apache.polygene.entitystore.sql.internal.DatabaseSQLService.DatabaseSQLServiceComposite;
-import org.apache.polygene.entitystore.sql.internal.DatabaseSQLServiceCoreMixin;
-import org.apache.polygene.entitystore.sql.internal.DatabaseSQLServiceSpi;
-import org.apache.polygene.entitystore.sql.internal.DatabaseSQLServiceStatementsMixin;
-import org.apache.polygene.entitystore.sql.internal.DatabaseSQLStringsBuilder;
-import org.apache.polygene.library.sql.common.SQLConfiguration;
-import org.sql.generation.api.vendor.SQLVendor;
-import org.sql.generation.api.vendor.SQLVendorProvider;
-
-/**
- * Base SQL EntityStore assembly.
- */
-@SuppressWarnings( "unchecked" )
-abstract class AbstractSQLEntityStoreAssembler<AssemblerType>
- extends Assemblers.VisibilityIdentityConfig<AssemblerType>
-{
-
- public static final Identity DEFAULT_ENTITYSTORE_IDENTITY = new StringIdentity( "entitystore-sql" );
-
- protected SQLVendor getSQLVendor()
- throws IOException
- {
- return SQLVendorProvider.createVendor( SQLVendor.class );
- }
-
- protected Class<?> getDatabaseStringBuilderMixin()
- {
- return DatabaseSQLStringsBuilder.CommonMixin.class;
- }
-
- protected abstract Class<?> getDatabaseSQLServiceSpecializationMixin();
-
- @Override
- public final void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- try
- {
- SQLVendor sqlVendor = this.getSQLVendor();
- if( sqlVendor == null )
- {
- throw new AssemblyException( "SQL Vendor could not be determined." );
- }
- module.services( DatabaseSQLServiceComposite.class )
- .withMixins( DatabaseSQLServiceCoreMixin.class,
- DatabaseSQLServiceSpi.CommonMixin.class,
- getDatabaseStringBuilderMixin(),
- DatabaseSQLServiceStatementsMixin.class,
- getDatabaseSQLServiceSpecializationMixin() )
- .identifiedBy( ( hasIdentity() ? identity().toString() : DEFAULT_ENTITYSTORE_IDENTITY ).toString() ).
- visibleIn( Visibility.module ).
- setMetaInfo( sqlVendor );
- }
- catch( IOException ioe )
- {
- throw new AssemblyException( ioe );
- }
- module.services( SQLEntityStoreService.class ).visibleIn( visibility() );
- if( hasConfig() )
- {
- configModule().entities( SQLConfiguration.class ).visibleIn( configVisibility() );
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/AbstractSQLMapEntityStoreAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/AbstractSQLMapEntityStoreAssembler.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/AbstractSQLMapEntityStoreAssembler.java
new file mode 100644
index 0000000..4e205d1
--- /dev/null
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/AbstractSQLMapEntityStoreAssembler.java
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.entitystore.sql.assembly;
+
+import org.apache.polygene.api.identity.Identity;
+import org.apache.polygene.api.identity.StringIdentity;
+import org.apache.polygene.bootstrap.Assemblers;
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.entitystore.sql.SQLMapEntityStoreMapping;
+import org.apache.polygene.entitystore.sql.SQLMapEntityStoreService;
+import org.apache.polygene.library.sql.common.SQLConfiguration;
+import org.jooq.SQLDialect;
+import org.jooq.conf.Settings;
+
+/**
+ * Base SQL EntityStore assembly.
+ */
+public abstract class AbstractSQLMapEntityStoreAssembler<AssemblerType>
+ extends Assemblers.VisibilityIdentityConfig<AssemblerType>
+{
+ public static final Identity DEFAULT_ENTITYSTORE_IDENTITY = new StringIdentity( "entitystore-sql" );
+
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ SQLDialect dialect = getSQLDialect();
+ if( dialect == null )
+ {
+ throw new AssemblyException( "SQLDialect must not be null" );
+ }
+ Settings settings = getSettings();
+ if( settings == null )
+ {
+ throw new AssemblyException( "Settings must not be null" );
+ }
+ SQLMapEntityStoreMapping mapping = getMapping();
+ if( settings == null )
+ {
+ throw new AssemblyException( "SQLMapEntityStoreSchema must not be null" );
+ }
+
+ module.services( SQLMapEntityStoreService.class )
+ .identifiedBy( ( hasIdentity() ? identity() : DEFAULT_ENTITYSTORE_IDENTITY ).toString() )
+ .visibleIn( visibility() )
+ .setMetaInfo( dialect )
+ .setMetaInfo( settings )
+ .setMetaInfo( mapping );
+
+ if( hasConfig() )
+ {
+ configModule().entities( SQLConfiguration.class ).visibleIn( configVisibility() );
+ }
+ }
+
+ protected Settings getSettings()
+ {
+ return new Settings();
+ }
+
+ protected SQLDialect getSQLDialect()
+ {
+ return SQLDialect.DEFAULT;
+ }
+
+ protected SQLMapEntityStoreMapping getMapping()
+ {
+ return new SQLMapEntityStoreMapping() {};
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/DerbySQLEntityStoreAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/DerbySQLEntityStoreAssembler.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/DerbySQLEntityStoreAssembler.java
index dc91d76..6288d85 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/DerbySQLEntityStoreAssembler.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/DerbySQLEntityStoreAssembler.java
@@ -19,30 +19,17 @@
*/
package org.apache.polygene.entitystore.sql.assembly;
-import java.io.IOException;
-import org.apache.polygene.entitystore.sql.internal.DerbySQLDatabaseSQLServiceMixin;
-import org.sql.generation.api.vendor.DerbyVendor;
-import org.sql.generation.api.vendor.SQLVendor;
-import org.sql.generation.api.vendor.SQLVendorProvider;
+import org.jooq.SQLDialect;
/**
* Derby EntityStore assembly.
*/
public class DerbySQLEntityStoreAssembler
- extends AbstractSQLEntityStoreAssembler<DerbySQLEntityStoreAssembler>
+ extends AbstractSQLMapEntityStoreAssembler<DerbySQLEntityStoreAssembler>
{
-
- @Override
- protected Class<?> getDatabaseSQLServiceSpecializationMixin()
- {
- return DerbySQLDatabaseSQLServiceMixin.class;
- }
-
@Override
- protected SQLVendor getSQLVendor()
- throws IOException
+ protected SQLDialect getSQLDialect()
{
- return SQLVendorProvider.createVendor( DerbyVendor.class );
+ return SQLDialect.DERBY;
}
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/H2SQLEntityStoreAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/H2SQLEntityStoreAssembler.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/H2SQLEntityStoreAssembler.java
index e596fba..018251e 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/H2SQLEntityStoreAssembler.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/H2SQLEntityStoreAssembler.java
@@ -19,30 +19,17 @@
*/
package org.apache.polygene.entitystore.sql.assembly;
-import java.io.IOException;
-import org.apache.polygene.entitystore.sql.internal.H2SQLDatabaseSQLServiceMixin;
-import org.sql.generation.api.vendor.H2Vendor;
-import org.sql.generation.api.vendor.SQLVendor;
-import org.sql.generation.api.vendor.SQLVendorProvider;
+import org.jooq.SQLDialect;
/**
* H2 EntityStore assembly.
*/
public class H2SQLEntityStoreAssembler
- extends AbstractSQLEntityStoreAssembler<H2SQLEntityStoreAssembler>
+ extends AbstractSQLMapEntityStoreAssembler<H2SQLEntityStoreAssembler>
{
-
- @Override
- protected Class<?> getDatabaseSQLServiceSpecializationMixin()
- {
- return H2SQLDatabaseSQLServiceMixin.class;
- }
-
@Override
- protected SQLVendor getSQLVendor()
- throws IOException
+ protected SQLDialect getSQLDialect()
{
- return SQLVendorProvider.createVendor( H2Vendor.class );
+ return SQLDialect.H2;
}
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/MySQLEntityStoreAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/MySQLEntityStoreAssembler.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/MySQLEntityStoreAssembler.java
index e3ea6d1..ff46c82 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/MySQLEntityStoreAssembler.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/MySQLEntityStoreAssembler.java
@@ -19,30 +19,17 @@
*/
package org.apache.polygene.entitystore.sql.assembly;
-import java.io.IOException;
-import org.apache.polygene.entitystore.sql.internal.MySQLDatabaseSQLServiceMixin;
-import org.sql.generation.api.vendor.MySQLVendor;
-import org.sql.generation.api.vendor.SQLVendor;
-import org.sql.generation.api.vendor.SQLVendorProvider;
+import org.jooq.SQLDialect;
/**
* MySQL EntityStore assembly.
*/
public class MySQLEntityStoreAssembler
- extends AbstractSQLEntityStoreAssembler<MySQLEntityStoreAssembler>
+ extends AbstractSQLMapEntityStoreAssembler<MySQLEntityStoreAssembler>
{
-
- @Override
- protected Class<?> getDatabaseSQLServiceSpecializationMixin()
- {
- return MySQLDatabaseSQLServiceMixin.class;
- }
-
@Override
- protected SQLVendor getSQLVendor()
- throws IOException
+ protected SQLDialect getSQLDialect()
{
- return SQLVendorProvider.createVendor( MySQLVendor.class );
+ return SQLDialect.MYSQL;
}
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/PostgreSQLEntityStoreAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/PostgreSQLEntityStoreAssembler.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/PostgreSQLEntityStoreAssembler.java
index a7f0a23..4400b8e 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/PostgreSQLEntityStoreAssembler.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/PostgreSQLEntityStoreAssembler.java
@@ -19,37 +19,17 @@
*/
package org.apache.polygene.entitystore.sql.assembly;
-import java.io.IOException;
-import org.apache.polygene.entitystore.sql.internal.PostgreSQLDatabaseSQLServiceMixin;
-import org.apache.polygene.entitystore.sql.internal.PostgreSQLStringBuilderMixin;
-import org.sql.generation.api.vendor.PostgreSQLVendor;
-import org.sql.generation.api.vendor.SQLVendor;
-import org.sql.generation.api.vendor.SQLVendorProvider;
+import org.jooq.SQLDialect;
/**
* PostgreSQL EntityStore assembly.
*/
public class PostgreSQLEntityStoreAssembler
- extends AbstractSQLEntityStoreAssembler<PostgreSQLEntityStoreAssembler>
+ extends AbstractSQLMapEntityStoreAssembler<PostgreSQLEntityStoreAssembler>
{
-
- @Override
- protected Class<?> getDatabaseSQLServiceSpecializationMixin()
- {
- return PostgreSQLDatabaseSQLServiceMixin.class;
- }
-
@Override
- protected Class<?> getDatabaseStringBuilderMixin()
+ protected SQLDialect getSQLDialect()
{
- return PostgreSQLStringBuilderMixin.class;
+ return SQLDialect.POSTGRES;
}
-
- @Override
- protected SQLVendor getSQLVendor()
- throws IOException
- {
- return SQLVendorProvider.createVendor( PostgreSQLVendor.class );
- }
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/SQLiteEntityStoreAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/SQLiteEntityStoreAssembler.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/SQLiteEntityStoreAssembler.java
index 7c043e7..1b7fa5e 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/SQLiteEntityStoreAssembler.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/assembly/SQLiteEntityStoreAssembler.java
@@ -19,30 +19,17 @@
*/
package org.apache.polygene.entitystore.sql.assembly;
-import java.io.IOException;
-import org.apache.polygene.entitystore.sql.internal.SQLiteDatabaseSQLServiceMixin;
-import org.sql.generation.api.vendor.SQLVendor;
-import org.sql.generation.api.vendor.SQLVendorProvider;
-import org.sql.generation.api.vendor.SQLiteVendor;
+import org.jooq.SQLDialect;
/**
* SQLite EntityStore assembly.
*/
public class SQLiteEntityStoreAssembler
- extends AbstractSQLEntityStoreAssembler<SQLiteEntityStoreAssembler>
+ extends AbstractSQLMapEntityStoreAssembler<SQLiteEntityStoreAssembler>
{
-
- @Override
- protected Class<?> getDatabaseSQLServiceSpecializationMixin()
- {
- return SQLiteDatabaseSQLServiceMixin.class;
- }
-
@Override
- protected SQLVendor getSQLVendor()
- throws IOException
+ protected SQLDialect getSQLDialect()
{
- return SQLVendorProvider.createVendor( SQLiteVendor.class );
+ return SQLDialect.SQLITE;
}
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLService.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLService.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLService.java
index 03ce525..fddb19f 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLService.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLService.java
@@ -24,59 +24,32 @@ import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
-import java.time.Instant;
import org.apache.polygene.api.entity.EntityReference;
import org.apache.polygene.api.service.ServiceComposite;
@SuppressWarnings( "PublicInnerClass" )
public interface DatabaseSQLService
{
-
- public interface DatabaseSQLServiceComposite
- extends DatabaseSQLService, ServiceComposite
+ interface DatabaseSQLServiceComposite extends DatabaseSQLService, ServiceComposite
{
}
- public final class EntityValueResult
+ final class EntityValueResult
{
-
- private final Long entityPK;
-
- private final Long entityOptimisticLock;
-
private final Reader reader;
- public EntityValueResult( Long entityPK, Long entityOptimisticLock, Reader reader )
+ EntityValueResult( Reader reader )
{
- this.entityPK = entityPK;
- this.entityOptimisticLock = entityOptimisticLock;
this.reader = reader;
}
/**
- * @return the entityPK
- */
- public Long getEntityPK()
- {
- return entityPK;
- }
-
- /**
- * @return the entityOptimisticLock
- */
- public Long getEntityOptimisticLock()
- {
- return entityOptimisticLock;
- }
-
- /**
* @return the reader
*/
public Reader getReader()
{
return reader;
}
-
}
void startDatabase()
@@ -109,16 +82,15 @@ public interface DatabaseSQLService
void populateGetAllEntitiesStatement( PreparedStatement ps )
throws SQLException;
- void populateInsertEntityStatement( PreparedStatement ps, EntityReference ref, String entity, Instant lastModified )
+ void populateInsertEntityStatement( PreparedStatement ps, EntityReference ref, String entity )
throws SQLException;
- void populateUpdateEntityStatement( PreparedStatement ps, Long entityPK, Long entityOptimisticLock, EntityReference ref, String entity, Instant lastModified )
+ void populateUpdateEntityStatement( PreparedStatement ps, EntityReference ref, String entity )
throws SQLException;
- void populateRemoveEntityStatement( PreparedStatement ps, Long entityPK, EntityReference ref )
+ void populateRemoveEntityStatement( PreparedStatement ps, EntityReference ref )
throws SQLException;
- EntityValueResult getEntityValue( ResultSet rs )
+ Reader getEntityStateReader( ResultSet rs )
throws SQLException;
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceState.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceState.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceState.java
index 31c4751..3e3926d 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceState.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceState.java
@@ -25,11 +25,9 @@ import org.sql.generation.api.vendor.SQLVendor;
public interface DatabaseSQLServiceState
{
-
@Optional
- public Property<String> schemaName();
+ Property<String> schemaName();
@Optional
- public Property<SQLVendor> vendor();
-
+ Property<SQLVendor> vendor();
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceStatementsMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceStatementsMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceStatementsMixin.java
index 8406e05..cce4568 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceStatementsMixin.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLServiceStatementsMixin.java
@@ -22,7 +22,6 @@ package org.apache.polygene.entitystore.sql.internal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
-import java.time.Instant;
import org.apache.polygene.api.entity.EntityReference;
import org.apache.polygene.api.injection.scope.This;
@@ -89,30 +88,26 @@ public abstract class DatabaseSQLServiceStatementsMixin
}
@Override
- public void populateInsertEntityStatement( PreparedStatement ps, EntityReference ref, String entity, Instant lastModified )
+ public void populateInsertEntityStatement( PreparedStatement ps, EntityReference ref, String entity )
throws SQLException
{
ps.setString( 1, ref.identity().toString() );
ps.setString( 2, entity );
- ps.setLong( 3, lastModified.toEpochMilli() );
}
@Override
- public void populateRemoveEntityStatement( PreparedStatement ps, Long entityPK, EntityReference ref )
+ public void populateRemoveEntityStatement( PreparedStatement ps, EntityReference ref )
throws SQLException
{
- ps.setLong( 1, entityPK );
+ ps.setString( 1, ref.identity().toString() );
}
@Override
- public void populateUpdateEntityStatement( PreparedStatement ps, Long entityPK, Long entityOptimisticLock, EntityReference ref, String entity, Instant lastModified )
+ public void populateUpdateEntityStatement( PreparedStatement ps, EntityReference ref, String entity )
throws SQLException
{
- ps.setLong( 1, entityOptimisticLock + 1 );
+ ps.setString( 1, ref.identity().toString() );
ps.setString( 2, entity );
- ps.setLong( 3, lastModified.toEpochMilli() );
- ps.setLong( 4, entityPK );
- ps.setLong( 5, entityOptimisticLock );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLStringsBuilder.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLStringsBuilder.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLStringsBuilder.java
index f75ba5a..6fb04cb 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLStringsBuilder.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DatabaseSQLStringsBuilder.java
@@ -1,10 +1,10 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
+ * distributed with work for additional information
+ * regarding copyright ownership. The ASF licenses file
* to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
+ * "License"); you may not use file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
@@ -29,7 +29,6 @@ import org.sql.generation.api.grammar.builders.modification.DeleteBySearchBuilde
import org.sql.generation.api.grammar.builders.modification.UpdateBySearchBuilder;
import org.sql.generation.api.grammar.common.SQLStatement;
import org.sql.generation.api.grammar.common.datatypes.SQLDataType;
-import org.sql.generation.api.grammar.definition.table.AutoGenerationPolicy;
import org.sql.generation.api.grammar.definition.table.UniqueSpecification;
import org.sql.generation.api.grammar.factories.BooleanFactory;
import org.sql.generation.api.grammar.factories.ColumnsFactory;
@@ -60,91 +59,68 @@ public interface DatabaseSQLStringsBuilder
String buildSQLForRemoveEntityStatement();
- @SuppressWarnings("PublicInnerClass")
abstract class CommonMixin
implements DatabaseSQLStringsBuilder
{
-
private static final Logger LOGGER = LoggerFactory.getLogger( DatabaseSQLStringsBuilder.class );
@This
- private DatabaseSQLServiceState _state;
+ private DatabaseSQLServiceState dbState;
private SQLVendor vendor;
-
private String schemaName;
private String[] schemaCreationSQLs;
-
private String[] indexCreationSQLs;
-
private String[] tableCreationSQLs;
private String selectAllEntitiesSQL;
-
private String selectEntitySQL;
-
private String insertEntitySQL;
-
private String updateEntitySQL;
-
private String removeEntitySQL;
@Override
public void init()
{
- this.vendor = this._state.vendor().get();
-
- this.schemaName = this._state.schemaName().get();
+ vendor = dbState.vendor().get();
+ schemaName = dbState.schemaName().get();
+ schemaCreationSQLs = toString( createSchemaStatements( vendor ) );
+ indexCreationSQLs = toString( createIndicesStatements( vendor ) );
+ tableCreationSQLs = toString( createTableStatements( vendor ) );
+ selectAllEntitiesSQL = vendor.toString( createSelectAllEntitiesStatement( vendor ) );
+ selectEntitySQL = vendor.toString( createSelectEntityStatement( vendor ) );
+ insertEntitySQL = vendor.toString( createInsertEntityStatement( vendor ) );
+ updateEntitySQL = vendor.toString( createUpdateEntityStatement( vendor ) );
+ removeEntitySQL = vendor.toString( createRemoveEntityStatement( vendor ) );
- this.schemaCreationSQLs = this.toString( this.createSchemaStatements( this.vendor ) );
if( LOGGER.isTraceEnabled() )
{
- LOGGER.trace( "SQL for schema creation: {}", Arrays.asList( this.schemaCreationSQLs ) );
+ LOGGER.trace( "SQL for schema creation: {}", Arrays.asList( schemaCreationSQLs ) );
+ LOGGER.trace( "SQL for index creation: {}", Arrays.asList( indexCreationSQLs ) );
+ LOGGER.trace( "SQL for table creation: {}", Arrays.asList( tableCreationSQLs ) );
+ LOGGER.trace( "SQL for select all entities: {}", selectAllEntitiesSQL );
+ LOGGER.trace( "SQL for select entity: {}", selectEntitySQL );
+ LOGGER.trace( "SQL for insert entity: {}", insertEntitySQL );
+ LOGGER.trace( "SQL for update entity: {}", updateEntitySQL );
+ LOGGER.trace( "SQL for remove entity: {}", removeEntitySQL );
}
-
- this.indexCreationSQLs = this.toString( this.createIndicesStatements( this.vendor ) );
- if( LOGGER.isTraceEnabled() )
- {
- LOGGER.trace( "SQL for index creation: {}", Arrays.asList( this.indexCreationSQLs ) );
- }
-
- this.tableCreationSQLs = this.toString( this.createTableStatements( this.vendor ) );
- if( LOGGER.isTraceEnabled() )
- {
- LOGGER.trace( "SQL for table creation: {}", Arrays.asList( this.tableCreationSQLs ) );
- }
-
- this.selectAllEntitiesSQL = this.vendor.toString( this.createSelectAllEntitiesStatement( this.vendor ) );
- LOGGER.trace( "SQL for select all entities: {}", this.selectAllEntitiesSQL );
-
- this.selectEntitySQL = this.vendor.toString( this.createSelectEntityStatement( this.vendor ) );
- LOGGER.trace( "SQL for select entity: {}", this.selectEntitySQL );
-
- this.insertEntitySQL = this.vendor.toString( this.createInsertEntityStatement( this.vendor ) );
- LOGGER.trace( "SQL for insert entity: {}", this.insertEntitySQL );
-
- this.updateEntitySQL = this.vendor.toString( this.createUpdateEntityStatement( this.vendor ) );
- LOGGER.trace( "SQL for update entity: {}", this.updateEntitySQL );
-
- this.removeEntitySQL = this.vendor.toString( this.createRemoveEntityStatement( this.vendor ) );
- LOGGER.trace( "SQL for remove entity: {}", this.removeEntitySQL );
}
protected String[] toString( SQLStatement[] stmts )
{
- List<String> result = new ArrayList<String>();
+ List<String> result = new ArrayList<>();
if( stmts != null )
{
for( Integer idx = 0; idx < stmts.length; ++idx )
{
- SQLStatement statement = stmts[idx];
+ SQLStatement statement = stmts[ idx ];
if( statement != null )
{
- String stringStatement = this.vendor.toString( statement );
+ String stringStatement = vendor.toString( statement );
if( stringStatement != null && stringStatement.length() > 0 )
{
- result.add( this.vendor.toString( statement ) );
+ result.add( vendor.toString( statement ) );
}
}
}
@@ -154,29 +130,24 @@ public interface DatabaseSQLStringsBuilder
protected SQLVendor getVendor()
{
- return this.vendor;
+ return vendor;
}
protected String getSchemaName()
{
- return this.schemaName;
+ return schemaName;
}
protected SQLStatement[] createSchemaStatements( SQLVendor vendor )
{
- // @formatter:off
- return new SQLStatement[]
- {
+ return new SQLStatement[] {
vendor.getDefinitionFactory().createSchemaDefinitionBuilder()
- .setSchemaName( this.schemaName )
- .createExpression()
+ .setSchemaName( schemaName ).createExpression()
};
- // @formatter:on
}
protected SQLStatement[] createIndicesStatements( SQLVendor vendor )
{
- // TODO
return new SQLStatement[] {};
}
@@ -185,31 +156,25 @@ public interface DatabaseSQLStringsBuilder
DefinitionFactory d = vendor.getDefinitionFactory();
TableReferenceFactory t = vendor.getTableReferenceFactory();
-
- // @formatter:off
- return new SQLStatement[]
- {
+ return new SQLStatement[] {
d.createTableDefinitionBuilder()
- .setTableName( t.tableName( this.getSchemaName(), SQLs.TABLE_NAME ) )
- .setTableContentsSource( d.createTableElementListBuilder()
- .addTableElement( d.createColumnDefinition( SQLs.ENTITY_PK_COLUMN_NAME, this.getPKType(), false, AutoGenerationPolicy.BY_DEFAULT ) )
- .addTableElement( d.createColumnDefinition( SQLs.ENTITY_OPTIMISTIC_LOCK_COLUMN_NAME, this.getOptimisticLockType(), false ) )
- .addTableElement( d.createColumnDefinition( SQLs.ENTITY_IDENTITY_COLUMN_NAME, this.getIDType(), false ) )
- .addTableElement( d.createColumnDefinition( SQLs.ENTITY_STATE_COLUMN_NAME, this.getStateType(), false ) )
- .addTableElement( d.createColumnDefinition( SQLs.ENTITY_LAST_MODIFIED_COLUMN_NAME, this.getLastModifiedType(), false ) )
- .addTableElement( d.createTableConstraintDefinition( d.createUniqueConstraintBuilder()
- .setUniqueness( UniqueSpecification.PRIMARY_KEY )
- .addColumns( SQLs.ENTITY_PK_COLUMN_NAME )
- .createExpression() ) )
- .addTableElement( d.createTableConstraintDefinition( d.createUniqueConstraintBuilder()
- .setUniqueness( UniqueSpecification.UNIQUE )
- .addColumns( SQLs.ENTITY_IDENTITY_COLUMN_NAME )
- .createExpression() ) )
- .createExpression()
- )
- .createExpression()
+ .setTableName( t.tableName( getSchemaName(), SQLs.TABLE_NAME ) )
+ .setTableContentsSource(
+ d.createTableElementListBuilder()
+ .addTableElement( d.createColumnDefinition( SQLs.ENTITY_IDENTITY_COLUMN_NAME,
+ getIDType(), false ) )
+ .addTableElement( d.createColumnDefinition( SQLs.ENTITY_VERSION_COLUMN_NAME,
+ getVersionType(), false ) )
+ .addTableElement( d.createColumnDefinition( SQLs.ENTITY_STATE_COLUMN_NAME,
+ getStateType(), false ) )
+ .addTableElement( d.createTableConstraintDefinition(
+ d.createUniqueConstraintBuilder()
+ .setUniqueness( UniqueSpecification.PRIMARY_KEY )
+ .addColumns( SQLs.ENTITY_IDENTITY_COLUMN_NAME )
+ .createExpression() )
+ ).createExpression()
+ ).createExpression()
};
- // @formatter:on
}
protected SQLStatement createSelectAllEntitiesStatement( SQLVendor vendor )
@@ -217,12 +182,10 @@ public interface DatabaseSQLStringsBuilder
QueryFactory q = vendor.getQueryFactory();
TableReferenceFactory t = vendor.getTableReferenceFactory();
- // @formatter:off
return q.simpleQueryBuilder()
- .select( SQLs.ENTITY_PK_COLUMN_NAME, SQLs.ENTITY_OPTIMISTIC_LOCK_COLUMN_NAME, SQLs.ENTITY_STATE_COLUMN_NAME )
- .from( t.tableName( this.schemaName, SQLs.TABLE_NAME ) )
- .createExpression();
- // @formatter:on
+ .select( SQLs.ENTITY_STATE_COLUMN_NAME )
+ .from( t.tableName( schemaName, SQLs.TABLE_NAME ) )
+ .createExpression();
}
protected SQLStatement createSelectEntityStatement( SQLVendor vendor )
@@ -233,13 +196,11 @@ public interface DatabaseSQLStringsBuilder
ColumnsFactory c = vendor.getColumnsFactory();
LiteralFactory l = vendor.getLiteralFactory();
- // @formatter:off
return q.simpleQueryBuilder()
- .select( SQLs.ENTITY_PK_COLUMN_NAME, SQLs.ENTITY_OPTIMISTIC_LOCK_COLUMN_NAME, SQLs.ENTITY_STATE_COLUMN_NAME )
- .from( t.tableName( this.schemaName, SQLs.TABLE_NAME ) )
- .where( b.eq( c.colName( SQLs.ENTITY_IDENTITY_COLUMN_NAME ), l.param() ) )
- .createExpression();
- // @formatter:on
+ .select( SQLs.ENTITY_STATE_COLUMN_NAME )
+ .from( t.tableName( schemaName, SQLs.TABLE_NAME ) )
+ .where( b.eq( c.colName( SQLs.ENTITY_IDENTITY_COLUMN_NAME ), l.param() ) )
+ .createExpression();
}
protected SQLStatement createInsertEntityStatement( SQLVendor vendor )
@@ -248,26 +209,15 @@ public interface DatabaseSQLStringsBuilder
TableReferenceFactory t = vendor.getTableReferenceFactory();
LiteralFactory l = vendor.getLiteralFactory();
- // @formatter:off
return m.insert()
- .setTableName( t.tableName( this.schemaName, SQLs.TABLE_NAME ) )
- .setColumnSource( m.columnSourceByValues()
- .addColumnNames(
- SQLs.ENTITY_OPTIMISTIC_LOCK_COLUMN_NAME,
- SQLs.ENTITY_IDENTITY_COLUMN_NAME,
- SQLs.ENTITY_STATE_COLUMN_NAME,
- SQLs.ENTITY_LAST_MODIFIED_COLUMN_NAME
- )
- .addValues(
- l.n( 0 ),
- l.param(),
- l.param(),
- l.param()
- )
- .createExpression()
- )
- .createExpression();
- // @formatter:on
+ .setTableName( t.tableName( schemaName, SQLs.TABLE_NAME ) )
+ .setColumnSource( m.columnSourceByValues()
+ .addColumnNames( SQLs.ENTITY_IDENTITY_COLUMN_NAME,
+ SQLs.ENTITY_STATE_COLUMN_NAME )
+ .addValues( l.param(),
+ l.param() )
+ .createExpression()
+ ).createExpression();
}
protected SQLStatement createUpdateEntityStatement( SQLVendor vendor )
@@ -278,20 +228,18 @@ public interface DatabaseSQLStringsBuilder
BooleanFactory b = vendor.getBooleanFactory();
ColumnsFactory c = vendor.getColumnsFactory();
- // @formatter:off
- UpdateBySearchBuilder builder = m.updateBySearch()
- .setTargetTable( m.createTargetTable( t.tableName( this.schemaName, SQLs.TABLE_NAME ) ) )
- .addSetClauses(
- m.setClause( SQLs.ENTITY_OPTIMISTIC_LOCK_COLUMN_NAME, m.updateSourceByExp( l.param() ) ),
- m.setClause( SQLs.ENTITY_STATE_COLUMN_NAME, m.updateSourceByExp( l.param() ) ),
- m.setClause( SQLs.ENTITY_LAST_MODIFIED_COLUMN_NAME, m.updateSourceByExp( l.param() ) )
- );
- builder
- .getWhereBuilder()
- .reset( b.eq( c.colName( SQLs.ENTITY_PK_COLUMN_NAME ), l.param() ) )
- .and( b.eq( c.colName( SQLs.ENTITY_OPTIMISTIC_LOCK_COLUMN_NAME ), l.param() ) );
+ UpdateBySearchBuilder builder = m.updateBySearch().setTargetTable(
+ m.createTargetTable( t.tableName( schemaName, SQLs.TABLE_NAME ) )
+ ).addSetClauses(
+ m.setClause( SQLs.ENTITY_VERSION_COLUMN_NAME, m.updateSourceByExp( l.param() ) ),
+ m.setClause( SQLs.ENTITY_STATE_COLUMN_NAME, m.updateSourceByExp( l.param() ) )
+ );
+ builder.getWhereBuilder().reset(
+ b.eq( c.colName( SQLs.ENTITY_IDENTITY_COLUMN_NAME ), l.param() )
+ ).and(
+ b.eq( c.colName( SQLs.ENTITY_VERSION_COLUMN_NAME ), l.param() )
+ );
return builder.createExpression();
- // @formatter:on
}
protected SQLStatement createRemoveEntityStatement( SQLVendor vendor )
@@ -302,88 +250,76 @@ public interface DatabaseSQLStringsBuilder
BooleanFactory b = vendor.getBooleanFactory();
ColumnsFactory c = vendor.getColumnsFactory();
- // @formatter:off
- DeleteBySearchBuilder builder = m.deleteBySearch()
- .setTargetTable( m.createTargetTable( t.tableName( this.schemaName, SQLs.TABLE_NAME ) ) );
- builder.getWhere()
- .reset( b.eq( c.colName( SQLs.ENTITY_PK_COLUMN_NAME ), l.param() ) );
+ DeleteBySearchBuilder builder = m.deleteBySearch().setTargetTable(
+ m.createTargetTable( t.tableName( schemaName, SQLs.TABLE_NAME ) )
+ );
+ builder.getWhere().reset(
+ b.eq( c.colName( SQLs.ENTITY_IDENTITY_COLUMN_NAME ), l.param() )
+ );
return builder.createExpression();
- // @formatter:on
- }
-
- protected SQLDataType getPKType()
- {
- return this.vendor.getDataTypeFactory().bigInt();
- }
-
- protected SQLDataType getOptimisticLockType()
- {
- return this.vendor.getDataTypeFactory().bigInt();
}
protected SQLDataType getIDType()
{
- return this.vendor.getDataTypeFactory().sqlVarChar( 64 );
+ return vendor.getDataTypeFactory().sqlVarChar( 64 );
}
- protected SQLDataType getStateType()
+ protected SQLDataType getVersionType()
{
- return this.vendor.getDataTypeFactory().sqlVarChar( 10000 );
+ return vendor.getDataTypeFactory().sqlVarChar( 64 );
}
- protected SQLDataType getLastModifiedType()
+ protected SQLDataType getStateType()
{
- return this.vendor.getDataTypeFactory().bigInt();
+ return vendor.getDataTypeFactory().sqlVarChar( 10000 );
}
@Override
public String[] buildSQLForSchemaCreation()
{
- return this.schemaCreationSQLs;
+ return schemaCreationSQLs;
}
@Override
public String[] buildSQLForIndexCreation()
{
- return this.indexCreationSQLs;
+ return indexCreationSQLs;
}
@Override
public String buildSQLForSelectAllEntitiesStatement()
{
- return this.selectAllEntitiesSQL;
+ return selectAllEntitiesSQL;
}
@Override
public String buildSQLForSelectEntityStatement()
{
- return this.selectEntitySQL;
+ return selectEntitySQL;
}
@Override
public String buildSQLForInsertEntityStatement()
{
- return this.insertEntitySQL;
+ return insertEntitySQL;
}
@Override
public String buildSQLForUpdateEntityStatement()
{
- return this.updateEntitySQL;
+ return updateEntitySQL;
}
@Override
public String buildSQLForRemoveEntityStatement()
{
- return this.removeEntitySQL;
+ return removeEntitySQL;
}
@Override
public String[] buildSQLForTableCreation()
{
- return this.tableCreationSQLs;
+ return tableCreationSQLs;
}
-
}
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DerbySQLDatabaseSQLServiceMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DerbySQLDatabaseSQLServiceMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DerbySQLDatabaseSQLServiceMixin.java
index 527cdab..083d79e 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DerbySQLDatabaseSQLServiceMixin.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/DerbySQLDatabaseSQLServiceMixin.java
@@ -19,6 +19,7 @@
*/
package org.apache.polygene.entitystore.sql.internal;
+import java.io.Reader;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.ResultSet;
@@ -28,11 +29,10 @@ import org.apache.polygene.library.sql.common.SQLUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@SuppressWarnings("ProtectedField")
+@SuppressWarnings( "ProtectedField" )
public abstract class DerbySQLDatabaseSQLServiceMixin
implements DatabaseSQLService, DatabaseSQLStringsBuilder, DatabaseSQLServiceSpi
{
-
private static final Logger LOGGER = LoggerFactory.getLogger( DerbySQLDatabaseSQLServiceMixin.class );
@This
@@ -46,10 +46,8 @@ public abstract class DerbySQLDatabaseSQLServiceMixin
try
{
String tableNameForQuery = SQLs.TABLE_NAME.toUpperCase();
- rs = connection.getMetaData().getTables( null, null, tableNameForQuery, new String[]
- {
- "TABLE"
- } );
+ rs = connection.getMetaData().getTables( null, null, tableNameForQuery,
+ new String[] { "TABLE" } );
boolean tableExists = rs.next();
LOGGER.trace( "Found table {}? {}", tableNameForQuery, tableExists );
return tableExists;
@@ -61,12 +59,9 @@ public abstract class DerbySQLDatabaseSQLServiceMixin
}
@Override
- public EntityValueResult getEntityValue( ResultSet rs )
+ public Reader getEntityStateReader( ResultSet rs )
throws SQLException
{
- return new EntityValueResult( rs.getLong( SQLs.ENTITY_PK_COLUMN_NAME ),
- rs.getLong( SQLs.ENTITY_OPTIMISTIC_LOCK_COLUMN_NAME ), new StringReader(
- rs.getString( SQLs.ENTITY_STATE_COLUMN_NAME ) ) );
+ return new StringReader( rs.getString( SQLs.ENTITY_STATE_COLUMN_NAME ) );
}
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/H2SQLDatabaseSQLServiceMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/H2SQLDatabaseSQLServiceMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/H2SQLDatabaseSQLServiceMixin.java
index ba34b36..3b870c6 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/H2SQLDatabaseSQLServiceMixin.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/H2SQLDatabaseSQLServiceMixin.java
@@ -19,6 +19,7 @@
*/
package org.apache.polygene.entitystore.sql.internal;
+import java.io.Reader;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.ResultSet;
@@ -29,35 +30,35 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class H2SQLDatabaseSQLServiceMixin
- implements DatabaseSQLService, DatabaseSQLStringsBuilder, DatabaseSQLServiceSpi
+ implements DatabaseSQLService, DatabaseSQLStringsBuilder, DatabaseSQLServiceSpi
{
-
private static final Logger LOGGER = LoggerFactory.getLogger( H2SQLDatabaseSQLServiceMixin.class );
@This
protected DatabaseSQLServiceSpi spi;
public boolean tableExists( Connection connection )
- throws SQLException
+ throws SQLException
{
ResultSet rs = null;
- try {
+ try
+ {
String tableNameForQuery = SQLs.TABLE_NAME.toUpperCase();
- rs = connection.getMetaData().getTables( null, null, tableNameForQuery, new String[]{ "TABLE" } );
+ rs = connection.getMetaData().getTables( null, null, tableNameForQuery,
+ new String[] { "TABLE" } );
boolean tableExists = rs.next();
LOGGER.trace( "Found table {}? {}", tableNameForQuery, tableExists );
return tableExists;
- } finally {
+ }
+ finally
+ {
SQLUtil.closeQuietly( rs );
}
}
- public EntityValueResult getEntityValue( ResultSet rs )
- throws SQLException
+ public Reader getEntityStateReader( ResultSet rs )
+ throws SQLException
{
- return new EntityValueResult( rs.getLong( SQLs.ENTITY_PK_COLUMN_NAME ),
- rs.getLong( SQLs.ENTITY_OPTIMISTIC_LOCK_COLUMN_NAME ),
- new StringReader( rs.getString( SQLs.ENTITY_STATE_COLUMN_NAME ) ) );
+ return new StringReader( rs.getString( SQLs.ENTITY_STATE_COLUMN_NAME ) );
}
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/MySQLDatabaseSQLServiceMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/MySQLDatabaseSQLServiceMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/MySQLDatabaseSQLServiceMixin.java
index da3479d..1c6c534 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/MySQLDatabaseSQLServiceMixin.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/MySQLDatabaseSQLServiceMixin.java
@@ -19,6 +19,7 @@
*/
package org.apache.polygene.entitystore.sql.internal;
+import java.io.Reader;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.ResultSet;
@@ -28,7 +29,7 @@ import org.apache.polygene.library.sql.common.SQLUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@SuppressWarnings("ProtectedField")
+@SuppressWarnings( "ProtectedField" )
public abstract class MySQLDatabaseSQLServiceMixin
implements DatabaseSQLService, DatabaseSQLStringsBuilder, DatabaseSQLServiceSpi
{
@@ -45,11 +46,9 @@ public abstract class MySQLDatabaseSQLServiceMixin
ResultSet rs = null;
try
{
- String tableNameForQuery = SQLs.TABLE_NAME;
- rs = connection.getMetaData().getTables( null, null, tableNameForQuery, new String[]
- {
- "TABLE"
- } );
+ String tableNameForQuery = SQLs.TABLE_NAME.toUpperCase();
+ rs = connection.getMetaData().getTables( null, null, tableNameForQuery,
+ new String[] { "TABLE" } );
boolean tableExists = rs.next();
LOGGER.trace( "Found table {}? {}", tableNameForQuery, tableExists );
return tableExists;
@@ -61,12 +60,9 @@ public abstract class MySQLDatabaseSQLServiceMixin
}
@Override
- public EntityValueResult getEntityValue( ResultSet rs )
+ public Reader getEntityStateReader( ResultSet rs )
throws SQLException
{
- return new EntityValueResult( rs.getLong( SQLs.ENTITY_PK_COLUMN_NAME ),
- rs.getLong( SQLs.ENTITY_OPTIMISTIC_LOCK_COLUMN_NAME ), new StringReader(
- rs.getString( SQLs.ENTITY_STATE_COLUMN_NAME ) ) );
+ return new StringReader( rs.getString( SQLs.ENTITY_STATE_COLUMN_NAME ) );
}
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/PostgreSQLDatabaseSQLServiceMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/PostgreSQLDatabaseSQLServiceMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/PostgreSQLDatabaseSQLServiceMixin.java
index 9052146..a4cf014 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/PostgreSQLDatabaseSQLServiceMixin.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/PostgreSQLDatabaseSQLServiceMixin.java
@@ -19,6 +19,7 @@
*/
package org.apache.polygene.entitystore.sql.internal;
+import java.io.Reader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
@@ -28,9 +29,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class PostgreSQLDatabaseSQLServiceMixin
- implements DatabaseSQLServiceSpi, DatabaseSQLStringsBuilder, DatabaseSQLService
+ implements DatabaseSQLServiceSpi, DatabaseSQLStringsBuilder, DatabaseSQLService
{
-
private static final Logger LOGGER = LoggerFactory.getLogger( PostgreSQLDatabaseSQLServiceMixin.class );
@This
@@ -38,31 +38,27 @@ public abstract class PostgreSQLDatabaseSQLServiceMixin
@Override
public boolean tableExists( Connection connection )
- throws SQLException
+ throws SQLException
{
ResultSet rs = null;
- try {
-
- rs = connection.getMetaData().getTables( null,
- this.spi.getCurrentSchemaName(),
- SQLs.TABLE_NAME,
- new String[]{ "TABLE" } );
+ try
+ {
+ rs = connection.getMetaData().getTables( null, spi.getCurrentSchemaName(), SQLs.TABLE_NAME,
+ new String[] { "TABLE" } );
boolean tableExists = rs.next();
LOGGER.trace( "Found table {}? {}", SQLs.TABLE_NAME, tableExists );
return tableExists;
-
- } finally {
+ }
+ finally
+ {
SQLUtil.closeQuietly( rs );
}
}
@Override
- public EntityValueResult getEntityValue( ResultSet rs )
- throws SQLException
+ public Reader getEntityStateReader( ResultSet rs )
+ throws SQLException
{
- return new EntityValueResult( rs.getLong( SQLs.ENTITY_PK_COLUMN_NAME ),
- rs.getLong( SQLs.ENTITY_OPTIMISTIC_LOCK_COLUMN_NAME ),
- rs.getCharacterStream( SQLs.ENTITY_STATE_COLUMN_NAME ) );
+ return rs.getCharacterStream( SQLs.ENTITY_STATE_COLUMN_NAME );
}
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLiteDatabaseSQLServiceMixin.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLiteDatabaseSQLServiceMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLiteDatabaseSQLServiceMixin.java
index 2715a00..d762f8b 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLiteDatabaseSQLServiceMixin.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLiteDatabaseSQLServiceMixin.java
@@ -19,6 +19,7 @@
*/
package org.apache.polygene.entitystore.sql.internal;
+import java.io.Reader;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.ResultSet;
@@ -29,9 +30,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class SQLiteDatabaseSQLServiceMixin
- implements DatabaseSQLService, DatabaseSQLStringsBuilder, DatabaseSQLServiceSpi
+ implements DatabaseSQLService, DatabaseSQLStringsBuilder, DatabaseSQLServiceSpi
{
-
private static final Logger LOGGER = LoggerFactory.getLogger( SQLiteDatabaseSQLServiceMixin.class );
@This
@@ -39,27 +39,28 @@ public abstract class SQLiteDatabaseSQLServiceMixin
@Override
public boolean tableExists( Connection connection )
- throws SQLException
+ throws SQLException
{
ResultSet rs = null;
- try {
+ try
+ {
String tableNameForQuery = SQLs.TABLE_NAME.toUpperCase();
- rs = connection.getMetaData().getTables( null, null, tableNameForQuery, new String[]{ "TABLE" } );
+ rs = connection.getMetaData().getTables( null, null, tableNameForQuery,
+ new String[] { "TABLE" } );
boolean tableExists = rs.next();
LOGGER.trace( "Found table {}? {}", tableNameForQuery, tableExists );
return tableExists;
- } finally {
+ }
+ finally
+ {
SQLUtil.closeQuietly( rs );
}
}
@Override
- public EntityValueResult getEntityValue( ResultSet rs )
- throws SQLException
+ public Reader getEntityStateReader( ResultSet rs )
+ throws SQLException
{
- return new EntityValueResult( rs.getLong( SQLs.ENTITY_PK_COLUMN_NAME ),
- rs.getLong( SQLs.ENTITY_OPTIMISTIC_LOCK_COLUMN_NAME ),
- new StringReader( rs.getString( SQLs.ENTITY_STATE_COLUMN_NAME ) ) );
+ return new StringReader( rs.getString( SQLs.ENTITY_STATE_COLUMN_NAME ) );
}
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLs.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLs.java b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLs.java
index bcadde1..8555a5d 100644
--- a/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLs.java
+++ b/extensions/entitystore-sql/src/main/java/org/apache/polygene/entitystore/sql/internal/SQLs.java
@@ -21,19 +21,9 @@ package org.apache.polygene.entitystore.sql.internal;
public interface SQLs
{
-
- String DEFAULT_SCHEMA_NAME = "polygene_es";
-
- String TABLE_NAME = "polygene_entities";
-
- String ENTITY_PK_COLUMN_NAME = "entity_pk";
-
- String ENTITY_IDENTITY_COLUMN_NAME = "entity_id";
-
- String ENTITY_STATE_COLUMN_NAME = "entity_state";
-
- String ENTITY_OPTIMISTIC_LOCK_COLUMN_NAME = "entity_optimistic_lock";
-
- String ENTITY_LAST_MODIFIED_COLUMN_NAME = "entity_last_modified";
-
+ String DEFAULT_SCHEMA_NAME = "POLYGENE_ES";
+ String TABLE_NAME = "POLYGENE_ENTITIES";
+ String ENTITY_IDENTITY_COLUMN_NAME = "ENTITY_IDENTITY";
+ String ENTITY_VERSION_COLUMN_NAME = "ENTITY_VERSION";
+ String ENTITY_STATE_COLUMN_NAME = "ENTITY_STATE";
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/DerbySQLEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/DerbySQLEntityStoreTest.java b/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/DerbySQLEntityStoreTest.java
index 498fb41..6d849cc 100644
--- a/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/DerbySQLEntityStoreTest.java
+++ b/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/DerbySQLEntityStoreTest.java
@@ -19,11 +19,9 @@
*/
package org.apache.polygene.entitystore.sql;
-import java.io.File;
import java.sql.Connection;
import java.sql.Statement;
import javax.sql.DataSource;
-import org.apache.derby.iapi.services.io.FileUtil;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.api.unitofwork.UnitOfWork;
import org.apache.polygene.api.usecase.UsecaseBuilder;
@@ -36,7 +34,6 @@ import org.apache.polygene.library.sql.common.SQLConfiguration;
import org.apache.polygene.library.sql.dbcp.DBCPDataSourceServiceAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
public class DerbySQLEntityStoreTest
extends AbstractEntityStoreTest
@@ -50,29 +47,28 @@ public class DerbySQLEntityStoreTest
super.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
// START SNIPPET: assembly
// DataSourceService
- new DBCPDataSourceServiceAssembler().
- identifiedBy( "derby-datasource-service" ).
- visibleIn( Visibility.module ).
- withConfig( config, Visibility.layer ).
- assemble( module );
+ new DBCPDataSourceServiceAssembler()
+ .identifiedBy( "derby-datasource-service" )
+ .visibleIn( Visibility.module )
+ .withConfig( config, Visibility.layer )
+ .assemble( module );
// DataSource
- new DataSourceAssembler().
- withDataSourceServiceIdentity( "derby-datasource-service" ).
- identifiedBy( "derby-datasource" ).
- visibleIn( Visibility.module ).
- withCircuitBreaker().
- assemble( module );
+ new DataSourceAssembler()
+ .withDataSourceServiceIdentity( "derby-datasource-service" )
+ .identifiedBy( "derby-datasource" )
+ .visibleIn( Visibility.module )
+ .withCircuitBreaker()
+ .assemble( module );
// SQL EntityStore
- new DerbySQLEntityStoreAssembler().
- visibleIn( Visibility.application ).
- withConfig( config, Visibility.layer ).
- assemble( module );
+ new DerbySQLEntityStoreAssembler()
+ .visibleIn( Visibility.application )
+ .withConfig( config, Visibility.layer )
+ .assemble( module );
}
// END SNIPPET: assembly
@@ -84,7 +80,8 @@ public class DerbySQLEntityStoreTest
"Delete " + getClass().getSimpleName() + " test data" ) );
try
{
- SQLConfiguration config = uow.get( SQLConfiguration.class, DerbySQLEntityStoreAssembler.DEFAULT_ENTITYSTORE_IDENTITY );
+ SQLConfiguration config = uow.get( SQLConfiguration.class,
+ DerbySQLEntityStoreAssembler.DEFAULT_ENTITYSTORE_IDENTITY );
Connection connection = serviceFinder.findService( DataSource.class ).get().getConnection();
connection.setAutoCommit( false );
String schemaName = config.schemaName().get();
@@ -94,10 +91,9 @@ public class DerbySQLEntityStoreTest
}
try( Statement stmt = connection.createStatement() )
{
- stmt.execute( String.format( "DELETE FROM %s." + SQLs.TABLE_NAME, schemaName ) );
+ stmt.execute( String.format( "DELETE FROM %s.%s", schemaName, SQLs.TABLE_NAME ) );
connection.commit();
}
- FileUtil.removeDirectory( new File( "target/polygene-data" ) );
}
finally
{
@@ -105,5 +101,4 @@ public class DerbySQLEntityStoreTest
super.tearDown();
}
}
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/H2SQLEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/H2SQLEntityStoreTest.java b/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/H2SQLEntityStoreTest.java
index 8b54b3d..1aed71f 100644
--- a/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/H2SQLEntityStoreTest.java
+++ b/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/H2SQLEntityStoreTest.java
@@ -19,8 +19,6 @@
*/
package org.apache.polygene.entitystore.sql;
-import java.io.File;
-import org.apache.derby.iapi.services.io.FileUtil;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
@@ -29,7 +27,6 @@ import org.apache.polygene.library.sql.assembly.DataSourceAssembler;
import org.apache.polygene.library.sql.dbcp.DBCPDataSourceServiceAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
public class H2SQLEntityStoreTest
extends AbstractEntityStoreTest
@@ -43,44 +40,28 @@ public class H2SQLEntityStoreTest
super.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
// START SNIPPET: assembly
// DataSourceService
- new DBCPDataSourceServiceAssembler().
- identifiedBy( "h2-datasource-service" ).
- visibleIn( Visibility.module ).
- withConfig( config, Visibility.layer ).
- assemble( module );
+ new DBCPDataSourceServiceAssembler()
+ .identifiedBy( "h2-datasource-service" )
+ .visibleIn( Visibility.module )
+ .withConfig( config, Visibility.layer )
+ .assemble( module );
// DataSource
- new DataSourceAssembler().
- withDataSourceServiceIdentity( "h2-datasource-service" ).
- identifiedBy( "h2-datasource" ).
- visibleIn( Visibility.module ).
- withCircuitBreaker().
- assemble( module );
+ new DataSourceAssembler()
+ .withDataSourceServiceIdentity( "h2-datasource-service" )
+ .identifiedBy( "h2-datasource" )
+ .visibleIn( Visibility.module )
+ .withCircuitBreaker()
+ .assemble( module );
// SQL EntityStore
- new H2SQLEntityStoreAssembler().
- visibleIn( Visibility.application ).
- withConfig( config, Visibility.layer ).
- assemble( module );
+ new H2SQLEntityStoreAssembler()
+ .visibleIn( Visibility.application )
+ .withConfig( config, Visibility.layer )
+ .assemble( module );
}
// END SNIPPET: assembly
-
- @Override
- public void tearDown()
- throws Exception
- {
- try
- {
- FileUtil.removeDirectory( new File( "target/polygene-data" ) );
- }
- finally
- {
- super.tearDown();
- }
- }
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/MySQLEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/MySQLEntityStoreTest.java b/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/MySQLEntityStoreTest.java
index 0718ddb..059301c 100644
--- a/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/MySQLEntityStoreTest.java
+++ b/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/MySQLEntityStoreTest.java
@@ -36,7 +36,6 @@ import org.apache.polygene.library.sql.datasource.DataSourceConfiguration;
import org.apache.polygene.library.sql.dbcp.DBCPDataSourceServiceAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.junit.ClassRule;
public class MySQLEntityStoreTest
@@ -64,29 +63,28 @@ public class MySQLEntityStoreTest
super.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
// START SNIPPET: assembly
// DataSourceService
- new DBCPDataSourceServiceAssembler().
- identifiedBy( "mysql-datasource-service" ).
- visibleIn( Visibility.module ).
- withConfig( config, Visibility.layer ).
- assemble( module );
+ new DBCPDataSourceServiceAssembler()
+ .identifiedBy( "mysql-datasource-service" )
+ .visibleIn( Visibility.module )
+ .withConfig( config, Visibility.layer )
+ .assemble( module );
// DataSource
- new DataSourceAssembler().
- withDataSourceServiceIdentity( "mysql-datasource-service" ).
- identifiedBy( "mysql-datasource" ).
- visibleIn( Visibility.module ).
- withCircuitBreaker().
- assemble( module );
+ new DataSourceAssembler()
+ .withDataSourceServiceIdentity( "mysql-datasource-service" )
+ .identifiedBy( "mysql-datasource" )
+ .visibleIn( Visibility.module )
+ .withCircuitBreaker()
+ .assemble( module );
// SQL EntityStore
- new MySQLEntityStoreAssembler().
- visibleIn( Visibility.application ).
- withConfig( config, Visibility.layer ).
- assemble( module );
+ new MySQLEntityStoreAssembler()
+ .visibleIn( Visibility.application )
+ .withConfig( config, Visibility.layer )
+ .assemble( module );
// END SNIPPET: assembly
String mysqlHost = DOCKER.getDockerHost();
int mysqlPort = DOCKER.getExposedContainerPort( "3306/tcp" );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/PostgreSQLEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/PostgreSQLEntityStoreTest.java b/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/PostgreSQLEntityStoreTest.java
index 49d5a13..c6dd48c 100644
--- a/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/PostgreSQLEntityStoreTest.java
+++ b/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/PostgreSQLEntityStoreTest.java
@@ -36,7 +36,6 @@ import org.apache.polygene.library.sql.datasource.DataSourceConfiguration;
import org.apache.polygene.library.sql.dbcp.DBCPDataSourceServiceAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.junit.ClassRule;
/**
@@ -88,29 +87,28 @@ public class PostgreSQLEntityStoreTest
super.assemble( module );
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
// START SNIPPET: assembly
// DataSourceService
- new DBCPDataSourceServiceAssembler().
- identifiedBy( "postgresql-datasource-service" ).
- visibleIn( Visibility.module ).
- withConfig( config, Visibility.layer ).
- assemble( module );
+ new DBCPDataSourceServiceAssembler()
+ .identifiedBy( "postgresql-datasource-service" )
+ .visibleIn( Visibility.module )
+ .withConfig( config, Visibility.layer )
+ .assemble( module );
// DataSource
- new DataSourceAssembler().
- withDataSourceServiceIdentity( "postgresql-datasource-service" ).
- identifiedBy( "postgresql-datasource" ).
- visibleIn( Visibility.module ).
- withCircuitBreaker().
- assemble( module );
+ new DataSourceAssembler()
+ .withDataSourceServiceIdentity( "postgresql-datasource-service" )
+ .identifiedBy( "postgresql-datasource" )
+ .visibleIn( Visibility.module )
+ .withCircuitBreaker()
+ .assemble( module );
// SQL EntityStore
- new PostgreSQLEntityStoreAssembler().
- visibleIn( Visibility.application ).
- withConfig( config, Visibility.layer ).
- assemble( module );
+ new PostgreSQLEntityStoreAssembler()
+ .visibleIn( Visibility.application )
+ .withConfig( config, Visibility.layer )
+ .assemble( module );
// END SNIPPET: assembly
String host = DOCKER.getDockerHost();
int port = DOCKER.getExposedContainerPort( "5432/tcp" );
@@ -129,7 +127,8 @@ public class PostgreSQLEntityStoreTest
);
try
{
- SQLConfiguration config = uow.get( SQLConfiguration.class, PostgreSQLEntityStoreAssembler.DEFAULT_ENTITYSTORE_IDENTITY );
+ SQLConfiguration config = uow.get( SQLConfiguration.class,
+ PostgreSQLEntityStoreAssembler.DEFAULT_ENTITYSTORE_IDENTITY );
Connection connection = serviceFinder.findService( DataSource.class ).get().getConnection();
connection.setAutoCommit( false );
String schemaName = config.schemaName().get();
@@ -139,7 +138,7 @@ public class PostgreSQLEntityStoreTest
}
try( Statement stmt = connection.createStatement() )
{
- stmt.execute( String.format( "DELETE FROM %s." + SQLs.TABLE_NAME, schemaName ) );
+ stmt.execute( String.format( "DROP SCHEMA \"%s\" CASCADE", schemaName ) );
connection.commit();
}
}
@@ -149,5 +148,4 @@ public class PostgreSQLEntityStoreTest
super.tearDown();
}
}
-
}
[41/50] [abbrv] polygene-java git commit: Finish jooq & liquibase
powered SQL ES
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/DerbySQLEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/DerbySQLEntityStoreTest.java b/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/DerbySQLEntityStoreTest.java
index 6d849cc..f66ca9c 100644
--- a/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/DerbySQLEntityStoreTest.java
+++ b/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/DerbySQLEntityStoreTest.java
@@ -28,13 +28,13 @@ import org.apache.polygene.api.usecase.UsecaseBuilder;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.sql.assembly.DerbySQLEntityStoreAssembler;
-import org.apache.polygene.entitystore.sql.internal.SQLs;
import org.apache.polygene.library.sql.assembly.DataSourceAssembler;
-import org.apache.polygene.library.sql.common.SQLConfiguration;
import org.apache.polygene.library.sql.dbcp.DBCPDataSourceServiceAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
+import static org.apache.polygene.entitystore.sql.assembly.DerbySQLEntityStoreAssembler.DEFAULT_ENTITYSTORE_IDENTITY;
+
public class DerbySQLEntityStoreTest
extends AbstractEntityStoreTest
{
@@ -80,18 +80,15 @@ public class DerbySQLEntityStoreTest
"Delete " + getClass().getSimpleName() + " test data" ) );
try
{
- SQLConfiguration config = uow.get( SQLConfiguration.class,
- DerbySQLEntityStoreAssembler.DEFAULT_ENTITYSTORE_IDENTITY );
+ SQLMapEntityStoreConfiguration config = uow.get( SQLMapEntityStoreConfiguration.class,
+ DEFAULT_ENTITYSTORE_IDENTITY );
Connection connection = serviceFinder.findService( DataSource.class ).get().getConnection();
connection.setAutoCommit( false );
- String schemaName = config.schemaName().get();
- if( schemaName == null )
- {
- schemaName = SQLs.DEFAULT_SCHEMA_NAME;
- }
try( Statement stmt = connection.createStatement() )
{
- stmt.execute( String.format( "DELETE FROM %s.%s", schemaName, SQLs.TABLE_NAME ) );
+ stmt.execute( String.format( "DELETE FROM %s.%s",
+ config.schemaName().get(),
+ config.entityTableName().get() ) );
connection.commit();
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/MySQLEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/MySQLEntityStoreTest.java b/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/MySQLEntityStoreTest.java
index 059301c..402782e 100644
--- a/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/MySQLEntityStoreTest.java
+++ b/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/MySQLEntityStoreTest.java
@@ -29,15 +29,16 @@ import org.apache.polygene.api.usecase.UsecaseBuilder;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.sql.assembly.MySQLEntityStoreAssembler;
-import org.apache.polygene.entitystore.sql.internal.SQLs;
-import org.apache.polygene.test.internal.DockerRule;
import org.apache.polygene.library.sql.assembly.DataSourceAssembler;
import org.apache.polygene.library.sql.datasource.DataSourceConfiguration;
import org.apache.polygene.library.sql.dbcp.DBCPDataSourceServiceAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
+import org.apache.polygene.test.internal.DockerRule;
import org.junit.ClassRule;
+import static org.apache.polygene.entitystore.sql.assembly.MySQLEntityStoreAssembler.DEFAULT_ENTITYSTORE_IDENTITY;
+
public class MySQLEntityStoreTest
extends AbstractEntityStoreTest
{
@@ -90,7 +91,8 @@ public class MySQLEntityStoreTest
int mysqlPort = DOCKER.getExposedContainerPort( "3306/tcp" );
config.forMixin( DataSourceConfiguration.class ).declareDefaults()
.url().set( "jdbc:mysql://" + mysqlHost + ":" + mysqlPort
- + "/jdbc_test_db?profileSQL=false&useLegacyDatetimeCode=false&serverTimezone=UTC" );
+ + "/jdbc_test_db?profileSQL=false&useLegacyDatetimeCode=false&serverTimezone=UTC"
+ + "&nullCatalogMeansCurrent=true&nullNamePatternMatchesAll=true" );
// START SNIPPET: assembly
}
// END SNIPPET: assembly
@@ -104,10 +106,14 @@ public class MySQLEntityStoreTest
try
{
Connection connection = serviceFinder.findService( DataSource.class ).get().getConnection();
+ SQLMapEntityStoreConfiguration configuration = uow.get( SQLMapEntityStoreConfiguration.class,
+ DEFAULT_ENTITYSTORE_IDENTITY );
connection.setAutoCommit( false );
try( Statement stmt = connection.createStatement() )
{
- stmt.execute( String.format( "TRUNCATE %s", SQLs.TABLE_NAME ) );
+ stmt.execute( String.format( "TRUNCATE %s.%s",
+ configuration.schemaName().get(),
+ configuration.entityTableName().get() ) );
connection.commit();
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/PostgreSQLEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/PostgreSQLEntityStoreTest.java b/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/PostgreSQLEntityStoreTest.java
index c6dd48c..d1f06f3 100644
--- a/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/PostgreSQLEntityStoreTest.java
+++ b/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/PostgreSQLEntityStoreTest.java
@@ -28,16 +28,17 @@ import org.apache.polygene.api.usecase.UsecaseBuilder;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.sql.assembly.PostgreSQLEntityStoreAssembler;
-import org.apache.polygene.entitystore.sql.internal.SQLs;
-import org.apache.polygene.test.internal.DockerRule;
import org.apache.polygene.library.sql.assembly.DataSourceAssembler;
import org.apache.polygene.library.sql.common.SQLConfiguration;
import org.apache.polygene.library.sql.datasource.DataSourceConfiguration;
import org.apache.polygene.library.sql.dbcp.DBCPDataSourceServiceAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.entity.AbstractEntityStoreTest;
+import org.apache.polygene.test.internal.DockerRule;
import org.junit.ClassRule;
+import static org.apache.polygene.entitystore.sql.assembly.PostgreSQLEntityStoreAssembler.DEFAULT_ENTITYSTORE_IDENTITY;
+
/**
* WARN This test run only if localhost:5432 is listening.
*
@@ -127,15 +128,10 @@ public class PostgreSQLEntityStoreTest
);
try
{
- SQLConfiguration config = uow.get( SQLConfiguration.class,
- PostgreSQLEntityStoreAssembler.DEFAULT_ENTITYSTORE_IDENTITY );
+ SQLConfiguration config = uow.get( SQLConfiguration.class, DEFAULT_ENTITYSTORE_IDENTITY );
Connection connection = serviceFinder.findService( DataSource.class ).get().getConnection();
connection.setAutoCommit( false );
String schemaName = config.schemaName().get();
- if( schemaName == null )
- {
- schemaName = SQLs.DEFAULT_SCHEMA_NAME;
- }
try( Statement stmt = connection.createStatement() )
{
stmt.execute( String.format( "DROP SCHEMA \"%s\" CASCADE", schemaName ) );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/SQLiteEntityStoreTest.java
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/SQLiteEntityStoreTest.java b/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/SQLiteEntityStoreTest.java
index 24dd298..07402b5 100644
--- a/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/SQLiteEntityStoreTest.java
+++ b/extensions/entitystore-sql/src/test/java/org/apache/polygene/entitystore/sql/SQLiteEntityStoreTest.java
@@ -31,8 +31,7 @@ import org.junit.BeforeClass;
import static org.apache.polygene.test.util.Assume.assumeNoIbmJdk;
-public class SQLiteEntityStoreTest
- extends AbstractEntityStoreTest
+public class SQLiteEntityStoreTest extends AbstractEntityStoreTest
{
@BeforeClass
public static void beforeClass_IBMJDK()
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/entitystore-sql/src/test/resources/mysql-datasource.properties
----------------------------------------------------------------------
diff --git a/extensions/entitystore-sql/src/test/resources/mysql-datasource.properties b/extensions/entitystore-sql/src/test/resources/mysql-datasource.properties
index 964c7d6..a2f4175 100644
--- a/extensions/entitystore-sql/src/test/resources/mysql-datasource.properties
+++ b/extensions/entitystore-sql/src/test/resources/mysql-datasource.properties
@@ -19,7 +19,7 @@
#
enabled=true
-#url=jdbc:mysql://localhost:3306/jdbc_test_db?profileSQL=false&useLegacyDatetimeCode=false&serverTimezone=UTC
+#url=jdbc:mysql://localhost:3306/jdbc_test_db?profileSQL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&nullCatalogMeansCurrent=true&nullNamePatternMatchesAll=true
driver=com.mysql.cj.jdbc.Driver
username=root
password=
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/SQLIndexingEngineConfiguration.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/SQLIndexingEngineConfiguration.java b/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/SQLIndexingEngineConfiguration.java
new file mode 100644
index 0000000..5920ed6
--- /dev/null
+++ b/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/SQLIndexingEngineConfiguration.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.index.sql;
+
+import org.apache.polygene.api.common.UseDefaults;
+import org.apache.polygene.api.property.Property;
+import org.apache.polygene.library.sql.common.SQLConfiguration;
+
+public interface SQLIndexingEngineConfiguration extends SQLConfiguration
+{
+ @UseDefaults( "POLYGENE_INDEX" )
+ @Override
+ Property<String> schemaName();
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/assembly/AbstractSQLIndexQueryAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/assembly/AbstractSQLIndexQueryAssembler.java b/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/assembly/AbstractSQLIndexQueryAssembler.java
index 11f257e..a9dcd0c 100644
--- a/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/assembly/AbstractSQLIndexQueryAssembler.java
+++ b/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/assembly/AbstractSQLIndexQueryAssembler.java
@@ -28,8 +28,8 @@ import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.index.reindexer.ReindexerConfiguration;
import org.apache.polygene.index.reindexer.ReindexerService;
+import org.apache.polygene.index.sql.SQLIndexingEngineConfiguration;
import org.apache.polygene.index.sql.support.common.ReindexingStrategy;
-import org.apache.polygene.library.sql.common.SQLConfiguration;
import org.sql.generation.api.vendor.SQLVendor;
import org.sql.generation.api.vendor.SQLVendorProvider;
@@ -91,7 +91,7 @@ public abstract class AbstractSQLIndexQueryAssembler<AssemblerType>
if( hasConfig() )
{
- configModule().entities( SQLConfiguration.class,
+ configModule().entities( SQLIndexingEngineConfiguration.class,
ReindexerConfiguration.class ).
visibleIn( configVisibility() );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/support/skeletons/AbstractSQLStartup.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/support/skeletons/AbstractSQLStartup.java b/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/support/skeletons/AbstractSQLStartup.java
index e74572f..b41c41a 100644
--- a/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/support/skeletons/AbstractSQLStartup.java
+++ b/extensions/indexing-sql/src/main/java/org/apache/polygene/index/sql/support/skeletons/AbstractSQLStartup.java
@@ -136,8 +136,6 @@ public abstract class AbstractSQLStartup
SQLDataType customizeType( Type propertyType, SQLTypeInfo sqlTypeInfo );
}
- public static final String DEFAULT_SCHEMA_NAME = "polygene";
-
private static final Class<?> ENTITY_PK_TYPE = Long.class;
private static final Class<?> ENTITY_TYPE_PK_TYPE = Integer.class;
@@ -195,15 +193,8 @@ public abstract class AbstractSQLStartup
this.initTypes();
this.modifyPrimitiveTypes( this._primitiveTypes, this._state.javaTypes2SQLTypes().get() );
- String schemaName = this._configuration.get().schemaName().get();
- if( schemaName == null )
- {
- schemaName = DEFAULT_SCHEMA_NAME;
- }
- else
- {
- this.checkSchemaName( schemaName );
- }
+ String schemaName = this._configuration.get().schemaName().get().toLowerCase();
+ this.checkSchemaName( schemaName );
LOGGER.debug( "Will use '{}' as schema name", schemaName );
this._state.schemaName().set( schemaName );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/extensions/indexing-sql/src/test/java/org/apache/polygene/index/sql/postgresql/PostgreSQLDBIntegrityTest.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-sql/src/test/java/org/apache/polygene/index/sql/postgresql/PostgreSQLDBIntegrityTest.java b/extensions/indexing-sql/src/test/java/org/apache/polygene/index/sql/postgresql/PostgreSQLDBIntegrityTest.java
index 627c8df..62c245e 100644
--- a/extensions/indexing-sql/src/test/java/org/apache/polygene/index/sql/postgresql/PostgreSQLDBIntegrityTest.java
+++ b/extensions/indexing-sql/src/test/java/org/apache/polygene/index/sql/postgresql/PostgreSQLDBIntegrityTest.java
@@ -90,11 +90,7 @@ public class PostgreSQLDBIntegrityTest
uow = this.unitOfWorkFactory.newUnitOfWork();
entity = uow.get( entity );
SQLConfiguration config = uow.get( SQLConfiguration.class, PostgreSQLIndexQueryAssembler.DEFAULT_IDENTITY );
- String schemaName = config.schemaName().get();
- if( schemaName == null )
- {
- schemaName = PostgreSQLAppStartup.DEFAULT_SCHEMA_NAME;
- }
+ String schemaName = config.schemaName().get().toLowerCase();
uow.remove( entity );
uow.complete();
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/libraries/sql-liquibase/build.gradle
----------------------------------------------------------------------
diff --git a/libraries/sql-liquibase/build.gradle b/libraries/sql-liquibase/build.gradle
index 4d94e30..e6a43ef 100644
--- a/libraries/sql-liquibase/build.gradle
+++ b/libraries/sql-liquibase/build.gradle
@@ -26,9 +26,7 @@ jar { manifest { name = "Apache Polygene\u2122 Library - SQL Liquibase" } }
dependencies {
api polygene.library( 'sql' )
-
- implementation libraries.liquibase
- implementation libraries.slf4j_api
+ api libraries.liquibase
runtimeOnly polygene.core.runtime
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/libraries/sql-liquibase/src/main/java/org/apache/polygene/library/sql/liquibase/LiquibaseAssembler.java
----------------------------------------------------------------------
diff --git a/libraries/sql-liquibase/src/main/java/org/apache/polygene/library/sql/liquibase/LiquibaseAssembler.java b/libraries/sql-liquibase/src/main/java/org/apache/polygene/library/sql/liquibase/LiquibaseAssembler.java
index 15124f8..e462c0b 100644
--- a/libraries/sql-liquibase/src/main/java/org/apache/polygene/library/sql/liquibase/LiquibaseAssembler.java
+++ b/libraries/sql-liquibase/src/main/java/org/apache/polygene/library/sql/liquibase/LiquibaseAssembler.java
@@ -27,13 +27,17 @@ import org.apache.polygene.bootstrap.ServiceDeclaration;
public class LiquibaseAssembler
extends Assemblers.VisibilityIdentityConfig<LiquibaseAssembler>
{
+ private boolean applyChangelogOnStartup;
+
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
- ServiceDeclaration service = module.services( LiquibaseService.class ).
- visibleIn( visibility() ).
- instantiateOnStartup();
+ ServiceDeclaration service = module.services( LiquibaseService.class ).visibleIn( visibility() );
+ if( applyChangelogOnStartup )
+ {
+ service.withActivators( LiquibaseService.ApplyChangelogActivator.class ).instantiateOnStartup();
+ }
if( hasIdentity() )
{
service.identifiedBy( identity() );
@@ -43,4 +47,10 @@ public class LiquibaseAssembler
configModule().entities( LiquibaseConfiguration.class ).visibleIn( configVisibility() );
}
}
+
+ public LiquibaseAssembler applyChangelogOnStartup()
+ {
+ applyChangelogOnStartup = true;
+ return this;
+ }
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/libraries/sql-liquibase/src/main/java/org/apache/polygene/library/sql/liquibase/LiquibaseConfiguration.java
----------------------------------------------------------------------
diff --git a/libraries/sql-liquibase/src/main/java/org/apache/polygene/library/sql/liquibase/LiquibaseConfiguration.java b/libraries/sql-liquibase/src/main/java/org/apache/polygene/library/sql/liquibase/LiquibaseConfiguration.java
index bb5c00b..99ffa3a 100644
--- a/libraries/sql-liquibase/src/main/java/org/apache/polygene/library/sql/liquibase/LiquibaseConfiguration.java
+++ b/libraries/sql-liquibase/src/main/java/org/apache/polygene/library/sql/liquibase/LiquibaseConfiguration.java
@@ -20,18 +20,18 @@
package org.apache.polygene.library.sql.liquibase;
import org.apache.polygene.api.common.UseDefaults;
-import org.apache.polygene.api.configuration.ConfigurationComposite;
-import org.apache.polygene.api.configuration.Enabled;
import org.apache.polygene.api.property.Property;
/**
- * Configuration for Liquibase
+ * Configuration for Liquibase.
*/
// START SNIPPET: config
public interface LiquibaseConfiguration
- extends ConfigurationComposite, Enabled
{
- @UseDefaults Property<String> contexts();
- @UseDefaults Property<String> changeLog();
+ @UseDefaults
+ Property<String> changeLog();
+
+ @UseDefaults
+ Property<String> contexts();
}
// END SNIPPET: config
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/libraries/sql-liquibase/src/main/java/org/apache/polygene/library/sql/liquibase/LiquibaseService.java
----------------------------------------------------------------------
diff --git a/libraries/sql-liquibase/src/main/java/org/apache/polygene/library/sql/liquibase/LiquibaseService.java b/libraries/sql-liquibase/src/main/java/org/apache/polygene/library/sql/liquibase/LiquibaseService.java
index e909999..4be23a5 100644
--- a/libraries/sql-liquibase/src/main/java/org/apache/polygene/library/sql/liquibase/LiquibaseService.java
+++ b/libraries/sql-liquibase/src/main/java/org/apache/polygene/library/sql/liquibase/LiquibaseService.java
@@ -19,58 +19,76 @@
*/
package org.apache.polygene.library.sql.liquibase;
-import java.net.ConnectException;
-import java.sql.Connection;
import java.sql.SQLException;
+import java.util.Collections;
+import java.util.Map;
import javax.sql.DataSource;
import liquibase.Liquibase;
import liquibase.database.DatabaseConnection;
import liquibase.database.jvm.JdbcConnection;
+import liquibase.exception.LiquibaseException;
import liquibase.resource.ClassLoaderResourceAccessor;
import org.apache.polygene.api.activation.ActivatorAdapter;
-import org.apache.polygene.api.activation.Activators;
import org.apache.polygene.api.configuration.Configuration;
import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
-import org.apache.polygene.api.service.ServiceComposite;
-import org.apache.polygene.api.service.ServiceImporterException;
import org.apache.polygene.api.service.ServiceReference;
-import org.apache.polygene.library.sql.common.SQLUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
/**
* Wrapper service for Liquibase.
*/
@Mixins( LiquibaseService.Mixin.class )
-@Activators( LiquibaseService.Activator.class )
public interface LiquibaseService
- extends ServiceComposite
{
-
- void activateLiquibase()
- throws Exception;
-
- public static class Activator
- extends ActivatorAdapter<ServiceReference<LiquibaseService>>
+ /**
+ * Creates a new Liquibase instance connected to a visible DataSource.
+ *
+ * <strong>WARNING</strong> remember to {@literal liquibase.getDatabase().close()}
+ *
+ * @return a new Liquibase instance connected to a visible DataSource.
+ * @throws SQLException if something goes wrong
+ * @throws LiquibaseException if something goes wrong
+ */
+ Liquibase newConnectedLiquibase() throws SQLException, LiquibaseException;
+
+ /**
+ * Apply the configured database changelog.
+ *
+ * @throws SQLException if something goes wrong
+ * @throws LiquibaseException if something goes wrong
+ */
+ void applyChangelog() throws SQLException, LiquibaseException;
+
+ /**
+ * Apply the configured database changelog.
+ *
+ * @param parameters changelog parameters, see {@link Liquibase#getChangeLogParameters()}
+ * @throws SQLException if something goes wrong
+ * @throws LiquibaseException if something goes wrong
+ */
+ void applyChangelog( Map<String, Object> parameters )
+ throws SQLException, LiquibaseException;
+
+ /**
+ * Apply database changelog on application startup.
+ *
+ * Assembled by {@link LiquibaseAssembler#applyChangelogOnStartup()}.
+ *
+ * @see LiquibaseService#applyChangelog()
+ */
+ class ApplyChangelogActivator extends ActivatorAdapter<ServiceReference<LiquibaseService>>
{
-
@Override
public void afterActivation( ServiceReference<LiquibaseService> activated )
- throws Exception
+ throws Exception
{
- activated.get().activateLiquibase();
+ activated.get().applyChangelog();
}
-
}
- public static abstract class Mixin
- implements LiquibaseService
+ class Mixin implements LiquibaseService
{
-
- private static final Logger LOGGER = LoggerFactory.getLogger( "org.apache.polygene.library.sql" );
-
@This
Configuration<LiquibaseConfiguration> config;
@@ -78,49 +96,42 @@ public interface LiquibaseService
ServiceReference<DataSource> dataSource;
@Override
- public void activateLiquibase()
- throws Exception
+ public Liquibase newConnectedLiquibase() throws SQLException, LiquibaseException
{
config.refresh();
- boolean enabled = config.get().enabled().get();
- if ( !enabled ) {
- return;
- }
-
- Connection connection = null;
- try {
-
- connection = dataSource.get().getConnection();
- DatabaseConnection dc = new JdbcConnection( connection );
- Liquibase liquibase = new Liquibase( config.get().changeLog().get(), new ClassLoaderResourceAccessor(), dc );
- liquibase.update( config.get().contexts().get() );
+ DatabaseConnection dbConnection = new JdbcConnection( dataSource.get().getConnection() );
+ return new Liquibase( config.get().changeLog().get(),
+ new ClassLoaderResourceAccessor(),
+ dbConnection );
+ }
- } catch ( SQLException e ) {
+ @Override
+ public void applyChangelog() throws SQLException, LiquibaseException
+ {
+ applyChangelog( Collections.emptyMap() );
+ }
- Throwable ex = e;
- while ( ex.getCause() != null ) {
- ex = ex.getCause();
+ @Override
+ public void applyChangelog( Map<String, Object> parameters )
+ throws SQLException, LiquibaseException
+ {
+ Liquibase liquibase = null;
+ try
+ {
+ liquibase = newConnectedLiquibase();
+ for( Map.Entry<String, Object> entry : parameters.entrySet() )
+ {
+ liquibase.getChangeLogParameters().set( entry.getKey(), entry.getValue() );
}
-
- if ( ex instanceof ConnectException ) {
- LOGGER.warn( "Could not connect to database; Liquibase should be disabled" );
- return;
+ liquibase.update( config.get().contexts().get() );
+ }
+ finally
+ {
+ if( liquibase != null )
+ {
+ liquibase.getDatabase().close();
}
-
- LOGGER.error( "Liquibase could not perform database migration", e );
-
- } catch ( ServiceImporterException ex ) {
-
- LOGGER.warn( "DataSource is not available - database refactoring skipped" );
-
- } finally {
-
- SQLUtil.rollbackQuietly( connection );
- SQLUtil.closeQuietly( connection );
-
}
}
-
}
-
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/libraries/sql-liquibase/src/test/java/org/apache/polygene/library/sql/liquibase/LiquibaseServiceTest.java
----------------------------------------------------------------------
diff --git a/libraries/sql-liquibase/src/test/java/org/apache/polygene/library/sql/liquibase/LiquibaseServiceTest.java b/libraries/sql-liquibase/src/test/java/org/apache/polygene/library/sql/liquibase/LiquibaseServiceTest.java
index 108a187..fd39fb3 100644
--- a/libraries/sql-liquibase/src/test/java/org/apache/polygene/library/sql/liquibase/LiquibaseServiceTest.java
+++ b/libraries/sql-liquibase/src/test/java/org/apache/polygene/library/sql/liquibase/LiquibaseServiceTest.java
@@ -19,8 +19,6 @@
*/
package org.apache.polygene.library.sql.liquibase;
-import java.io.IOException;
-import java.sql.SQLException;
import java.util.List;
import java.util.function.Function;
import javax.sql.DataSource;
@@ -60,8 +58,7 @@ import static org.junit.Assert.assertTrue;
public class LiquibaseServiceTest
{
@Test
- public void testLiquibase()
- throws SQLException, IOException, ActivationException, AssemblyException
+ public void testLiquibase() throws ActivationException
{
final SingletonAssembler assembler = new SingletonAssembler()
{
@@ -89,9 +86,9 @@ public class LiquibaseServiceTest
// START SNIPPET: assembly
new LiquibaseAssembler()
.withConfig( configModule, Visibility.layer )
+ .applyChangelogOnStartup()
.assemble( module );
// END SNIPPET: assembly
- module.forMixin( LiquibaseConfiguration.class ).declareDefaults().enabled().set( true );
module.forMixin( LiquibaseConfiguration.class ).declareDefaults().changeLog().set( "changelog.xml" );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/libraries/sql/src/main/java/org/apache/polygene/library/sql/common/SQLConfiguration.java
----------------------------------------------------------------------
diff --git a/libraries/sql/src/main/java/org/apache/polygene/library/sql/common/SQLConfiguration.java b/libraries/sql/src/main/java/org/apache/polygene/library/sql/common/SQLConfiguration.java
index 0a0da78..2a62a7e 100644
--- a/libraries/sql/src/main/java/org/apache/polygene/library/sql/common/SQLConfiguration.java
+++ b/libraries/sql/src/main/java/org/apache/polygene/library/sql/common/SQLConfiguration.java
@@ -20,7 +20,6 @@
package org.apache.polygene.library.sql.common;
import org.apache.polygene.api.common.Optional;
-import org.apache.polygene.api.configuration.ConfigurationComposite;
import org.apache.polygene.api.property.Property;
/**
@@ -28,13 +27,10 @@ import org.apache.polygene.api.property.Property;
* database, and given schema name as schema to create tables in.
*/
public interface SQLConfiguration
- extends ConfigurationComposite
{
-
/**
* The schema name to use to create/find tables.
*/
@Optional
Property<String> schemaName();
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/libraries/sql/src/test/java/org/apache/polygene/library/sql/jmx/DataSourceConfigurationManagerServiceTest.java
----------------------------------------------------------------------
diff --git a/libraries/sql/src/test/java/org/apache/polygene/library/sql/jmx/DataSourceConfigurationManagerServiceTest.java b/libraries/sql/src/test/java/org/apache/polygene/library/sql/jmx/DataSourceConfigurationManagerServiceTest.java
index 3645623..fc2a922 100644
--- a/libraries/sql/src/test/java/org/apache/polygene/library/sql/jmx/DataSourceConfigurationManagerServiceTest.java
+++ b/libraries/sql/src/test/java/org/apache/polygene/library/sql/jmx/DataSourceConfigurationManagerServiceTest.java
@@ -30,8 +30,8 @@ import org.apache.polygene.library.sql.assembly.DataSourceAssembler;
import org.apache.polygene.library.sql.assembly.DataSourceJMXAssembler;
import org.apache.polygene.library.sql.datasource.DataSources;
import org.apache.polygene.library.sql.dbcp.DBCPDataSourceServiceAssembler;
+import org.apache.polygene.library.sql.liquibase.LiquibaseAssembler;
import org.apache.polygene.library.sql.liquibase.LiquibaseConfiguration;
-import org.apache.polygene.library.sql.liquibase.LiquibaseService;
import org.apache.polygene.test.EntityTestAssembler;
import org.junit.Test;
@@ -95,10 +95,9 @@ public class DataSourceConfigurationManagerServiceTest
.assemble( testModule );
// Set up Liquibase service that will create the tables
- testModule.services( LiquibaseService.class ).identifiedBy( "liquibase1" ).instantiateOnStartup();
- testModule.entities( LiquibaseConfiguration.class );
- testModule.forMixin( LiquibaseConfiguration.class ).declareDefaults()
- .enabled().set( true );
+ new LiquibaseAssembler().identifiedBy( "liquibase1" )
+ .applyChangelogOnStartup()
+ .assemble( testModule );
testModule.forMixin( LiquibaseConfiguration.class ).declareDefaults()
.changeLog().set( "changelog.xml" );
}
@@ -115,12 +114,11 @@ public class DataSourceConfigurationManagerServiceTest
.assemble( testModule2 );
// Set up Liquibase service that will create the tables
- testModule2.services( LiquibaseService.class ).identifiedBy( "liquibase2" ).instantiateOnStartup();
- testModule2.entities( LiquibaseConfiguration.class );
- testModule2.forMixin( LiquibaseConfiguration.class ).declareDefaults()
- .enabled().set( true );
+ new LiquibaseAssembler().identifiedBy( "liquibase2" )
+ .applyChangelogOnStartup()
+ .assemble( testModule2 );
testModule2.forMixin( LiquibaseConfiguration.class ).declareDefaults()
- .changeLog().set( "changelog.xml" );
+ .changeLog().set( "changelog.xml" );
}
// START SNIPPET: jmx
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/samples/sql-support/src/main/java/org/apache/polygene/sample/sqlsupport/Main.java
----------------------------------------------------------------------
diff --git a/samples/sql-support/src/main/java/org/apache/polygene/sample/sqlsupport/Main.java b/samples/sql-support/src/main/java/org/apache/polygene/sample/sqlsupport/Main.java
index a3cb6aa..5a96f31 100644
--- a/samples/sql-support/src/main/java/org/apache/polygene/sample/sqlsupport/Main.java
+++ b/samples/sql-support/src/main/java/org/apache/polygene/sample/sqlsupport/Main.java
@@ -31,9 +31,7 @@ import org.apache.polygene.api.structure.Module;
import org.apache.polygene.api.unitofwork.UnitOfWork;
import org.apache.polygene.bootstrap.Energy4Java;
import org.apache.polygene.entitystore.sql.assembly.PostgreSQLEntityStoreAssembler;
-import org.apache.polygene.entitystore.sql.internal.SQLs;
import org.apache.polygene.index.sql.assembly.PostgreSQLIndexQueryAssembler;
-import org.apache.polygene.index.sql.support.postgresql.PostgreSQLAppStartup;
import org.apache.polygene.library.sql.common.SQLConfiguration;
import org.apache.polygene.library.sql.common.SQLUtil;
@@ -120,9 +118,6 @@ public class Main
connection.setAutoCommit( false );
connection.setReadOnly( false );
String schemaName = config.schemaName().get();
- if ( schemaName == null ) {
- schemaName = SQLs.DEFAULT_SCHEMA_NAME;
- }
Statement stmt = null;
try {
@@ -146,9 +141,6 @@ public class Main
connection.setAutoCommit( false );
connection.setReadOnly( false );
String schemaName = config.schemaName().get();
- if ( schemaName == null ) {
- schemaName = PostgreSQLAppStartup.DEFAULT_SCHEMA_NAME;
- }
Statement stmt = null;
try {
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/sql/DerbySQLEntityStorePerformanceTest.java
----------------------------------------------------------------------
diff --git a/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/sql/DerbySQLEntityStorePerformanceTest.java b/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/sql/DerbySQLEntityStorePerformanceTest.java
index 5906307..09a0331 100644
--- a/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/sql/DerbySQLEntityStorePerformanceTest.java
+++ b/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/sql/DerbySQLEntityStorePerformanceTest.java
@@ -26,15 +26,15 @@ import org.apache.polygene.api.usecase.UsecaseBuilder;
import org.apache.polygene.bootstrap.Assembler;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.entitystore.sql.SQLMapEntityStoreConfiguration;
import org.apache.polygene.entitystore.sql.assembly.DerbySQLEntityStoreAssembler;
-import org.apache.polygene.entitystore.sql.internal.SQLs;
import org.apache.polygene.library.sql.assembly.DataSourceAssembler;
-import org.apache.polygene.library.sql.common.SQLConfiguration;
-import org.apache.polygene.library.sql.common.SQLUtil;
import org.apache.polygene.library.sql.dbcp.DBCPDataSourceServiceAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.performance.entitystore.AbstractEntityStorePerformanceTest;
+import static org.apache.polygene.entitystore.sql.assembly.DerbySQLEntityStoreAssembler.DEFAULT_ENTITYSTORE_IDENTITY;
+
/**
* Performance test for DerbySQLEntityStore.
*/
@@ -88,30 +88,22 @@ public class DerbySQLEntityStorePerformanceTest
{
return;
}
- UnitOfWork uow = this.uowf.newUnitOfWork( UsecaseBuilder.newUsecase(
- "Delete " + getClass().getSimpleName() + " test data" ) );
+ UnitOfWork uow = uowf.newUnitOfWork( UsecaseBuilder.newUsecase(
+ "Delete " + getClass().getSimpleName() + " test data" )
+ );
try
{
- SQLConfiguration config = uow.get( SQLConfiguration.class,
- DerbySQLEntityStoreAssembler.DEFAULT_ENTITYSTORE_IDENTITY );
+ SQLMapEntityStoreConfiguration config = uow.get( SQLMapEntityStoreConfiguration.class,
+ DEFAULT_ENTITYSTORE_IDENTITY );
Connection connection = serviceFinder.findService( DataSource.class ).get().getConnection();
- String schemaName = config.schemaName().get();
- if( schemaName == null )
- {
- schemaName = SQLs.DEFAULT_SCHEMA_NAME;
- }
-
- Statement stmt = null;
- try
+ connection.setAutoCommit( false );
+ try( Statement stmt = connection.createStatement() )
{
- stmt = connection.createStatement();
- stmt.execute( String.format( "DELETE FROM %s." + SQLs.TABLE_NAME, schemaName ) );
+ stmt.execute( String.format( "DELETE FROM %s.%s",
+ config.schemaName().get(),
+ config.entityTableName().get() ) );
connection.commit();
}
- finally
- {
- SQLUtil.closeQuietly( stmt );
- }
}
finally
{
@@ -119,5 +111,4 @@ public class DerbySQLEntityStorePerformanceTest
super.cleanUp();
}
}
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/e3f025e4/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/sql/PostgreSQLEntityStorePerformanceTest.java
----------------------------------------------------------------------
diff --git a/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/sql/PostgreSQLEntityStorePerformanceTest.java b/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/sql/PostgreSQLEntityStorePerformanceTest.java
index e0c2bcc..b1e8a17 100644
--- a/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/sql/PostgreSQLEntityStorePerformanceTest.java
+++ b/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/sql/PostgreSQLEntityStorePerformanceTest.java
@@ -19,12 +19,13 @@ package org.apache.polygene.test.performance.entitystore.sql;
import java.sql.Connection;
import java.sql.Statement;
-import org.junit.Ignore;
+import javax.sql.DataSource;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.api.structure.Application;
import org.apache.polygene.api.structure.Module;
import org.apache.polygene.api.unitofwork.UnitOfWork;
import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
+import org.apache.polygene.api.usecase.UsecaseBuilder;
import org.apache.polygene.bootstrap.ApplicationAssemblerAdapter;
import org.apache.polygene.bootstrap.Assembler;
import org.apache.polygene.bootstrap.AssemblyException;
@@ -32,12 +33,13 @@ import org.apache.polygene.bootstrap.Energy4Java;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
import org.apache.polygene.entitystore.sql.assembly.PostgreSQLEntityStoreAssembler;
-import org.apache.polygene.entitystore.sql.internal.SQLs;
import org.apache.polygene.library.sql.assembly.DataSourceAssembler;
import org.apache.polygene.library.sql.common.SQLConfiguration;
-import org.apache.polygene.library.sql.common.SQLUtil;
import org.apache.polygene.library.sql.dbcp.DBCPDataSourceServiceAssembler;
import org.apache.polygene.test.performance.entitystore.AbstractEntityStorePerformanceTest;
+import org.junit.Ignore;
+
+import static org.apache.polygene.entitystore.sql.assembly.PostgreSQLEntityStoreAssembler.DEFAULT_ENTITYSTORE_IDENTITY;
/**
* Performance test for PostgreSQLEntityStore.
@@ -119,30 +121,20 @@ public class PostgreSQLEntityStorePerformanceTest
Module moduleInstance = application.findModule( "Layer 1", "config" );
UnitOfWorkFactory uowf = moduleInstance.unitOfWorkFactory();
- UnitOfWork uow = uowf.newUnitOfWork();
+ UnitOfWork uow = uowf.newUnitOfWork(
+ UsecaseBuilder.newUsecase( "Delete " + getClass().getSimpleName() + " test data" )
+ );
try
{
- SQLConfiguration config = uow.get( SQLConfiguration.class,
- PostgreSQLEntityStoreAssembler.DEFAULT_ENTITYSTORE_IDENTITY );
- // TODO fix AbstractEntityStorePerformanceTest to extend from AbstractPolygeneTest
- Connection connection = null; // SQLUtil.getConnection( this.serviceLocator );
+ SQLConfiguration config = uow.get( SQLConfiguration.class, DEFAULT_ENTITYSTORE_IDENTITY );
+ Connection connection = serviceFinder.findService( DataSource.class ).get().getConnection();
+ connection.setAutoCommit( false );
String schemaName = config.schemaName().get();
- if( schemaName == null )
- {
- schemaName = SQLs.DEFAULT_SCHEMA_NAME;
- }
-
- Statement stmt = null;
- try
+ try( Statement stmt = connection.createStatement() )
{
- stmt = connection.createStatement();
- stmt.execute( String.format( "DELETE FROM %s." + SQLs.TABLE_NAME, schemaName ) );
+ stmt.execute( String.format( "DROP SCHEMA \"%s\" CASCADE", schemaName ) );
connection.commit();
}
- finally
- {
- SQLUtil.closeQuietly( stmt );
- }
}
finally
{
[05/50] [abbrv] polygene-java git commit: Fixing the Value,
Tranisent and Object templates, so they compile.
Posted by pa...@apache.org.
Fixing the Value, Tranisent and Object templates, so they compile.
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/284fb8ee
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/284fb8ee
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/284fb8ee
Branch: refs/heads/serialization-3.0
Commit: 284fb8eef861f28189397e101a016ee400d8fa16
Parents: a7bdc40
Author: niclas <ni...@spicter.com>
Authored: Sat Mar 11 13:41:20 2017 +0800
Committer: niclas <ni...@spicter.com>
Committed: Sat Mar 11 13:41:20 2017 +0800
----------------------------------------------------------------------
.../DomainLayer/DomainModule/Object.tmpl | 4 +-
.../DomainLayer/DomainModule/Transient.tmpl | 47 ++++++++++++++++++++
.../DomainLayer/DomainModule/Value.tmpl | 2 +-
.../DomainLayer/DomainModule/bootstrap.tmpl | 2 +-
4 files changed, 52 insertions(+), 3 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/284fb8ee/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Object.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Object.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Object.tmpl
index 27d6119..9ff4e00 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Object.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Object.tmpl
@@ -19,8 +19,10 @@
-%>
package <%= packageName %>.model.<%= polygene.current.name %>;
-import org.apache.polygene.api.injection.scope.This
+import org.apache.polygene.api.injection.scope.Structure;
+import org.apache.polygene.api.injection.scope.Uses;
import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.value.ValueBuilderFactory;
public class <%= polygene.current.clazz.name %>
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/284fb8ee/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Transient.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Transient.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Transient.tmpl
new file mode 100644
index 0000000..29f32e2
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Transient.tmpl
@@ -0,0 +1,47 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.model.<%= polygene.current.name %>;
+
+import org.apache.polygene.api.injection.scope.Uses;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.property.Property;
+
+@Mixins( { <%= polygene.current.clazz.name %>.Mixin.class } )
+public interface <%= polygene.current.clazz.name %>
+{
+ Property<String> name(); // Sample hidden property
+
+ // If Property declarations are public, the Mixin must be abstract, because PropertyMixin will implement those methods.
+ abstract class Mixin
+ implements <%= polygene.current.clazz.name %>
+ {
+ // Transients supports @Uses injection
+ //
+ // Socket socket = serverSockete.accept();
+ // TransientBuilder<<%= polygene.current.clazz.name %>> builder = transientBuilderFactory.newTransientBuilder(<%= polygene.current.clazz.name %>.class);
+ // builder.use( socket );
+ // builder.prototype().name().set( name + counter++ );
+ // <%= polygene.current.clazz.name %> <%= polygene.current.clazz.name.toLowerCase() %> = builder.newInstance();
+
+// @Uses
+// private Socket items;
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/284fb8ee/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
index 60e117d..95eed76 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
@@ -19,7 +19,7 @@
-%>
package <%= packageName %>.model.<%= polygene.current.name %>;
-import org.apache.polygene.api.injection.scope.This
+import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.property.Property;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/284fb8ee/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl
index cbab067..3ee206c 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl
@@ -54,7 +54,7 @@ public class <%- firstUpper(polygene.current.name) %>Module
<% } %>
<% if( polygene.current.values ) { %>
<% for( var value in polygene.current.values ) { %>
- <% var v = polygene.current.current[value]; %>
+ <% var v = polygene.current.values[value]; %>
module.values(<%= v.name + ".class" %>)<% if( v.visibility ) {%><%-".visibleIn(" + v.visibility +")"%><% } %>;
<% } %>
<% } %>
[04/50] [abbrv] polygene-java git commit: Restructuring of the yeoman
generator,
to make it more easy to work with and demand naming in extensions to be
unified.
Posted by pa...@apache.org.
Restructuring of the yeoman generator, to make it more easy to work with and demand naming in extensions to be unified.
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/a7bdc408
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/a7bdc408
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/a7bdc408
Branch: refs/heads/serialization-3.0
Commit: a7bdc40862e9a9865bd660bedb9aa91791915b5a
Parents: 46e26e6
Author: niclas <ni...@spicter.com>
Authored: Sat Mar 11 09:00:54 2017 +0800
Committer: niclas <ni...@spicter.com>
Committed: Sat Mar 11 09:44:05 2017 +0800
----------------------------------------------------------------------
.../ElasticSearchIndexingAssembler.java | 26 ++
libraries/shiro-core/src/docs/shiro.txt | 4 +
tools/generator-polygene/app/index.js | 325 ++++++-------------
.../app/templates/CodahaleModule/bootstrap.tmpl | 50 ---
.../app/templates/ConfigModule/bootstrap.tmpl | 41 ---
.../ConfigModule/bootstrap.tmpl | 41 +++
.../ConfigurationLayer/ConfigModule/module.js | 8 +
.../app/templates/ConfigurationLayer/layer.js | 10 +
.../RestApiModule/DefaultEnroler.tmpl | 52 +++
.../RestApiModule/DefaultVerifier.tmpl | 46 +++
.../RestApiModule/NullEnroler.tmpl | 32 ++
.../RestApiModule/NullVerifier.tmpl | 34 ++
.../RestApiModule/bootstrap.tmpl | 56 ++++
.../ConnectivityLayer/RestApiModule/module.js | 25 ++
.../app/templates/ConnectivityLayer/layer.js | 10 +
.../app/templates/CrudModule/bootstrap.tmpl | 38 ---
.../DomainLayer/CrudModule/bootstrap.tmpl | 38 +++
.../templates/DomainLayer/CrudModule/module.js | 9 +
.../DomainLayer/DomainModule/Crud.tmpl | 41 +++
.../DomainLayer/DomainModule/Entity.tmpl | 41 +++
.../DomainLayer/DomainModule/Object.tmpl | 33 ++
.../DomainLayer/DomainModule/Service.tmpl | 36 ++
.../DomainLayer/DomainModule/Value.tmpl | 41 +++
.../DomainLayer/DomainModule/bootstrap.tmpl | 87 +++++
.../DomainLayer/DomainModule/module.js | 42 +++
.../SecurityModule/CryptoConfiguration.tmpl | 37 +++
.../SecurityModule/CryptoException.tmpl | 28 ++
.../SecurityModule/CryptoService.tmpl | 106 ++++++
.../EncryptedStringPropertyConcern.tmpl | 41 +++
...ntityStoreBackedSecurityRepositoryMixin.tmpl | 60 ++++
.../DomainLayer/SecurityModule/Group.tmpl | 41 +++
.../SecurityModule/RealmService.tmpl | 48 +++
.../SecurityModule/SecurityRepository.tmpl | 63 ++++
.../DomainLayer/SecurityModule/User.tmpl | 51 +++
.../DomainLayer/SecurityModule/bootstrap.tmpl | 53 +++
.../DomainLayer/SecurityModule/module.js | 28 ++
.../app/templates/DomainLayer/bootstrap.tmpl | 4 +-
.../app/templates/DomainLayer/layer.js | 10 +
.../app/templates/DomainModule/Crud.tmpl | 41 ---
.../app/templates/DomainModule/Entity.tmpl | 41 ---
.../app/templates/DomainModule/Object.tmpl | 33 --
.../app/templates/DomainModule/Service.tmpl | 36 --
.../app/templates/DomainModule/Value.tmpl | 41 ---
.../app/templates/DomainModule/bootstrap.tmpl | 85 -----
.../FileConfigurationModule/bootstrap.tmpl | 41 ---
.../app/templates/Heroes/Hero.tmpl | 28 --
.../app/templates/Heroes/app.tmpl | 103 ------
.../app/templates/Heroes/bootstrap.tmpl | 63 ----
.../app/templates/Heroes/web.tmpl | 54 ---
.../Heroes/webapp/app/app.component.css | 34 --
.../Heroes/webapp/app/app.component.js | 41 ---
.../Heroes/webapp/app/app.component.js.map | 1 -
.../Heroes/webapp/app/app.component.ts | 37 ---
.../Heroes/webapp/app/dashboard.component.css | 67 ----
.../Heroes/webapp/app/dashboard.component.html | 15 -
.../Heroes/webapp/app/dashboard.component.js | 38 ---
.../webapp/app/dashboard.component.js.map | 1 -
.../Heroes/webapp/app/dashboard.component.ts | 31 --
.../Heroes/webapp/app/hero-detail.component.css | 36 --
.../webapp/app/hero-detail.component.html | 16 -
.../Heroes/webapp/app/hero-detail.component.js | 37 ---
.../webapp/app/hero-detail.component.js.map | 1 -
.../Heroes/webapp/app/hero-detail.component.ts | 34 --
.../app/templates/Heroes/webapp/app/hero.js | 13 -
.../app/templates/Heroes/webapp/app/hero.js.map | 1 -
.../templates/Heroes/webapp/app/hero.service.js | 30 --
.../Heroes/webapp/app/hero.service.js.map | 1 -
.../templates/Heroes/webapp/app/hero.service.ts | 22 --
.../app/templates/Heroes/webapp/app/hero.ts | 11 -
.../Heroes/webapp/app/heroes.component.css | 66 ----
.../Heroes/webapp/app/heroes.component.html | 21 --
.../Heroes/webapp/app/heroes.component.js | 42 ---
.../Heroes/webapp/app/heroes.component.js.map | 1 -
.../Heroes/webapp/app/heroes.component.ts | 39 ---
.../app/templates/Heroes/webapp/app/main.js | 15 -
.../app/templates/Heroes/webapp/app/main.js.map | 1 -
.../app/templates/Heroes/webapp/app/main.ts | 16 -
.../templates/Heroes/webapp/app/mock-heroes.js | 19 --
.../Heroes/webapp/app/mock-heroes.js.map | 1 -
.../templates/Heroes/webapp/app/mock-heroes.ts | 21 --
.../app/templates/Heroes/webapp/index.html | 41 ---
.../app/templates/Heroes/webapp/styles.css | 149 ---------
.../CachingModule/bootstrap.tmpl | 51 +++
.../InfrastructureLayer/CachingModule/module.js | 11 +
.../FileConfigurationModule/bootstrap.tmpl | 41 +++
.../FileConfigurationModule/module.js | 8 +
.../IndexingModule/bootstrap.tmpl | 52 +++
.../IndexingModule/module.js | 8 +
.../MetricsModule/bootstrap.tmpl | 48 +++
.../InfrastructureLayer/MetricsModule/module.js | 10 +
.../SerializationModule/bootstrap.tmpl | 43 +++
.../SerializationModule/module.js | 8 +
.../StorageModule/bootstrap.tmpl | 51 +++
.../InfrastructureLayer/StorageModule/module.js | 8 +
.../InfrastructureLayer/bootstrap.tmpl | 9 +-
.../app/templates/InfrastructureLayer/layer.js | 10 +
.../JacksonSerializationModule/bootstrap.tmpl | 43 ---
.../templates/NoCachingModule/bootstrap.tmpl | 46 ---
.../templates/RdfIndexingModule/bootstrap.tmpl | 50 ---
.../HardcodedSecurityRepositoryMixin.tmpl | 54 ---
.../RestApiModule/SecurityRepository.tmpl | 36 --
.../templates/RestApiModule/SimpleEnroler.tmpl | 52 ---
.../templates/RestApiModule/SimpleVerifier.tmpl | 46 ---
.../app/templates/RestApiModule/bootstrap.tmpl | 56 ----
.../SecurityModule/SecurityRepository.tmpl | 35 --
.../app/templates/SecurityModule/bootstrap.tmpl | 46 ---
.../templates/SolrIndexingModule/bootstrap.tmpl | 49 ---
.../app/templates/StorageModule/bootstrap.tmpl | 51 ---
.../app/templates/buildtool/build.js | 22 ++
.../templates/buildtool/gradle-bootstrap.tmpl | 8 +
.../app/templates/buildtool/settings.tmpl | 2 +-
111 files changed, 1768 insertions(+), 2387 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ElasticSearchIndexingAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ElasticSearchIndexingAssembler.java b/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ElasticSearchIndexingAssembler.java
new file mode 100644
index 0000000..d13e790
--- /dev/null
+++ b/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ElasticSearchIndexingAssembler.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.index.elasticsearch.assembly;
+
+/**
+ * This is a dummy Assembler to support the Yeoman Polygene Generator, which require naming conventions for
+ * the systems that it supports.
+ */
+public class ElasticSearchIndexingAssembler extends ESFilesystemIndexQueryAssembler
+{
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/libraries/shiro-core/src/docs/shiro.txt
----------------------------------------------------------------------
diff --git a/libraries/shiro-core/src/docs/shiro.txt b/libraries/shiro-core/src/docs/shiro.txt
index 38c826f..fd35a05 100644
--- a/libraries/shiro-core/src/docs/shiro.txt
+++ b/libraries/shiro-core/src/docs/shiro.txt
@@ -242,3 +242,7 @@ contribute.
== Logging ==
All code from this library use the `org.apache.polygene.library.shiro` logger.
+
+
+
+
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/index.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/index.js b/tools/generator-polygene/app/index.js
index 7ab5505..a13be9d 100644
--- a/tools/generator-polygene/app/index.js
+++ b/tools/generator-polygene/app/index.js
@@ -21,6 +21,7 @@
var generators = require('yeoman-generator');
var fs = require('fs');
+
var polygene = {};
module.exports = generators.Base.extend(
@@ -43,21 +44,9 @@ module.exports = generators.Base.extend(
polygene.entitystore = polygene.entitystore ? polygene.entitystore : null;
polygene.caching = polygene.caching ? polygene.caching : null;
polygene.serialization = polygene.serialization ? polygene.serialization : null;
- console.log(JSON.stringify(polygene,null,4));
- }
- else {
- polygene = {
- name: firstUpper(this.appname),
- packageName: "com.acme." + this.appname,
- singletonApp: false,
- entitystore: null,
- indexing: null,
- serialization: null,
- caching: null,
- features: ['rest api'],
- modules: {}
- };
+ console.log(JSON.stringify(polygene, null, 4));
}
+ assignFunctions(polygene);
},
prompting: function () {
@@ -71,13 +60,13 @@ module.exports = generators.Base.extend(
type: 'input',
name: 'name',
message: 'Your project name',
- default: polygene.name
+ default: polygene.name ? polygene.name : firstUpper(this.appname)
},
{
type: 'input',
name: 'packageName',
message: 'Java package name',
- default: polygene.packageName
+ default: polygene.packageName ? polygene.packageName : "com.acme"
},
{
type: 'list',
@@ -102,7 +91,7 @@ module.exports = generators.Base.extend(
'SQLite'
],
message: 'Which entity store do you want to use?',
- default: polygene.entitystore
+ default: polygene.entitystore ? polygene.entitystore : "Memory"
},
{
type: 'list',
@@ -113,17 +102,19 @@ module.exports = generators.Base.extend(
'Solr',
'SQL'
],
- message: 'Which indexing system do you want to use?'
+ message: 'Which indexing system do you want to use?',
+ default: polygene.indexing ? polygene.indexing : "Rdf"
},
{
type: 'list',
name: 'caching',
choices: [
- 'none',
- 'memcache',
- 'ehcache'
+ 'None',
+ 'Memcache',
+ 'EhCache'
],
- message: 'Which caching system do you want to use?'
+ message: 'Which caching system do you want to use?',
+ default: polygene.caching ? polygene.caching : "None"
},
{
type: 'list',
@@ -133,27 +124,40 @@ module.exports = generators.Base.extend(
// 'Johnzon',
'Stax'
],
- message: 'Which serialization system do you want to use?'
+ message: 'Which serialization system do you want to use?',
+ default: polygene.serialization ? polygene.serialization : "Jackson"
},
{
type: 'list',
name: 'metrics',
choices: [
- 'none',
- 'codahale'
+ 'None',
+ 'Codahale'
],
- message: 'Which metrics capturing system do you want to use?'
+ message: 'Which metrics capturing system do you want to use?',
+ default: polygene.metrics ? polygene.metrics : "None"
},
{
type: 'checkbox',
name: 'features',
choices: [
- 'rest api',
- // 'jmx',
- // 'version migration',
- 'sample (heroes) web application'
+ 'rest api'
+ , 'security'
+ // ,'version migration'
+ // ,'logging'
+ // ,'jmx'
+ // ,'circuit breakers'
+ // ,'file transactions'
+ // ,'spring integration'
+ // ,'servlet deployment'
+ // ,'osgi support'
+ // ,'alarms'
+ // ,'scheduling'
+ // ,'groovy mixins'
+ // ,'javascript mixins'
],
- message: 'Other features?'
+ message: 'Other features?',
+ default: polygene.features ? polygene.features : []
}
]
).then(function (answers) {
@@ -170,73 +174,26 @@ module.exports = generators.Base.extend(
polygene.serialization = answers.serialization;
polygene.metrics = answers.metrics;
polygene.packageName = answers.packageName;
- answers.features.forEach(function (f) {
- polygene.features.push(f);
- });
+ polygene.features = answers.features;
polygene.javaPackageDir = polygene.javaPackageDir ? polygene.javaPackageDir : polygene.packageName.replace(/[.]/g, '/');
polygene.singletonApp = false;
- if (hasFeature('sample (heroes) web application')) {
- polygene.features.push('rest api');
- }
}.bind(this)
);
}
},
writing: function () {
- copyPolygeneBootstrap(this, "config", "ConfigurationLayer", !polygene.singeltonApp);
- copyPolygeneBootstrap(this, "infrastructure", "InfrastructureLayer", !polygene.singeltonApp);
- copyPolygeneBootstrap(this, "domain", "DomainLayer", !polygene.singeltonApp);
- copyPolygeneBootstrap(this, "connectivity", "ConnectivityLayer", !polygene.singeltonApp);
-
- copyPolygeneBootstrap(this, "config", "ConfigModule", true);
-
- copyPolygeneBootstrap(this, "infrastructure", "FileConfigurationModule", true);
-
- copyEntityStore(this, polygene.entitystore);
-
- copyPolygeneBootstrap(this, "infrastructure", "RdfIndexingModule", hasIndexing('Rdf'));
- copyPolygeneBootstrap(this, "infrastructure", "ElasticSearchIndexingModule", hasIndexing('Elasticsearch'));
- copyPolygeneBootstrap(this, "infrastructure", "SolrIndexingModule", hasIndexing('Solr'));
- copyPolygeneBootstrap(this, "infrastructure", "SqlIndexingModule", hasIndexing('Sql'));
-
- copyPolygeneBootstrap(this, "infrastructure", "NoCachingModule", hasCaching('none'));
- copyPolygeneBootstrap(this, "infrastructure", "MemcacheCachingModule", hasCaching('Memcache'));
- copyPolygeneBootstrap(this, "infrastructure", "EhCacheCachingModule", hasCaching('Ehcache'));
-
- copyPolygeneBootstrap(this, "infrastructure", "JacksonSerializationModule", hasSerialization('Jackson'));
- copyPolygeneBootstrap(this, "infrastructure", "StaxSerializationModule", hasSerialization('Stax'));
- copyPolygeneBootstrap(this, "infrastructure", "OrgJsonSerializationModule", hasSerialization('Orgjson'));
-
- copyPolygeneBootstrap(this, "connectivity", "RestApiModule", hasFeature('rest api'));
- copyPolygeneBootstrap(this, "infrastructure", "ReindexerModule", hasFeature('reindexer'));
- copyPolygeneBootstrap(this, "infrastructure", "MetricsModule", hasFeature('metrics'));
- copyPolygeneBootstrap(this, "infrastructure", "JmxModule", hasFeature('jmx'));
- copyPolygeneBootstrap(this, "infrastructure", "MigrationModule", hasFeature('version migration'));
-
- copyPolygeneBootstrap(this, "domain", "CrudModule", true);
- var ctx = this;
- Object.keys(polygene.modules).forEach(function (moduleName, index) {
- copyPolygeneDomainModule(ctx, moduleName, polygene.modules[moduleName]);
+ polygene.ctx = this;
+ fs.readdir(__dirname + "/templates", function (err, files) {
+ files.forEach(function (directory) {
+ if (directory.endsWith("Layer")) {
+ var layer = require(__dirname + '/templates/' + directory + '/layer.js');
+ layer.write(polygene);
+ }
+ });
});
- copyPolygeneBootstrap(this, "domain", "CrudModule", hasFeature('rest api'));
- // copyPolygeneBootstrap(this, "domain", "SecurityModule", true);
- copyHeroesSampleApp(this);
- copyPolygeneDomain(this, "security", "RestApiModule", "SecurityRepository", hasFeature('rest api'));
-
- copyRestFeature(this, hasFeature('rest api'));
-
- copyTemplate(this, 'buildtool/gradle-app.tmpl', 'app/build.gradle');
- copyTemplate(this, 'buildtool/gradle-bootstrap.tmpl', 'bootstrap/build.gradle');
- copyTemplate(this, 'buildtool/gradle-model.tmpl', 'model/build.gradle');
- copyTemplate(this, 'buildtool/gradle-rest.tmpl', 'rest/build.gradle');
- copyTemplate(this, 'buildtool/gradle-root.tmpl', 'build.gradle');
- copyTemplate(this, 'buildtool/settings.tmpl', 'settings.gradle');
- copyTemplate(this, 'buildtool/gradlew.tmpl', 'gradlew');
- copyTemplate(this, 'buildtool/gradlew-bat.tmpl', 'gradlew.bat');
- this.fs.copy(this.templatePath('buildtool/gradle-wrapper.jar_'), this.destinationPath('gradle/wrapper/gradle-wrapper.jar'));
- this.fs.copy(this.templatePath('buildtool/gradle-wrapper.properties_'), this.destinationPath('gradle/wrapper/gradle-wrapper.properties'));
-
+ var buildToolChain = require(__dirname + '/templates/buildtool/build.js');
+ buildToolChain.write(polygene);
if (this.options.export != null) {
exportModel(this, "exported-model.json");
}
@@ -244,142 +201,6 @@ module.exports = generators.Base.extend(
}
);
-function copyPolygeneBootstrap(ctx, layer, moduleName, condition) {
- if (condition) {
- copyTemplate(ctx,
- moduleName + '/bootstrap.tmpl',
- 'bootstrap/src/main/java/' + polygene.javaPackageDir + '/bootstrap/' + layer + '/' + moduleName + '.java');
- }
-}
-
-function copyEntityStore(ctx, entityStoreName) {
- copyTemplate(ctx,
- 'StorageModule/bootstrap.tmpl',
- 'bootstrap/src/main/java/' + polygene.javaPackageDir + '/bootstrap/infrastructure/' + entityStoreName + 'StorageModule.java');
-}
-
-function copyPolygeneApp(ctx, name, condition) {
- if (condition) {
- copyTemplate(ctx,
- name + '/bootstrap.tmpl',
- 'bootstrap/src/main/java/' + polygene.javaPackageDir + '/bootstrap/' + name + 'ApplicationAssembler.java');
-
- copyTemplate(ctx,
- name + '/app.tmpl',
- 'app/src/main/java/' + polygene.javaPackageDir + '/app/' + name + '.java');
-
- copyTemplate(ctx,
- name + '/webapp/',
- 'app/src/main/webapp/');
- }
-}
-
-function copyPolygeneDomain(ctx, model, module, clazz, condition) {
- if (condition) {
- copyTemplate(ctx,
- module + '/' + clazz + '.tmpl',
- 'model/src/main/java/' + polygene.javaPackageDir + '/model/' + model + '/' + clazz + '.java');
- }
-}
-
-function copyPolygeneDomainModule(ctx, moduleName, moduleDef) {
- var clazz = firstUpper(moduleName) + "Module";
- polygene.current = moduleDef;
- polygene.current.name = moduleName;
- copyTemplate(ctx,
- 'DomainModule/bootstrap.tmpl',
- 'bootstrap/src/main/java/' + polygene.javaPackageDir + '/bootstrap/domain/' + clazz + '.java');
- for (var idx1 in moduleDef.cruds) {
- if (moduleDef.cruds.hasOwnProperty(idx1)) {
- polygene.current.clazz = moduleDef.cruds[idx1];
- copyTemplate(ctx,
- 'DomainModule/Crud.tmpl',
- 'model/src/main/java/' + polygene.javaPackageDir + '/model/' + moduleName + '/' + moduleDef.cruds[idx1].name + '.java');
- }
- }
- for (var idx2 in moduleDef.values) {
- if (moduleDef.values.hasOwnProperty(idx2)) {
- polygene.current.clazz = moduleDef.values[idx2];
- copyTemplate(ctx,
- 'DomainModule/Value.tmpl',
- 'model/src/main/java/' + polygene.javaPackageDir + '/model/' + moduleName + '/' + moduleDef.values[idx2].name + '.java');
- }
- }
- for (var idx3 in moduleDef.entities) {
- if (moduleDef.entities.hasOwnProperty(idx3)) {
- polygene.current.clazz = moduleDef.entities[idx2];
- copyTemplate(ctx,
- 'DomainModule/Entity.tmpl',
- 'model/src/main/java/' + polygene.javaPackageDir + '/model/' + moduleName + '/' + moduleDef.entities[idx3].name + '.java');
- }
- }
- for (var idx4 in moduleDef.transients) {
- if (moduleDef.transients.hasOwnProperty(idx4)) {
- polygene.current.clazz = moduleDef.transients[idx3];
- copyTemplate(ctx,
- 'DomainModule/Transient.tmpl',
- 'model/src/main/java/' + polygene.javaPackageDir + '/model/' + moduleName + '/' + moduleDef.transients[idx4].name + '.java');
- }
- }
- for (var idx5 in moduleDef.objects) {
- if (moduleDef.objects.hasOwnProperty(idx5)) {
- polygene.current.clazz = moduleDef.objects[idx5];
- copyTemplate(ctx,
- 'DomainModule/Object.tmpl',
- 'model/src/main/java/' + polygene.javaPackageDir + '/model/' + moduleName + '/' + moduleDef.objects[idx5].name + '.java');
- }
- }
- for (var idx6 in moduleDef.services) {
- if (moduleDef.services.hasOwnProperty(idx6)) {
- polygene.current.clazz = moduleDef.services[idx6];
- copyTemplate(ctx,
- 'DomainModule/Service.tmpl',
- 'model/src/main/java/' + polygene.javaPackageDir + '/model/' + moduleName + '/' + moduleDef.services[idx6].name + '.java');
- }
- }
-}
-
-function copyRestFeature(ctx, condition) {
- if (condition) {
- copyPolygeneBootstrap(ctx, "domain", "SecurityModule", true);
-
- copyTemplate(ctx,
- 'RestApiModule/SimpleEnroler.tmpl',
- 'rest/src/main/java/' + polygene.javaPackageDir + '/rest/security/SimpleEnroler.java');
-
- copyTemplate(ctx,
- 'RestApiModule/SimpleVerifier.tmpl',
- 'rest/src/main/java/' + polygene.javaPackageDir + '/rest/security/SimpleVerifier.java');
-
- copyTemplate(ctx,
- 'RestApiModule/HardcodedSecurityRepositoryMixin.tmpl',
- 'model/src/main/java/' + polygene.javaPackageDir + '/model/security/HardcodedSecurityRepositoryMixin.java');
- }
-}
-
-function copyHeroesSampleApp(ctx) {
- copyPolygeneDomain(ctx, "heroes", "Heroes", "Hero", hasFeature('sample (heroes) web application'));
- copyPolygeneApp(ctx, "Heroes", hasFeature('sample (heroes) web application'));
- copyTemplate(ctx,
- 'Heroes/web.tmpl',
- 'app/src/main/webapp/WEB-INF/web.xml');
-}
-
-function copyTemplate(ctx, from, to) {
- ctx.fs.copyTpl(
- ctx.templatePath(from),
- ctx.destinationPath(to),
- {
- packageName: polygene.packageName,
- hasFeature: hasFeature,
- hasEntityStore: hasEntityStore,
- hasIndexing: hasIndexing,
- hasCaching: hasCaching,
- firstUpper: firstUpper,
- polygene: polygene
- }
- );
-}
function hasEntityStore(esType) {
return polygene.entitystore === esType;
@@ -413,3 +234,57 @@ function exportModel(ctx, filename) {
delete polygene.current;
return fs.writeFileSync(filename, JSON.stringify(polygene, null, 4) + "\n", 'utf8');
}
+
+function assignFunctions(polygene) {
+
+ polygene.hasFeature = function (feature) {
+ console.log(polygene.features);
+ return polygene.features.indexOf(feature) >= 0;
+ };
+
+ polygene.copyTemplate = function (ctx, from, to) {
+ ctx.fs.copyTpl(
+ ctx.templatePath(from),
+ ctx.destinationPath(to),
+ {
+ packageName: polygene.packageName,
+ hasFeature: hasFeature,
+ hasEntityStore: hasEntityStore,
+ hasIndexing: hasIndexing,
+ hasCaching: hasCaching,
+ firstUpper: firstUpper,
+ polygene: polygene
+ }
+ );
+ };
+
+ polygene.copyPolygeneBootstrap = function (ctx, layer, moduleName, condition) {
+ if (condition) {
+ copyTemplate(ctx,
+ moduleName + '/bootstrap.tmpl',
+ 'bootstrap/src/main/java/' + polygene.javaPackageDir + '/bootstrap/' + layer + '/' + moduleName + '.java');
+ }
+ };
+
+ polygene.copyEntityStore = function (ctx, entityStoreName) {
+ copyTemplate(ctx,
+ 'StorageModule/bootstrap.tmpl',
+ 'bootstrap/src/main/java/' + polygene.javaPackageDir + '/bootstrap/infrastructure/' + entityStoreName + 'StorageModule.java');
+ };
+
+ polygene.copyModules = function (dirname) {
+ fs.readdir(dirname, function (err, files) {
+ if (files !== undefined) {
+ files.forEach(function (directory) {
+ if (directory.endsWith("Module")) {
+ var module = require(dirname + "/" + directory + '/module.js');
+ module.write(polygene);
+ }
+ });
+ }
+ });
+ };
+ polygene.firstUpper = function (text) {
+ return text.charAt(0).toUpperCase() + text.substring(1);
+ };
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/CodahaleModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/CodahaleModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/CodahaleModule/bootstrap.tmpl
deleted file mode 100644
index ec826a2..0000000
--- a/tools/generator-polygene/app/templates/CodahaleModule/bootstrap.tmpl
+++ /dev/null
@@ -1,50 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.bootstrap.infrastructure;
-
-import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.LayerAssembly;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.bootstrap.layered.ModuleAssembler;
-import org.apache.polygene.metrics.codehale.assembly.CodahaleMetricsAssembler;
-import org.apache.polygene.library.rdf.repository.NativeConfiguration;
-
-public class RdfIndexingModule
- implements ModuleAssembler
-{
- public static final String NAME = "Rdf Indexing Module";
- private final ModuleAssembly configModule;
-
- public RdfIndexingModule( ModuleAssembly configModule )
- {
- this.configModule = configModule;
- }
-
- @Override
- public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
- throws AssemblyException
- {
- configModule.entities( NativeConfiguration.class ).visibleIn( Visibility.application );
- new RdfNativeSesameStoreAssembler(Visibility.application, Visibility.module).assemble( module );
- return module;
- }
-}
-
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/ConfigModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConfigModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/ConfigModule/bootstrap.tmpl
deleted file mode 100644
index b152d3a..0000000
--- a/tools/generator-polygene/app/templates/ConfigModule/bootstrap.tmpl
+++ /dev/null
@@ -1,41 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.bootstrap.config;
-
-import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.LayerAssembly;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.bootstrap.layered.ModuleAssembler;
-import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
-import org.apache.polygene.valueserialization.jackson.JacksonValueSerializationAssembler;
-
-public class ConfigModule
- implements ModuleAssembler
-{
- @Override
- public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
- throws AssemblyException
- {
- module.services( MemoryEntityStoreService.class ).visibleIn( Visibility.layer );
- new JacksonValueSerializationAssembler().visibleIn( Visibility.layer ).assemble( module );
- return module;
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl
new file mode 100644
index 0000000..b152d3a
--- /dev/null
+++ b/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl
@@ -0,0 +1,41 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.bootstrap.config;
+
+import org.apache.polygene.api.common.Visibility;
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.LayerAssembly;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.bootstrap.layered.ModuleAssembler;
+import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
+import org.apache.polygene.valueserialization.jackson.JacksonValueSerializationAssembler;
+
+public class ConfigModule
+ implements ModuleAssembler
+{
+ @Override
+ public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
+ throws AssemblyException
+ {
+ module.services( MemoryEntityStoreService.class ).visibleIn( Visibility.layer );
+ new JacksonValueSerializationAssembler().visibleIn( Visibility.layer ).assemble( module );
+ return module;
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/module.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/module.js b/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/module.js
new file mode 100644
index 0000000..690f715
--- /dev/null
+++ b/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/module.js
@@ -0,0 +1,8 @@
+module.exports = {
+
+ write: function (p) {
+ p.copyTemplate(p.ctx,
+ 'ConfigurationLayer/ConfigModule/bootstrap.tmpl',
+ 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/config/ConfigModule.java');
+ }
+};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/ConfigurationLayer/layer.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConfigurationLayer/layer.js b/tools/generator-polygene/app/templates/ConfigurationLayer/layer.js
new file mode 100644
index 0000000..06a3e31
--- /dev/null
+++ b/tools/generator-polygene/app/templates/ConfigurationLayer/layer.js
@@ -0,0 +1,10 @@
+
+module.exports = {
+
+ write: function (p) {
+ p.copyTemplate(p.ctx,
+ 'ConfigurationLayer/bootstrap.tmpl',
+ 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/config/ConfigurationLayer.java');
+ p.copyModules(__dirname );
+ }
+};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/DefaultEnroler.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/DefaultEnroler.tmpl b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/DefaultEnroler.tmpl
new file mode 100644
index 0000000..c469137
--- /dev/null
+++ b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/DefaultEnroler.tmpl
@@ -0,0 +1,52 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.rest.security;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.polygene.api.injection.scope.Service;
+import org.apache.polygene.api.injection.scope.Uses;
+import org.restlet.Application;
+import org.restlet.data.ClientInfo;
+import org.restlet.security.Enroler;
+import org.restlet.security.Role;
+import <%= packageName %>.model.security.SecurityRepository;
+
+
+public class DefaultEnroler
+ implements Enroler
+{
+ @Service
+ private SecurityRepository repository;
+
+ @Uses
+ private Application application;
+
+ @Override
+ public void enrole( ClientInfo clientInfo )
+ {
+ org.restlet.security.User user = clientInfo.getUser();
+ String name = user.getName();
+ List<String> roleList = repository.findRoleNamesOfUser( name );
+ List<Role> restletRoles = new ArrayList<>();
+ roleList.stream().map( roleName -> Role.get( application, roleName ) );
+ clientInfo.setRoles( restletRoles );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/DefaultVerifier.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/DefaultVerifier.tmpl b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/DefaultVerifier.tmpl
new file mode 100644
index 0000000..256b39d
--- /dev/null
+++ b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/DefaultVerifier.tmpl
@@ -0,0 +1,46 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.rest.security;
+
+import org.apache.polygene.api.injection.scope.Service;
+import org.restlet.security.SecretVerifier;
+import org.restlet.security.Verifier;
+import <%= packageName %>.model.security.SecurityRepository;
+
+public class DefaultVerifier extends SecretVerifier
+ implements Verifier
+{
+ @Service
+ private SecurityRepository repository;
+
+ @Override
+ public int verify( String user, char[] secret )
+ {
+ if( user == null || secret == null )
+ {
+ return RESULT_UNKNOWN;
+ }
+ if( repository.verifyPassword( user, String.valueOf( secret ) ) )
+ {
+ return RESULT_VALID;
+ }
+ return RESULT_INVALID;
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/NullEnroler.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/NullEnroler.tmpl b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/NullEnroler.tmpl
new file mode 100644
index 0000000..8076289
--- /dev/null
+++ b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/NullEnroler.tmpl
@@ -0,0 +1,32 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.rest.security;
+
+import org.restlet.data.ClientInfo;
+import org.restlet.security.Enroler;
+
+public class NullEnroler
+ implements Enroler
+{
+ @Override
+ public void enrole( ClientInfo clientInfo )
+ {
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/NullVerifier.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/NullVerifier.tmpl b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/NullVerifier.tmpl
new file mode 100644
index 0000000..e7af254
--- /dev/null
+++ b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/NullVerifier.tmpl
@@ -0,0 +1,34 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.rest.security;
+
+import org.restlet.security.SecretVerifier;
+import org.restlet.security.Verifier;
+
+public class NullVerifier extends SecretVerifier
+ implements Verifier
+{
+
+ @Override
+ public int verify( String user, char[] secret )
+ {
+ return RESULT_VALID;
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/bootstrap.tmpl
new file mode 100644
index 0000000..d2ad313
--- /dev/null
+++ b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/bootstrap.tmpl
@@ -0,0 +1,56 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.bootstrap.connectivity;
+
+<% if( hasFeature('security') ) { %>
+import <%= packageName %>.rest.security.DefaultEnroler;
+import <%= packageName %>.rest.security.DefaultVerifier;
+<% } else { %>
+import <%= packageName %>.rest.security.NullEnroler;
+import <%= packageName %>.rest.security.NullVerifier;
+<% } %>
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.LayerAssembly;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.bootstrap.layered.ModuleAssembler;
+import org.apache.polygene.library.restlet.assembly.RestletCrudConnectivityAssembler;
+import org.apache.polygene.library.restlet.resource.EntryPoint;
+
+public class RestApiModule
+ implements ModuleAssembler
+{
+ public static String NAME;
+
+ @Override
+ public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
+ throws AssemblyException
+ {
+<% if( hasFeature('security') ) { %>
+ module.objects( DefaultVerifier.class, DefaultEnroler.class);
+<% } else {%>
+ module.objects( NullVerifier.class, NullEnroler.class);
+<% } %>
+ new RestletCrudConnectivityAssembler().assemble( module );
+ module.values( EntryPoint.class );
+ module.values( /* add value types */ );
+ module.services( /* add services */ );
+ return module;
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/module.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/module.js b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/module.js
new file mode 100644
index 0000000..8524da3
--- /dev/null
+++ b/tools/generator-polygene/app/templates/ConnectivityLayer/RestApiModule/module.js
@@ -0,0 +1,25 @@
+
+module.exports = {
+
+ write: function (p) {
+ if (p.hasFeature("rest api")) {
+ p.copyTemplate(p.ctx,
+ 'ConnectivityLayer/RestApiModule/bootstrap.tmpl',
+ 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/connectivity/RestApiModule.java');
+ if (p.hasFeature("security")) {
+ copyFile(p, "DefaultEnroler");
+ copyFile(p, "DefaultVerifier");
+ }
+ else {
+ copyFile(p, "NullEnroler");
+ copyFile(p, "NullVerifier");
+ }
+ }
+ }
+};
+
+function copyFile(p, clazz) {
+ p.copyTemplate(p.ctx,
+ 'ConnectivityLayer/RestApiModule/' + clazz + '.tmpl',
+ 'rest/src/main/java/' + p.javaPackageDir + '/rest/security/' + clazz + '.java');
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/ConnectivityLayer/layer.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConnectivityLayer/layer.js b/tools/generator-polygene/app/templates/ConnectivityLayer/layer.js
new file mode 100644
index 0000000..6a0e9b3
--- /dev/null
+++ b/tools/generator-polygene/app/templates/ConnectivityLayer/layer.js
@@ -0,0 +1,10 @@
+
+module.exports = {
+
+ write: function (p) {
+ p.copyTemplate(p.ctx,
+ 'ConnectivityLayer/bootstrap.tmpl',
+ 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/connectivity/ConnectivityLayer.java');
+ p.copyModules(__dirname );
+ }
+};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/CrudModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/CrudModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/CrudModule/bootstrap.tmpl
deleted file mode 100644
index 0877723..0000000
--- a/tools/generator-polygene/app/templates/CrudModule/bootstrap.tmpl
+++ /dev/null
@@ -1,38 +0,0 @@
-<%#
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
--%>
-package <%= packageName %>.bootstrap.domain;
-
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.LayerAssembly;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.bootstrap.layered.ModuleAssembler;
-import org.apache.polygene.library.restlet.assembly.CrudServiceAssembler;
-
-public class CrudModule
- implements ModuleAssembler
-{
- @Override
- public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
- throws AssemblyException
- {
- new CrudServiceAssembler().assemble( module );
- return module;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/CrudModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/CrudModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/DomainLayer/CrudModule/bootstrap.tmpl
new file mode 100644
index 0000000..0877723
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/CrudModule/bootstrap.tmpl
@@ -0,0 +1,38 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.bootstrap.domain;
+
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.LayerAssembly;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.bootstrap.layered.ModuleAssembler;
+import org.apache.polygene.library.restlet.assembly.CrudServiceAssembler;
+
+public class CrudModule
+ implements ModuleAssembler
+{
+ @Override
+ public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
+ throws AssemblyException
+ {
+ new CrudServiceAssembler().assemble( module );
+ return module;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/CrudModule/module.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/CrudModule/module.js b/tools/generator-polygene/app/templates/DomainLayer/CrudModule/module.js
new file mode 100644
index 0000000..acc509a
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/CrudModule/module.js
@@ -0,0 +1,9 @@
+
+module.exports = {
+
+ write: function (p) {
+ p.copyTemplate(p.ctx,
+ 'DomainLayer/CrudModule/bootstrap.tmpl',
+ 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/domain/CrudModule.java');
+ }
+};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl
new file mode 100644
index 0000000..95eed76
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl
@@ -0,0 +1,41 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.model.<%= polygene.current.name %>;
+
+import org.apache.polygene.api.injection.scope.This;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.property.Property;
+
+@Mixins( { <%= polygene.current.clazz.name %>.Mixin.class } )
+public interface <%= polygene.current.clazz.name %>
+{
+ interface State
+ {
+ Property<String> name(); // Sample hidden property
+ }
+
+ class Mixin
+ implements <%= polygene.current.clazz.name %>
+ {
+ @This
+ private State state; // Sample reference to hidden property
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl
new file mode 100644
index 0000000..95eed76
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl
@@ -0,0 +1,41 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.model.<%= polygene.current.name %>;
+
+import org.apache.polygene.api.injection.scope.This;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.property.Property;
+
+@Mixins( { <%= polygene.current.clazz.name %>.Mixin.class } )
+public interface <%= polygene.current.clazz.name %>
+{
+ interface State
+ {
+ Property<String> name(); // Sample hidden property
+ }
+
+ class Mixin
+ implements <%= polygene.current.clazz.name %>
+ {
+ @This
+ private State state; // Sample reference to hidden property
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Object.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Object.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Object.tmpl
new file mode 100644
index 0000000..27d6119
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Object.tmpl
@@ -0,0 +1,33 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.model.<%= polygene.current.name %>;
+
+import org.apache.polygene.api.injection.scope.This
+import org.apache.polygene.api.mixin.Mixins;
+
+public class <%= polygene.current.clazz.name %>
+{
+ @Uses
+ private String name; // Sample @Uses injection
+
+ @Structure
+ private ValueBuilderFactory vbf; // Sample @Structure injection
+
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Service.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Service.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Service.tmpl
new file mode 100644
index 0000000..0edefdc
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Service.tmpl
@@ -0,0 +1,36 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.model.<%= polygene.current.name %>;
+
+import org.apache.polygene.api.injection.scope.Structure;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.value.ValueBuilderFactory;
+
+@Mixins( { <%= polygene.current.clazz.name %>.Mixin.class } )
+public interface <%= polygene.current.clazz.name %>
+{
+ class Mixin
+ implements <%= polygene.current.clazz.name %>
+ {
+ @Structure
+ private ValueBuilderFactory vbf;
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
new file mode 100644
index 0000000..60e117d
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
@@ -0,0 +1,41 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.model.<%= polygene.current.name %>;
+
+import org.apache.polygene.api.injection.scope.This
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.property.Property;
+
+@Mixins( { <%= polygene.current.clazz.name %>.Mixin.class } )
+public interface <%= polygene.current.clazz.name %>
+{
+ interface State
+ {
+ Property<String> name(); // Sample hidden property
+ }
+
+ class Mixin
+ implements <%= polygene.current.clazz.name %>
+ {
+ @This
+ private State state; // Sample reference to hidden property
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl
new file mode 100644
index 0000000..cbab067
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/bootstrap.tmpl
@@ -0,0 +1,87 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.bootstrap.domain;
+
+import org.apache.polygene.bootstrap.AssemblyException;
+import org.apache.polygene.bootstrap.LayerAssembly;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.bootstrap.layered.ModuleAssembler;
+<% for( var idx in polygene.current.cruds) { %>
+<%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.cruds[idx].name + ";" %>
+<% } %>
+<% for( var idx in polygene.current.values) { %><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.values[idx].name + ";" %><% } %>
+<% for( var idx in polygene.current.entities) { %><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.entities[idx].name + ";" %><% } %>
+<% for( var idx in polygene.current.transients) { %><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.transients[idx].name + ";" %><% } %>
+<% for( var idx in polygene.current.objects) { %><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.objects[idx].name + ";" %><% } %>
+<% for( var idx in polygene.current.services) { %><%= "import " + packageName + ".model." + polygene.current.name + "." + polygene.current.services[idx].name + ";" %><% } %>
+
+import static org.apache.polygene.api.common.Visibility.layer;
+import static org.apache.polygene.api.common.Visibility.application;
+
+public class <%- firstUpper(polygene.current.name) %>Module
+ implements ModuleAssembler
+{
+ @Override
+ public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
+ throws AssemblyException
+ {
+<% if( polygene.current.cruds ) { %>
+ <% for( var value in polygene.current.cruds ) { %>
+ <% var crud1 = polygene.current.cruds[value]; %>
+ module.values(<%- crud1.name + ".class" %>)<% if( crud1.visibility ) {%><%-".visibleIn(" + crud1.visibility +")"%><% } %>;
+ <% } %>
+ <% for( var value in polygene.current.cruds ) { %>
+ <% var crud2 = polygene.current.cruds[value]; %>
+ module.entities(<%= crud2.name + ".class" %>)<% if( crud2.visibility ) {%><%-".visibleIn(" + crud2.visibility +")"%><% } %>;
+ <% } %>
+<% } %>
+<% if( polygene.current.values ) { %>
+ <% for( var value in polygene.current.values ) { %>
+ <% var v = polygene.current.current[value]; %>
+ module.values(<%= v.name + ".class" %>)<% if( v.visibility ) {%><%-".visibleIn(" + v.visibility +")"%><% } %>;
+ <% } %>
+<% } %>
+<% if( polygene.current.entities ) { %>
+ <% for( var value in polygene.current.entities ) { %>
+ <% var entity = polygene.current.entities[value]; %>
+ module.values(<%= entity.name + ".class" %>)<% if( entity.visibility ) {%><%-".visibleIn(" + entity.visibility +")"%><% } %>;
+ <% } %>
+<% } %>
+<% if( polygene.current.transients ) { %>
+ <% for( var value in polygene.current.transients ) { %>
+ <% var trans = polygene.current.transients[value]; %>
+ module.values(<%= trans.name + ".class" %>)<% if( trans.visibility ) {%><%-".visibleIn(" + trans.visibility +")"%><% } %>;
+ <% } %>
+<% } %>
+<% if( polygene.current.objects ) { %>
+ <% for( var value in polygene.current.objects ) { %>
+ <% var obj = polygene.current.objects[value]; %>
+ module.values(<%= obj.name + ".class" %>)<% if( obj.visibility ) {%><%-".visibleIn(" + obj.visibility +")"%><% } %>;
+ <% } %>
+<% } %>
+<% if( polygene.current.services ) { %>
+ <% for( var value in polygene.current.services ) { %>
+ <% var service = polygene.current.services[value]; %>
+ module.values(<%= service.name + ".class" %>)<% if( service.visibility ) {%><%-".visibleIn(" + service.visibility +")"%><% } %>;
+ <% } %>
+<% } %>
+ return module;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js
new file mode 100644
index 0000000..2ceeaa5
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js
@@ -0,0 +1,42 @@
+module.exports = {
+
+ write: function (p) {
+
+ Object.keys(p.modules).forEach(function (moduleName, index) {
+ copyPolygeneDomainModule(p, moduleName, p.modules[moduleName])
+ });
+ }
+
+};
+
+function copyFile(p, module, clazz) {
+ p.copyTemplate(p.ctx,
+ p.firstUpper(module) + 'Module/' + clazz + '.tmpl',
+ 'model/src/main/java/' + p.javaPackageDir + '/model/' + module + '/' + clazz + '.java');
+}
+
+function copyPolygeneDomainModule(p, moduleName, moduleDef) {
+ p.current = moduleDef;
+ p.current.name = moduleName;
+ var clazz = p.firstUpper(moduleName) + "Module";
+ p.copyTemplate(p.ctx,
+ 'DomainLayer/DomainModule/bootstrap.tmpl',
+ 'bootstrap/src/main/java/' + p.javaPackageDir + '/bootstrap/domain/' + clazz + '.java');
+ copyComposites(p, moduleDef.cruds, "Crud");
+ copyComposites(p, moduleDef.entities, "Entity");
+ copyComposites(p, moduleDef.values, "Value");
+ copyComposites(p, moduleDef.transients, "Transient");
+ copyComposites(p, moduleDef.objects, "Object");
+ copyComposites(p, moduleDef.services, "Service");
+}
+
+function copyComposites(p, composites, type) {
+ for (var idx in composites) {
+ if (composites.hasOwnProperty(idx)) {
+ p.current.clazz = composites[idx];
+ p.copyTemplate(p.ctx,
+ 'DomainLayer/DomainModule/' + type + '.tmpl',
+ 'model/src/main/java/' + p.javaPackageDir + '/model/' + p.current.name + '/' + p.current.clazz.name + '.java');
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoConfiguration.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoConfiguration.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoConfiguration.tmpl
new file mode 100644
index 0000000..89883a2
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoConfiguration.tmpl
@@ -0,0 +1,37 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.model.security;
+
+import org.apache.polygene.api.property.Property;
+import org.apache.polygene.api.common.Optional;
+
+public class CryptoConfiguration
+{
+ @Optional
+ Property<String> digestAlgorithm();
+
+ @Optional
+ Property<String> digestAlgorithm();
+
+ Property<String> secret1();
+
+ Property<String> secret2();
+
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoException.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoException.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoException.tmpl
new file mode 100644
index 0000000..00ec8f8
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoException.tmpl
@@ -0,0 +1,28 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.model.security;
+
+public class CryptoException extends RuntimeException
+{
+ public CryptoException( String message, Throwable cause )
+ {
+ super( message, cause );
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoService.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoService.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoService.tmpl
new file mode 100644
index 0000000..4bc72c2
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/CryptoService.tmpl
@@ -0,0 +1,106 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.model.security;
+
+import java.security.MessageDigest;
+import java.crypto.Cipher;
+import java.crypto.spec.IvParameterSpec;
+import java.crypto.spec.SecretKeySpec;
+
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.property.Property;
+
+@Mixins( { CryptoService.Mixin.class } )
+public interface CryptoService
+{
+ String encrypt( String clear );
+
+ String decrypt( String encrypted );
+
+ class CryptoMixin
+ implements CryptoService
+ {
+ private byte[] keyBytes;
+ private byte[] ivBytes;
+ private Cipher cipher;
+ private MessageDigest digest;
+
+ public CryptoMixin(Configuration<CryptoConfiguration> configuration)
+ throws Exception
+ {
+ CryptoConfiguration config = configuration.configuration().get();
+ String digestAlgorithm = config.digestAlgorithm().get();
+ if( digestAlgorithm == null )
+ digestAlgorithm = "SHA-1";
+ digest = MessageDigest.getInstance( );
+ byte[] keyBytes = hashed( config.secret1().get() );
+ byte[] ivBytes = hashed( config.secret2().get() );
+
+ SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
+ IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
+
+ String encryptionAlgorithm = config.encryptionAlgorithm().get();
+ if( encryptionAlgorithm == null )
+ encryptionAlgorithm = "AES";
+ cipher = Cipher.getInstance( encryptionAlgorithm );
+ }
+
+ public String encrypt( String clear )
+ throws CryptoException
+ {
+ try
+ {
+ cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
+
+ byte[] input = clear.getBytes();
+ byte[] encrypted= new byte[cipher.getOutputSize(input.length)];
+ int enc_len = cipher.update(input, 0, input.length, encrypted, 0);
+ enc_len += cipher.doFinal(encrypted, enc_len);
+ return new String( encrypted, 0, enc_len );
+
+ } catch( Exception e ) {
+ throw new CryptoException( "Unable to encrypt.", e );
+ }
+ }
+
+ public String decrypt( String encryptedString )
+ throws CryptoException
+ {
+ try
+ {
+ cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
+
+ byte[] encrypted = encryptedString.getBytes();
+ byte[] decrypted = new byte[cipher.getOutputSize(enc_len)];
+ int dec_len = cipher.update(encrypted, 0, enc_len, decrypted, 0);
+ dec_len += cipher.doFinal(decrypted, dec_len);
+ return new String( decrypted, 0, dec_len );
+ } catch( Exception e ) {
+ throw new CryptoException( "Unable to decrypt.", e );
+ }
+ }
+
+ private byte[] hashed( String data )
+ {
+ digest.reset();
+ return digest.digest( data.getBytes() );
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/EncryptedStringPropertyConcern.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/EncryptedStringPropertyConcern.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/EncryptedStringPropertyConcern.tmpl
new file mode 100644
index 0000000..4083a39
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/EncryptedStringPropertyConcern.tmpl
@@ -0,0 +1,41 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.model.security;
+
+import org.apache.polygene.api.concern.ConcernOf;
+import org.apache.polygene.api.property.Property;
+import org.apache.polygene.api.injection.scope.Service;
+
+public class EncryptedStringPropertyConcern extends ConcernOf<Property<String>>
+ implements Property<String>
+{
+ @Service
+ private CryptoService crypto;
+
+ public String get() {
+ String value = next.get();
+ return crypto.decrypt( value );
+ }
+
+ public void set( String value ) {
+ String encrypted = crypto.encrypt( value );
+ next.set( value );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/EntityStoreBackedSecurityRepositoryMixin.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/EntityStoreBackedSecurityRepositoryMixin.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/EntityStoreBackedSecurityRepositoryMixin.tmpl
new file mode 100644
index 0000000..56c4a5c
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/EntityStoreBackedSecurityRepositoryMixin.tmpl
@@ -0,0 +1,60 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.model.security;
+
+import java.util.Collections;
+import java.util.List;
+import org.apache.polygene.api.unitofwork.concern.UnitOfWorkPropagation;
+
+public class EntityStoreBackedSecurityRepositoryMixin
+ implements SecurityRepository
+{
+ @Structure
+ private UnitOfWorkFactory uowf;
+
+ @Override
+ @UnitOfWorkPropagation
+ public boolean verifyPassword( String userName, String password )
+ {
+ Identity identity = new StringIdentity("User-" + userName );
+ User user = uow.currentUnitOfWork(User.class, identity );
+
+ if( userName.equals("admin") && password.equals("secret") )
+ {
+ return true;
+ }
+ if( userName.equals("user") && password.equals("123") )
+ {
+ return true;
+ }
+ return false;
+ }
+
+ @UnitOfWorkPropagation
+ public List<String> findRoleNamesOfUser( String name )
+ {
+ if( "admin".equals( name ) )
+ {
+ return Collections.singletonList("admin");
+ }
+ return Collections.singletonList("user");
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/a7bdc408/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/Group.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/Group.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/Group.tmpl
new file mode 100644
index 0000000..eb83232
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/Group.tmpl
@@ -0,0 +1,41 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+package <%= packageName %>.model.security;
+
+import org.apache.polygene.api.injection.scope.This
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.property.Property;
+
+@Mixins( { Group.Mixin } )
+public interface Group
+{
+ interface State
+ {
+ Property<String> password();
+ }
+
+ class Mixin
+ implements Group
+ {
+ @This
+ private State state; // Sample reference to hidden property
+
+ }
+}
[38/50] [abbrv] polygene-java git commit: Serialization API and SPI
javadoc
Posted by pa...@apache.org.
Serialization API and SPI javadoc
POLYGENE-231
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/37c31d4a
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/37c31d4a
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/37c31d4a
Branch: refs/heads/serialization-3.0
Commit: 37c31d4a0182e8bc50a3723d446df623a52731cb
Parents: 9485717
Author: Paul Merlin <pa...@apache.org>
Authored: Mon Mar 13 10:07:02 2017 +0100
Committer: Paul Merlin <pa...@apache.org>
Committed: Mon Mar 13 11:24:42 2017 +0100
----------------------------------------------------------------------
.../api/serialization/Deserializer.java | 5 +++
.../api/serialization/Serialization.java | 10 +++---
.../polygene/api/serialization/Serializer.java | 6 ++++
.../polygene/api/serialization/package.html | 23 ++++++++++--
.../AbstractBinaryDeserializer.java | 2 ++
.../serialization/AbstractBinarySerializer.java | 2 ++
.../spi/serialization/AbstractDeserializer.java | 7 ++++
.../spi/serialization/AbstractSerializer.java | 7 ++++
.../serialization/AbstractTextDeserializer.java | 2 ++
.../serialization/AbstractTextSerializer.java | 2 ++
.../spi/serialization/BuiltInConverters.java | 21 +++++++++++
.../spi/serialization/JsonDeserializer.java | 3 ++
.../spi/serialization/JsonSerialization.java | 3 ++
.../spi/serialization/JsonSerializer.java | 3 ++
.../spi/serialization/XmlDeserializer.java | 3 ++
.../spi/serialization/XmlSerialization.java | 3 ++
.../spi/serialization/XmlSerializer.java | 2 +-
.../polygene/spi/serialization/package.html | 37 +++++++++++++++++---
18 files changed, 127 insertions(+), 14 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/37c31d4a/core/api/src/main/java/org/apache/polygene/api/serialization/Deserializer.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/serialization/Deserializer.java b/core/api/src/main/java/org/apache/polygene/api/serialization/Deserializer.java
index 7ab1c44..0b633dd 100644
--- a/core/api/src/main/java/org/apache/polygene/api/serialization/Deserializer.java
+++ b/core/api/src/main/java/org/apache/polygene/api/serialization/Deserializer.java
@@ -24,6 +24,11 @@ import java.util.stream.Stream;
import org.apache.polygene.api.structure.ModuleDescriptor;
import org.apache.polygene.api.type.ValueType;
+/**
+ * Deserializer.
+ *
+ * Provides methods and functions to deserialize objects and set of objects.
+ */
public interface Deserializer
{
<T> T deserialize( ModuleDescriptor module, ValueType valueType, InputStream state );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/37c31d4a/core/api/src/main/java/org/apache/polygene/api/serialization/Serialization.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/serialization/Serialization.java b/core/api/src/main/java/org/apache/polygene/api/serialization/Serialization.java
index ff1d32f..8bf005b 100644
--- a/core/api/src/main/java/org/apache/polygene/api/serialization/Serialization.java
+++ b/core/api/src/main/java/org/apache/polygene/api/serialization/Serialization.java
@@ -18,17 +18,15 @@
package org.apache.polygene.api.serialization;
/**
- *
+ * Serialization extends {@link Serializer} and {@link Deserializer}.
*/
public interface Serialization extends Serializer, Deserializer
{
/**
- * Serialization format @Service tags.
+ * Serialization format {@literal @Service} tags.
*
- * <p>
- * Serialization implementations should be tagged with theses at assembly time so that consumers can
- * specify which format they need.
- * </p>
+ * Serialization implementations should be tagged with theses at assembly time so that consumers can
+ * specify which format they need.
*/
interface Formats
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/37c31d4a/core/api/src/main/java/org/apache/polygene/api/serialization/Serializer.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/serialization/Serializer.java b/core/api/src/main/java/org/apache/polygene/api/serialization/Serializer.java
index bdbe482..39e15b1 100644
--- a/core/api/src/main/java/org/apache/polygene/api/serialization/Serializer.java
+++ b/core/api/src/main/java/org/apache/polygene/api/serialization/Serializer.java
@@ -26,6 +26,12 @@ import java.util.function.Function;
import java.util.stream.Stream;
import org.apache.polygene.api.common.Optional;
+/**
+ * Serializer.
+ *
+ * All implementations must handle all {@link Options}, they might extend them to provide more control.
+ * See their respective documentation for the details.
+ */
public interface Serializer
{
void serialize( Options options, Writer writer, @Optional Object object );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/37c31d4a/core/api/src/main/java/org/apache/polygene/api/serialization/package.html
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/serialization/package.html b/core/api/src/main/java/org/apache/polygene/api/serialization/package.html
index fc2a3bd..467fc65 100644
--- a/core/api/src/main/java/org/apache/polygene/api/serialization/package.html
+++ b/core/api/src/main/java/org/apache/polygene/api/serialization/package.html
@@ -14,11 +14,30 @@
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
- ~
- ~
-->
<html>
<body>
<h2>Serialization API.</h2>
+<p>
+ {@link Serialization} extends {@link Serializer} and {@link Deserializer}.
+ <br/>
+ {@link SerializationException} is thrown when something goes wrong.
+</p>
+<p>
+ Serialization implementations should be tagged with {@link Serialization.Format} at assembly time so that consumers
+ can specify which format they need:
+</p>
+<pre><code>@Service @Tagged( Serialization.Format.JSON ) Serialization serialization;</code></pre>
+<p>
+ {@link Serializer}s and {@link Deserializers} provides methods and functions to (de)serialize objects
+ and set of objects.
+</p>
+<p>
+ Serialized representations might be textual (e.g. {@literal JSON} and {@literal XML}) or binary.
+ Implementations are free to use any codec to encode/decode from/to text and bytes but it must be bi-directional.
+</p>
+<p>
+ The serialization behavior can be influenced using {@link Serializer.Options}.
+</p>
</body>
</html>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/37c31d4a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinaryDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinaryDeserializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinaryDeserializer.java
index 7e2d19a..5cf2660 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinaryDeserializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinaryDeserializer.java
@@ -33,6 +33,8 @@ import static java.util.stream.Collectors.joining;
* Base Binary Deserializer.
*
* Implementations work on bytes, this base deserializer decode Strings from Base64 to produce bytes.
+ *
+ * See {@link AbstractBinarySerializer}.
*/
public abstract class AbstractBinaryDeserializer extends AbstractDeserializer
// END SNIPPET: binary
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/37c31d4a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinarySerializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinarySerializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinarySerializer.java
index 0cf17eb..c17ffb4 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinarySerializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractBinarySerializer.java
@@ -31,6 +31,8 @@ import static java.nio.charset.StandardCharsets.UTF_8;
* Base Binary Serializer.
*
* Implementations work on bytes, this base serializer encode these bytes in Base64 to produce Strings.
+ *
+ * See {@link AbstractBinaryDeserializer}.
*/
public abstract class AbstractBinarySerializer extends AbstractSerializer
// END SNIPPET: binary
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/37c31d4a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractDeserializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractDeserializer.java
index 17982f3..b373160 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractDeserializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractDeserializer.java
@@ -32,6 +32,13 @@ import org.apache.polygene.api.type.MapType;
import org.apache.polygene.api.type.ValueType;
import org.apache.polygene.spi.module.ModuleSpi;
+/**
+ * Base Deserializer.
+ *
+ * Provides default implementations for convenience API methods.
+ *
+ * See {@link AbstractSerializer}.
+ */
public abstract class AbstractDeserializer implements Deserializer
{
protected static final ValueType ENTITY_REF_LIST_VALUE_TYPE = CollectionType.listOf( EntityReference.class );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/37c31d4a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractSerializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractSerializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractSerializer.java
index b5f10ff..3269adb 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractSerializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractSerializer.java
@@ -27,6 +27,13 @@ import java.util.stream.StreamSupport;
import org.apache.polygene.api.common.Optional;
import org.apache.polygene.api.serialization.Serializer;
+/**
+ * Base Serializer.
+ *
+ * Provides default implementations for convenience API methods.
+ *
+ * See {@link AbstractDeserializer}.
+ */
public abstract class AbstractSerializer implements Serializer
{
@Override
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/37c31d4a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextDeserializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextDeserializer.java
index d87dd6d..f61db14 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextDeserializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextDeserializer.java
@@ -29,6 +29,8 @@ import static java.nio.charset.StandardCharsets.UTF_8;
* Base Text Deserializer.
*
* Implementations work on Strings, this base deserializer decode bytes in UTF-8 to produce strings.
+ *
+ * See {@link AbstractTextSerializer}.
*/
public abstract class AbstractTextDeserializer extends AbstractDeserializer
// END SNIPPET: text
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/37c31d4a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextSerializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextSerializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextSerializer.java
index 2c2b83c..aa9821d 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextSerializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/AbstractTextSerializer.java
@@ -30,6 +30,8 @@ import static java.nio.charset.StandardCharsets.UTF_8;
* Base Text Serializer.
*
* Implementations work on Strings, this base serializer encode these strings in UTF-8 to produce bytes.
+ *
+ * See {@link AbstractTextDeserializer}.
*/
public abstract class AbstractTextSerializer extends AbstractSerializer
// END SNIPPET: text
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/37c31d4a/core/spi/src/main/java/org/apache/polygene/spi/serialization/BuiltInConverters.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/BuiltInConverters.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/BuiltInConverters.java
index a6392ff..0c1b774 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/BuiltInConverters.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/BuiltInConverters.java
@@ -37,6 +37,27 @@ import org.apache.polygene.api.type.ValueType;
/**
* Built-in serialization converters.
+ *
+ * Mixin for {@link org.apache.polygene.api.serialization.Serialization} implementations that provides built-in
+ * {@link Converter}s for the following types:
+ *
+ * <ul>
+ * <li>{@link Identity}</li>
+ * <li>{@link EntityReference}</li>
+ * <li>{@link BigDecimal}</li>
+ * <li>{@link BigInteger}</li>
+ * <li>{@link Instant}</li>
+ * <li>{@link ZonedDateTime}</li>
+ * <li>{@link OffsetDateTime}</li>
+ * <li>{@link LocalDateTime}</li>
+ * <li>{@link LocalDate}</li>
+ * <li>{@link LocalTime}</li>
+ * <li>{@link Duration}</li>
+ * <li>{@link Period}</li>
+ * </ul>
+ *
+ * Note that this does not include {@link String} nor primitive values and their boxed counterparts.
+ * {@literal Serialization} implementations must handle those.
*/
@Mixins( BuiltInConverters.Mixin.class )
public interface BuiltInConverters
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/37c31d4a/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonDeserializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonDeserializer.java
index a0dac71..30060ef 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonDeserializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonDeserializer.java
@@ -39,6 +39,9 @@ import org.apache.polygene.spi.module.ModuleSpi;
import static java.util.stream.Collectors.joining;
+/**
+ * {@literal javax.json} deserializer.
+ */
public interface JsonDeserializer extends Deserializer
{
<T> T fromJson( ModuleDescriptor module, ValueType valueType, JsonValue state );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/37c31d4a/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerialization.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerialization.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerialization.java
index a98e70f..f41078b 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerialization.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerialization.java
@@ -19,6 +19,9 @@ package org.apache.polygene.spi.serialization;
import org.apache.polygene.api.serialization.Serialization;
+/**
+ * {@literal javax.json} serialization.
+ */
public interface JsonSerialization extends Serialization, JsonSerializer, JsonDeserializer
{
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/37c31d4a/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerializer.java
index 54dd92b..9ec1863 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/JsonSerializer.java
@@ -28,6 +28,9 @@ import javax.json.JsonValue;
import org.apache.polygene.api.common.Optional;
import org.apache.polygene.api.serialization.Serializer;
+/**
+ * {@literal javax.json} serializer.
+ */
public interface JsonSerializer extends Serializer
{
<T> Function<T, JsonValue> toJsonFunction( Options options );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/37c31d4a/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlDeserializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlDeserializer.java
index 9e559c8..f61e533 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlDeserializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlDeserializer.java
@@ -34,6 +34,9 @@ import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
+/**
+ * {@literal javax.xml} deserializer.
+ */
public interface XmlDeserializer extends Deserializer
{
<T> T fromXml( ModuleDescriptor module, ValueType valueType, Document state );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/37c31d4a/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlSerialization.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlSerialization.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlSerialization.java
index 12fda54..c4b7f37 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlSerialization.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlSerialization.java
@@ -19,6 +19,9 @@ package org.apache.polygene.spi.serialization;
import org.apache.polygene.api.serialization.Serialization;
+/**
+ * {@literal javax.xml} serialization.
+ */
public interface XmlSerialization extends Serialization, XmlSerializer, XmlDeserializer
{
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/37c31d4a/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlSerializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlSerializer.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlSerializer.java
index 32ce539..afffe5f 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlSerializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/XmlSerializer.java
@@ -36,7 +36,7 @@ import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
- * XML State Serializer.
+ * {@literal javax.xml} serializer.
*/
public interface XmlSerializer extends Serializer
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/37c31d4a/core/spi/src/main/java/org/apache/polygene/spi/serialization/package.html
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/package.html b/core/spi/src/main/java/org/apache/polygene/spi/serialization/package.html
index 2e2f188..8078138 100644
--- a/core/spi/src/main/java/org/apache/polygene/spi/serialization/package.html
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/package.html
@@ -14,11 +14,38 @@
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
- ~
- ~
-->
<html>
- <body>
- <h2>Serialization SPI.</h2>
- </body>
+<body>
+<h2>Serialization SPI.</h2>
+<p>
+ This package contains specialized serialization APIs for the {@literal JSON} and {@literal XML} formats.
+ See {@link @JsonSerialization}, based on {@literal javax.json},
+ and {@link XmlSerialization}, based on {@literal javax.xml}.
+</p>
+<p>
+ This package also contains base implementations, mixins and helpers for serialization API implementations:
+</p>
+<p><strong>Base implementations</strong></p>
+<ul>
+ <li>
+ Use {@link AbstractTextSerializer} and {@link AbstractTextDeserializer} as a basis to implement the
+ serialization API for text representations.
+ </li>
+ <li>
+ Use {@link AbstractBinarySerializer} and {@link AbstractBinaryDeserializer} as a basis to implement the
+ serialization API for binary representations.
+ </li>
+ <li>
+ Use {@link AbstractSerializer} and {@link AbstractDeserializer} if you need to handle text/binary conversion
+ yourself.
+ </li>
+</ul>
+<p>
+ <strong>Mixins</strong>
+</p>
+<ul>
+ <li>{@link BuiltInConverters} provides built-in {@link Converter}s for types supported by the Polygene Runtime.</li>
+</ul>
+</body>
</html>
[10/50] [abbrv] polygene-java git commit: Fixed Serialization missing
in RdfIndexingAssembler,
causing failed tests. Fixed additional issues in Yeoman generator.
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxCollectionSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxCollectionSerializationTest.java b/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxCollectionSerializationTest.java
index ae1267b..04ed30a 100644
--- a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxCollectionSerializationTest.java
+++ b/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxCollectionSerializationTest.java
@@ -19,6 +19,7 @@
*/
package org.apache.polygene.valueserialization.stax;
+import org.apache.polygene.valueserialization.stax.assembly.StaxValueSerializationAssembler;
import org.junit.BeforeClass;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxConfigurationDeserializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxConfigurationDeserializationTest.java b/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxConfigurationDeserializationTest.java
index 3c52f82..052072f 100644
--- a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxConfigurationDeserializationTest.java
+++ b/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxConfigurationDeserializationTest.java
@@ -21,6 +21,7 @@
package org.apache.polygene.valueserialization.stax;
import org.apache.polygene.api.identity.StringIdentity;
+import org.apache.polygene.valueserialization.stax.assembly.StaxValueSerializationAssembler;
import org.junit.Ignore;
import org.junit.Test;
import org.apache.polygene.api.injection.scope.Service;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxPlainValueSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxPlainValueSerializationTest.java b/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxPlainValueSerializationTest.java
index 1d1c456..11f1e7d 100644
--- a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxPlainValueSerializationTest.java
+++ b/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxPlainValueSerializationTest.java
@@ -21,6 +21,7 @@ package org.apache.polygene.valueserialization.stax;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.test.value.AbstractPlainValueSerializationTest;
+import org.apache.polygene.valueserialization.stax.assembly.StaxValueSerializationAssembler;
import org.junit.BeforeClass;
import static org.apache.polygene.test.util.Assume.assumeNoIbmJdk;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxValueCompositeSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxValueCompositeSerializationTest.java b/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxValueCompositeSerializationTest.java
index 57a7e9a..65d66f6 100644
--- a/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxValueCompositeSerializationTest.java
+++ b/extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxValueCompositeSerializationTest.java
@@ -19,6 +19,7 @@
*/
package org.apache.polygene.valueserialization.stax;
+import org.apache.polygene.valueserialization.stax.assembly.StaxValueSerializationAssembler;
import org.junit.BeforeClass;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/RestletCrudConnectivityAssembler.java
----------------------------------------------------------------------
diff --git a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/RestletCrudConnectivityAssembler.java b/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/RestletCrudConnectivityAssembler.java
index 3979194..21a2e0c 100644
--- a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/RestletCrudConnectivityAssembler.java
+++ b/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/RestletCrudConnectivityAssembler.java
@@ -38,7 +38,7 @@ import org.apache.polygene.library.restlet.resource.EntryPointResource;
import org.apache.polygene.library.restlet.resource.ResourceBuilder;
import org.apache.polygene.library.restlet.serialization.FormRepresentation;
import org.apache.polygene.library.restlet.serialization.JsonRepresentation;
-import org.apache.polygene.valueserialization.jackson.JacksonValueSerializationAssembler;
+import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
public class RestletCrudConnectivityAssembler
implements Assembler
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/configuration/ConfigurationModule.java
----------------------------------------------------------------------
diff --git a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/configuration/ConfigurationModule.java b/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/configuration/ConfigurationModule.java
index 87f5241..e564c0d 100644
--- a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/configuration/ConfigurationModule.java
+++ b/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/configuration/ConfigurationModule.java
@@ -26,7 +26,7 @@ import org.apache.polygene.bootstrap.LayerAssembly;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.bootstrap.layered.ModuleAssembler;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
-import org.apache.polygene.valueserialization.jackson.JacksonValueSerializationAssembler;
+import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
public class ConfigurationModule
implements ModuleAssembler
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/infrastructue/SerializationModule.java
----------------------------------------------------------------------
diff --git a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/infrastructue/SerializationModule.java b/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/infrastructue/SerializationModule.java
index 736edaa..77d1166 100644
--- a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/infrastructue/SerializationModule.java
+++ b/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/infrastructue/SerializationModule.java
@@ -25,7 +25,7 @@ import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.LayerAssembly;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.bootstrap.layered.ModuleAssembler;
-import org.apache.polygene.valueserialization.jackson.JacksonValueSerializationAssembler;
+import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
public class SerializationModule
implements ModuleAssembler
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/settings.gradle
----------------------------------------------------------------------
diff --git a/settings.gradle b/settings.gradle
index a982fbb..5b9c045 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -81,6 +81,7 @@ include 'core:api',
'extensions:valueserialization-stax',
'tools:model-detail',
'tools:envisage',
+ 'tools:generator-polygene',
// 'tools:qidea',
'tests:regression',
'tests:performance',
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl
index b152d3a..0c925da 100644
--- a/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/ConfigurationLayer/ConfigModule/bootstrap.tmpl
@@ -25,7 +25,7 @@ import org.apache.polygene.bootstrap.LayerAssembly;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.bootstrap.layered.ModuleAssembler;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
-import org.apache.polygene.valueserialization.jackson.JacksonValueSerializationAssembler;
+import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
public class ConfigModule
implements ModuleAssembler
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/tools/generator-polygene/app/templates/InfrastructureLayer/MetricsModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/MetricsModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/MetricsModule/bootstrap.tmpl
index 2bbc875..a4d3919 100644
--- a/tools/generator-polygene/app/templates/InfrastructureLayer/MetricsModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/MetricsModule/bootstrap.tmpl
@@ -41,7 +41,7 @@ public class <%- polygene.metrics %>MetricsModule
public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
throws AssemblyException
{
- new <%- polygene.metrics %>Assembler(Visibility.application, Visibility.module).assemble( module );
+ new <%- polygene.metrics %>MetricsAssembler().assemble( module );
return module;
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl
index ea455cd..62b3586 100644
--- a/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/SerializationModule/bootstrap.tmpl
@@ -24,7 +24,7 @@ import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.LayerAssembly;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.bootstrap.layered.ModuleAssembler;
-import org.apache.polygene.valueserialization.<%- polygene.serialization.toLowerCase() %>.<%- polygene.serialization %>ValueSerializationAssembler;
+import org.apache.polygene.valueserialization.<%- polygene.serialization.toLowerCase() %>.assembly.<%- polygene.serialization %>ValueSerializationAssembler;
public class <%- polygene.serialization %>ValueSerializationModule
implements ModuleAssembler
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/tools/generator-polygene/build.gradle
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/build.gradle b/tools/generator-polygene/build.gradle
new file mode 100644
index 0000000..64bd9f0
--- /dev/null
+++ b/tools/generator-polygene/build.gradle
@@ -0,0 +1,68 @@
+def allEntityStores = [
+ 'Cassandra',
+ 'File',
+ 'DerbySQL',
+ 'Geode',
+ 'H2SQL',
+ 'Hazelcast',
+ 'JClouds',
+ 'Jdbm',
+ 'LevelDB',
+ 'Memory',
+ 'MongoDB',
+ 'MySQL',
+ 'Preferences',
+ 'Redis',
+ 'Riak',
+ 'PostgresSQL',
+ 'SQLite'
+]
+
+def allIndexing = [
+ "Rdf",
+ "ElasticSearch",
+ "Solr",
+ "SQL"
+]
+
+def allCaching = [
+ "None",
+ "EhCache",
+ "Memcache"
+]
+
+def allMetrics = [
+ "None",
+ "Codahale"
+]
+
+def allValueSerialization = [
+ "Jackson",
+ "Stax"
+]
+
+def featureCombinations(array, result) {
+ if (array?.empty) {
+ return []
+ }
+ return [array, featureCombinations(array.tail())]
+}
+
+def allFeatures = [
+ 'rest api',
+ 'jmx',
+ 'security'
+].forEach( {
+
+});
+
+def allFeatureCombos = [
+
+]
+
+def allCombos = [
+
+]
+
+println allFeatures
+
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/b8aea70a/tools/generator-polygene/test/generator_test.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/test/generator_test.js b/tools/generator-polygene/test/generator_test.js
index 0e8ef8b..e215d4c 100644
--- a/tools/generator-polygene/test/generator_test.js
+++ b/tools/generator-polygene/test/generator_test.js
@@ -3,17 +3,127 @@ var helpers = require('yeoman-test');
var assert = require('yeoman-assert');
var shell = require('shelljs');
-// See http://yeoman.io/authoring/testing.html
-describe('polygene-generator', function () {
- it('generates a buildable gradle project', function () {
- return helpers.run(path.join(__dirname, '../app'))
- .withPrompts({
- name: 'test-project',
- packageName: 'org.apache.polygene.generator.test'
- })
- .then(function(dir) {
- assert.file(['gradlew', 'settings.gradle', 'build.gradle']);
- assert(shell.exec(path.join(dir, 'gradlew') + ' build').code == 0);
+//See http://yeoman.io/authoring/testing.html
+
+describe('polygene-generator-defaults', function () {
+ this.timeout(10000);
+ it('generates a Gradle buildable Apache Polygene project', function () {
+ return helpers.run(path.join(__dirname, '../app'))
+ .withPrompts({
+ name: 'test-project',
+ packageName: 'org.apache.polygene.generator.test'
+ })
+ .then(buildAndVerify);
+ });
+});
+
+[
+ 'Cassandra',
+ 'File',
+ 'Geode',
+ 'Hazelcast',
+ 'JClouds',
+ 'Jdbm',
+ 'LevelDB',
+ 'MongoDB',
+ 'Preferences',
+ 'Redis',
+ 'Riak',
+ 'SQL',
+ 'Memory' // Somehow the last EntityStore is used in subsequent test arrays. Pick the fastest.
+].forEach(function (entityStore) {
+ describe('polygene-generator-default-and-' + entityStore.toLowerCase() + "-entitystore", function () {
+ this.timeout(10000);
+ it('generates a Gradle buildable Apache Polygene project with ' + entityStore + ' as the Entity Store', function () {
+ return helpers.run(path.join(__dirname, '../app'))
+ .withPrompts({
+ name: 'test-project',
+ packageName: 'org.apache.polygene.generator.test',
+ entitystore: entityStore
+ })
+ .then(buildAndVerify);
+ });
+ });
+});
+
+[
+ 'Rdf',
+ 'ElasticSearch',
+ 'Solr',
+ 'SQL'
+].forEach(function (indexing) {
+ describe('polygene-generator-default-and-' + indexing.toLowerCase() + '-indexing', function () {
+ this.timeout(10000);
+ it('generates a Gradle buildable Apache Polygene project with '+ indexing + ' as the Indexing system', function () {
+ return helpers.run(path.join(__dirname, '../app'))
+ .withPrompts({
+ name: 'test-project',
+ packageName: 'org.apache.polygene.generator.test',
+ indexing: indexing
+ })
+ .then(buildAndVerify);
+ });
+ });
+});
+
+[
+ 'None',
+ 'Memcache',
+ 'EhCache'
+].forEach(function (caching) {
+ describe('polygene-generator-default-and-' + caching.toLowerCase() + '-caching', function () {
+ this.timeout(10000);
+ it('generates a Gradle buildable Apache Polygene project with '+caching+' as the Caching system', function () {
+ return helpers.run(path.join(__dirname, '../app'))
+ .withPrompts({
+ name: 'test-project',
+ packageName: 'org.apache.polygene.generator.test',
+ caching: caching
+ })
+ .then(buildAndVerify);
});
- });
+ });
});
+
+[
+ 'Jackson',
+ // 'Johnzon',
+ 'Stax'
+].forEach(function (serialization) {
+ describe('polygene-generator-default-and-' + serialization.toLowerCase() + '-caching', function () {
+ this.timeout(10000);
+ it('generates a Gradle buildable Apache Polygene project with '+serialization+' as the Serialization system', function () {
+ return helpers.run(path.join(__dirname, '../app'))
+ .withPrompts({
+ name: 'test-project',
+ packageName: 'org.apache.polygene.generator.test',
+ serialization: serialization
+ })
+ .then(buildAndVerify);
+ });
+ });
+});
+
+[
+ 'None',
+ 'Codahale'
+].forEach(function (metrics) {
+ describe('polygene-generator-default-and-' + metrics.toLowerCase() + '-caching', function () {
+ this.timeout(10000);
+ it('generates a Gradle buildable Apache Polygene project with '+metrics+' as the Metrics system', function () {
+ return helpers.run(path.join(__dirname, '../app'))
+ .withPrompts({
+ name: 'test-project',
+ packageName: 'org.apache.polygene.generator.test',
+ metrics: metrics
+ })
+ .then(buildAndVerify);
+ });
+ });
+});
+
+
+function buildAndVerify(dir) {
+ assert.file(['gradlew', 'settings.gradle', 'build.gradle']);
+ assert(shell.exec(path.join(dir, 'gradlew') + ' build').code == 0);
+}
\ No newline at end of file
[43/50] [abbrv] polygene-java git commit: Introduce serialization
converters in API
Posted by pa...@apache.org.
Introduce serialization converters in API
Converters are \u201cformat agnostic\u201d and convert instances to String and the
other way around. Built-in converters for base types supported by the
Polygene Runtime (Identity, EntityReference, big numbers, date types).
POLYGENE-231
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/55916ef8
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/55916ef8
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/55916ef8
Branch: refs/heads/serialization-3.0
Commit: 55916ef81cb6145a11162589c6b54f0cf9573b13
Parents: 0a23e9f
Author: Paul Merlin <pa...@apache.org>
Authored: Mon Mar 13 09:28:42 2017 +0100
Committer: Paul Merlin <pa...@apache.org>
Committed: Mon Mar 13 11:24:42 2017 +0100
----------------------------------------------------------------------
.../polygene/api/serialization/Converter.java | 49 ++++
.../polygene/api/serialization/Converters.java | 131 +++++++++++
.../javaxjson/JavaxJsonDeserializer.java | 15 +-
.../JavaxJsonSerializationService.java | 223 ++----------------
.../javaxjson/JavaxJsonSerializer.java | 15 +-
.../spi/serialization/BuiltInConverters.java | 235 +++++++++++++++++++
.../javaxxml/JavaxXmlDeserializer.java | 10 +
.../javaxxml/JavaxXmlSerializationService.java | 195 ++-------------
.../javaxxml/JavaxXmlSerializer.java | 10 +
.../msgpack/MessagePackDeserializer.java | 10 +
.../MessagePackSerializationService.java | 195 ++-------------
.../msgpack/MessagePackSerializer.java | 10 +
12 files changed, 535 insertions(+), 563 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/55916ef8/core/api/src/main/java/org/apache/polygene/api/serialization/Converter.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/serialization/Converter.java b/core/api/src/main/java/org/apache/polygene/api/serialization/Converter.java
new file mode 100644
index 0000000..b411ad3
--- /dev/null
+++ b/core/api/src/main/java/org/apache/polygene/api/serialization/Converter.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.api.serialization;
+
+/**
+ * Converter for (de)serialization.
+ *
+ * Convert instances of {@link T} to String and the other way around.
+ *
+ * @param <T> the converted type
+ */
+public interface Converter<T>
+{
+ /**
+ * @return the converted type
+ */
+ Class<T> type();
+
+ /**
+ * Convert.
+ *
+ * @param object the {@link T} to convert to String, never null
+ * @return the String representation of the given object
+ */
+ String toString( T object );
+
+ /**
+ * Revert.
+ *
+ * @param string the String to convert back to {@link T}
+ * @return the {@link T}
+ */
+ T fromString( String string );
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/55916ef8/core/api/src/main/java/org/apache/polygene/api/serialization/Converters.java
----------------------------------------------------------------------
diff --git a/core/api/src/main/java/org/apache/polygene/api/serialization/Converters.java b/core/api/src/main/java/org/apache/polygene/api/serialization/Converters.java
new file mode 100644
index 0000000..6b8cbef
--- /dev/null
+++ b/core/api/src/main/java/org/apache/polygene/api/serialization/Converters.java
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.api.serialization;
+
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.type.HasTypes;
+import org.apache.polygene.api.type.ValueType;
+
+import static org.apache.polygene.api.type.HasTypesCollectors.closestType;
+
+/**
+ * Serialization Converters.
+ */
+@Mixins( Converters.Mixin.class )
+public interface Converters
+{
+ /**
+ * Register a converter for a value type.
+ *
+ * @param valueType the value type
+ * @param converter the converter
+ */
+ void registerConverter( ValueType valueType, Converter<?> converter );
+
+ /**
+ * Find a matching converter amongst registered ones.
+ *
+ * See {@link org.apache.polygene.api.type.HasTypesCollectors#closestType(HasTypes)}.
+ *
+ * @param valueType the value type
+ * @param <T> the converted type
+ * @return the closest matching registered converter, or {@literal null} if none
+ */
+ <T> Converter<T> converterFor( ValueType valueType );
+
+ default <T> Converter<T> converterFor( Class<? extends T> type )
+ {
+ return converterFor( ValueType.of( type ) );
+ }
+
+ /**
+ * Serialization Converters default Mixin.
+ */
+ class Mixin implements Converters
+ {
+ private final Map<ValueType, Converter<?>> converters = new LinkedHashMap<>();
+
+ @Override
+ public void registerConverter( ValueType valueType, Converter<?> converter )
+ {
+ converters.put( valueType, converter );
+ }
+
+ @Override
+ public <T> Converter<T> converterFor( ValueType valueType )
+ {
+ Converter<T> converter = castConverter( converters.keySet().stream()
+ .collect( closestType( valueType ) )
+ .map( converters::get )
+ .orElse( null ) );
+ if( converter != null )
+ {
+ return converter;
+ }
+ if( valueType.primaryType().isEnum() )
+ {
+ return new EnumConverter( valueType.primaryType() );
+ }
+ return null;
+ }
+
+ @SuppressWarnings( "unchecked" )
+ private <T> Converter<T> castConverter( Converter<?> converter )
+ {
+ return (Converter<T>) converter;
+ }
+
+ private static class EnumConverter<E extends Enum<E>> implements Converter<E>
+ {
+ private final Class<E> enumType;
+ private final Map<String, E> values;
+
+ private EnumConverter( final Class<E> enumType )
+ {
+ this.enumType = enumType;
+ E[] enumValues = enumType.getEnumConstants();
+ this.values = new HashMap<>( enumValues.length );
+ for( E enumValue : enumValues )
+ {
+ values.put( enumValue.name(), enumValue );
+ }
+ }
+
+ @Override
+ public Class<E> type()
+ {
+ return enumType;
+ }
+
+ @Override
+ public String toString( E object )
+ {
+ return object.name();
+ }
+
+ @Override
+ public E fromString( String string )
+ {
+ return values.get( string );
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/55916ef8/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java
index b9d9e94..a1e5d75 100644
--- a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonDeserializer.java
@@ -41,12 +41,13 @@ import org.apache.polygene.api.entity.EntityReference;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.injection.scope.Uses;
import org.apache.polygene.api.property.PropertyDescriptor;
+import org.apache.polygene.api.serialization.Converter;
+import org.apache.polygene.api.serialization.Converters;
import org.apache.polygene.api.serialization.SerializationException;
import org.apache.polygene.api.service.ServiceDescriptor;
import org.apache.polygene.api.structure.ModuleDescriptor;
import org.apache.polygene.api.type.ArrayType;
import org.apache.polygene.api.type.CollectionType;
-import org.apache.polygene.api.type.EnumType;
import org.apache.polygene.api.type.MapType;
import org.apache.polygene.api.type.ValueCompositeType;
import org.apache.polygene.api.type.ValueType;
@@ -69,6 +70,9 @@ import static org.apache.polygene.serialization.javaxjson.JavaxJson.requireJsonS
public class JavaxJsonDeserializer extends AbstractTextDeserializer implements JsonDeserializer
{
@This
+ private Converters converters;
+
+ @This
private JavaxJsonAdapters adapters;
@Uses
@@ -87,16 +91,17 @@ public class JavaxJsonDeserializer extends AbstractTextDeserializer implements J
{
return null;
}
+ Converter<Object> converter = converters.converterFor( valueType );
+ if( converter != null )
+ {
+ return (T) converter.fromString( doDeserialize( module, ValueType.STRING, json ).toString() );
+ }
JavaxJsonAdapter<?> adapter = adapters.adapterFor( valueType );
if( adapter != null )
{
return (T) adapter.deserialize( json, ( jsonValue, type ) -> doDeserialize( module, type, jsonValue ) );
}
Class<? extends ValueType> valueTypeClass = valueType.getClass();
- if( EnumType.class.isAssignableFrom( valueTypeClass ) )
- {
- return (T) Enum.valueOf( (Class) valueType.primaryType(), asString( json ) );
- }
if( ArrayType.class.isAssignableFrom( valueTypeClass ) )
{
return (T) deserializeArray( module, (ArrayType) valueType, json );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/55916ef8/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializationService.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializationService.java b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializationService.java
index 2b662ea..2618db7 100644
--- a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializationService.java
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializationService.java
@@ -17,32 +17,21 @@
*/
package org.apache.polygene.serialization.javaxjson;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.time.Duration;
-import java.time.Instant;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.LocalTime;
-import java.time.OffsetDateTime;
-import java.time.Period;
-import java.time.ZonedDateTime;
import java.util.function.BiFunction;
import java.util.function.Function;
import javax.json.Json;
import javax.json.JsonNumber;
import javax.json.JsonString;
import javax.json.JsonValue;
-import org.apache.polygene.api.entity.EntityReference;
-import org.apache.polygene.api.identity.Identity;
-import org.apache.polygene.api.identity.StringIdentity;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.injection.scope.Uses;
import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.serialization.Converters;
import org.apache.polygene.api.serialization.SerializationException;
import org.apache.polygene.api.service.ServiceActivation;
import org.apache.polygene.api.service.ServiceDescriptor;
import org.apache.polygene.api.type.ValueType;
+import org.apache.polygene.spi.serialization.BuiltInConverters;
// TODO Move into JavaxJsonSerialization
// TODO Do the same on XML & MessagePack
@@ -55,6 +44,12 @@ public interface JavaxJsonSerializationService extends JavaxJsonSerialization, S
private ServiceDescriptor descriptor;
@This
+ private BuiltInConverters builtInConverters;
+
+ @This
+ private Converters converters;
+
+ @This
private JavaxJsonAdapters adapters;
private boolean registrationDone = false;
@@ -64,6 +59,8 @@ public interface JavaxJsonSerializationService extends JavaxJsonSerialization, S
{
if( !registrationDone )
{
+ registerCustomConverters();
+ registerBuiltInConverters();
registerCustomAdapters();
registerBaseAdapters();
registrationDone = true;
@@ -73,6 +70,16 @@ public interface JavaxJsonSerializationService extends JavaxJsonSerialization, S
@Override
public void passivateService() {}
+ private void registerCustomConverters()
+ {
+ // TODO register custom converters
+ }
+
+ private void registerBuiltInConverters()
+ {
+ builtInConverters.registerBuiltInConverters( converters );
+ }
+
private void registerCustomAdapters()
{
JavaxJsonSettings.orDefault( descriptor.metaInfo( JavaxJsonSettings.class ) )
@@ -92,24 +99,6 @@ public interface JavaxJsonSerializationService extends JavaxJsonSerialization, S
adapters.registerAdapter( ValueType.BYTE, new ByteAdapter() );
adapters.registerAdapter( ValueType.FLOAT, new FloatAdapter() );
adapters.registerAdapter( ValueType.DOUBLE, new DoubleAdapter() );
-
- // Number types
- adapters.registerAdapter( ValueType.BIG_DECIMAL, new BigDecimalAdapter() );
- adapters.registerAdapter( ValueType.BIG_INTEGER, new BigIntegerAdapter() );
-
- // Date types
- adapters.registerAdapter( ValueType.INSTANT, new InstantAdapter() );
- adapters.registerAdapter( ValueType.ZONED_DATE_TIME, new ZonedDateTimeAdapter() );
- adapters.registerAdapter( ValueType.OFFSET_DATE_TIME, new OffsetDateTimeAdapter() );
- adapters.registerAdapter( ValueType.LOCAL_DATE_TIME, new LocalDateTimeAdapter() );
- adapters.registerAdapter( ValueType.LOCAL_DATE, new LocalDateAdapter() );
- adapters.registerAdapter( ValueType.LOCAL_TIME, new LocalTimeAdapter() );
- adapters.registerAdapter( ValueType.DURATION, new DurationAdapter() );
- adapters.registerAdapter( ValueType.PERIOD, new PeriodAdapter() );
-
- // Other supported types
- adapters.registerAdapter( ValueType.IDENTITY, new IdentityAdapter() );
- adapters.registerAdapter( ValueType.ENTITY_REFERENCE, new EntityReferenceAdapter() );
}
private static abstract class ToJsonStringAdapter<T> implements JavaxJsonAdapter<T>
@@ -357,177 +346,5 @@ public interface JavaxJsonSerializationService extends JavaxJsonSerialization, S
}
}
}
-
- private static class BigDecimalAdapter extends ToJsonStringAdapter<BigDecimal>
- {
- @Override
- public Class<BigDecimal> type() { return BigDecimal.class; }
-
- @Override
- public BigDecimal deserialize( JsonValue json,
- BiFunction<JsonValue, ValueType, Object> deserializeFunction )
- {
- switch( json.getValueType() )
- {
- case NULL:
- return null;
- case NUMBER:
- return new BigDecimal( json.toString() );
- case STRING:
- return new BigDecimal( ( (JsonString) json ).getString() );
- default:
- throw new SerializationException(
- "Don't know how to deserialize BigDecimal from " + json );
- }
- }
- }
-
- private static class BigIntegerAdapter extends ToJsonStringAdapter<BigInteger>
- {
- @Override
- public Class<BigInteger> type() { return BigInteger.class; }
-
- @Override
- public BigInteger deserialize( JsonValue json,
- BiFunction<JsonValue, ValueType, Object> deserializeFunction )
- {
- switch( json.getValueType() )
- {
- case NULL:
- return null;
- case NUMBER:
- return new BigInteger( json.toString() );
- case STRING:
- return new BigInteger( ( (JsonString) json ).getString() );
- default:
- throw new SerializationException(
- "Don't know how to deserialize BigInteger from " + json );
- }
- }
- }
-
- private static class PeriodAdapter extends ToJsonStringAdapter<Period>
- {
- @Override
- public Class<Period> type() { return Period.class; }
-
- @Override
- public Period deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
- {
- return Period.parse( JavaxJson.asString( json ) );
- }
- }
-
- private static class DurationAdapter extends ToJsonStringAdapter<Duration>
- {
- @Override
- public Class<Duration> type() { return Duration.class; }
-
- @Override
- public Duration deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
- {
- return Duration.parse( JavaxJson.asString( json ) );
- }
- }
-
- private static class LocalTimeAdapter extends ToJsonStringAdapter<LocalTime>
- {
- @Override
- public Class<LocalTime> type() { return LocalTime.class; }
-
- @Override
- public LocalTime deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
- {
- return LocalTime.parse( JavaxJson.asString( json ) );
- }
- }
-
- private static class LocalDateAdapter extends ToJsonStringAdapter<LocalDate>
- {
- @Override
- public Class<LocalDate> type() { return LocalDate.class; }
-
- @Override
- public LocalDate deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
- {
- return LocalDate.parse( JavaxJson.asString( json ) );
- }
- }
-
- private static class LocalDateTimeAdapter extends ToJsonStringAdapter<LocalDateTime>
- {
- @Override
- public Class<LocalDateTime> type() { return LocalDateTime.class; }
-
- @Override
- public LocalDateTime deserialize( JsonValue json,
- BiFunction<JsonValue, ValueType, Object> deserializeFunction )
- {
- return LocalDateTime.parse( JavaxJson.asString( json ) );
- }
- }
-
- private static class OffsetDateTimeAdapter extends ToJsonStringAdapter<OffsetDateTime>
- {
- @Override
- public Class<OffsetDateTime> type() { return OffsetDateTime.class; }
-
- @Override
- public OffsetDateTime deserialize( JsonValue json,
- BiFunction<JsonValue, ValueType, Object> deserializeFunction )
- {
- return OffsetDateTime.parse( JavaxJson.asString( json ) );
- }
- }
-
- private static class ZonedDateTimeAdapter extends ToJsonStringAdapter<ZonedDateTime>
- {
- @Override
- public Class<ZonedDateTime> type() { return ZonedDateTime.class; }
-
- @Override
- public ZonedDateTime deserialize( JsonValue json,
- BiFunction<JsonValue, ValueType, Object> deserializeFunction )
- {
- return ZonedDateTime.parse( JavaxJson.asString( json ) );
- }
- }
-
- private static class InstantAdapter extends ToJsonStringAdapter<Instant>
- {
- @Override
- public Class<Instant> type() { return Instant.class; }
-
- @Override
- public Instant deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
- {
- return Instant.parse( JavaxJson.asString( json ) );
- }
- }
-
- private static class IdentityAdapter extends ToJsonStringAdapter<Identity>
- {
- @Override
- public Class<Identity> type() { return Identity.class; }
-
- @Override
- public Identity deserialize( JsonValue json, BiFunction<JsonValue, ValueType, Object> deserializeFunction )
- {
- return StringIdentity.fromString( JavaxJson.asString( json ) );
- }
- }
-
- private static class EntityReferenceAdapter extends ToJsonStringAdapter<EntityReference>
- {
- @Override
- public Class<EntityReference> type() { return EntityReference.class; }
-
- @Override
- public EntityReference deserialize( JsonValue json,
- BiFunction<JsonValue, ValueType, Object> deserializeFunction )
- {
- return EntityReference.parseEntityReference( JavaxJson.asString( json ) );
- }
- }
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/55916ef8/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java
index c93c822..07294a9 100644
--- a/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java
+++ b/core/spi/src/main/java/org/apache/polygene/serialization/javaxjson/JavaxJsonSerializer.java
@@ -39,9 +39,10 @@ import org.apache.polygene.api.association.AssociationStateHolder;
import org.apache.polygene.api.composite.CompositeInstance;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.injection.scope.Uses;
+import org.apache.polygene.api.serialization.Converter;
+import org.apache.polygene.api.serialization.Converters;
import org.apache.polygene.api.service.ServiceDescriptor;
import org.apache.polygene.api.type.ArrayType;
-import org.apache.polygene.api.type.EnumType;
import org.apache.polygene.api.type.MapType;
import org.apache.polygene.api.type.ValueCompositeType;
import org.apache.polygene.api.type.ValueType;
@@ -58,6 +59,9 @@ import static org.apache.polygene.api.util.Collectors.toMap;
public class JavaxJsonSerializer extends AbstractTextSerializer implements JsonSerializer
{
@This
+ private Converters converters;
+
+ @This
private JavaxJsonAdapters adapters;
@Uses
@@ -76,15 +80,16 @@ public class JavaxJsonSerializer extends AbstractTextSerializer implements JsonS
return JsonValue.NULL;
}
Class<?> objectClass = object.getClass();
+ Converter<Object> converter = converters.converterFor( objectClass );
+ if( converter != null )
+ {
+ return doSerialize( options, converter.toString( object ), false );
+ }
JavaxJsonAdapter<?> adapter = adapters.adapterFor( objectClass );
if( adapter != null )
{
return adapter.serialize( object, obj -> doSerialize( options, obj, false ) );
}
- if( EnumType.isEnum( objectClass ) )
- {
- return JavaxJson.toJsonString( object.toString() );
- }
if( ValueCompositeType.isValueComposite( objectClass ) )
{
return serializeValueComposite( options, object, root );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/55916ef8/core/spi/src/main/java/org/apache/polygene/spi/serialization/BuiltInConverters.java
----------------------------------------------------------------------
diff --git a/core/spi/src/main/java/org/apache/polygene/spi/serialization/BuiltInConverters.java b/core/spi/src/main/java/org/apache/polygene/spi/serialization/BuiltInConverters.java
new file mode 100644
index 0000000..a6392ff
--- /dev/null
+++ b/core/spi/src/main/java/org/apache/polygene/spi/serialization/BuiltInConverters.java
@@ -0,0 +1,235 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.spi.serialization;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.OffsetDateTime;
+import java.time.Period;
+import java.time.ZonedDateTime;
+import org.apache.polygene.api.entity.EntityReference;
+import org.apache.polygene.api.identity.Identity;
+import org.apache.polygene.api.identity.StringIdentity;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.serialization.Converter;
+import org.apache.polygene.api.serialization.Converters;
+import org.apache.polygene.api.type.ValueType;
+
+/**
+ * Built-in serialization converters.
+ */
+@Mixins( BuiltInConverters.Mixin.class )
+public interface BuiltInConverters
+{
+ void registerBuiltInConverters( Converters converters );
+
+ class Mixin implements BuiltInConverters
+ {
+ @Override
+ public void registerBuiltInConverters( Converters converters )
+ {
+ // Polygene types
+ converters.registerConverter( ValueType.IDENTITY, new IdentityConverter() );
+ converters.registerConverter( ValueType.ENTITY_REFERENCE, new EntityReferenceConverter() );
+
+ // Big numbers types
+ converters.registerConverter( ValueType.BIG_DECIMAL, new BigDecimalConverter() );
+ converters.registerConverter( ValueType.BIG_INTEGER, new BigIntegerConverter() );
+
+ // Date types
+ converters.registerConverter( ValueType.INSTANT, new InstantConverter() );
+ converters.registerConverter( ValueType.ZONED_DATE_TIME, new ZonedDateTimeConverter() );
+ converters.registerConverter( ValueType.OFFSET_DATE_TIME, new OffsetDateTimeConverter() );
+ converters.registerConverter( ValueType.LOCAL_DATE_TIME, new LocalDateTimeConverter() );
+ converters.registerConverter( ValueType.LOCAL_DATE, new LocalDateConverter() );
+ converters.registerConverter( ValueType.LOCAL_TIME, new LocalTimeConverter() );
+ converters.registerConverter( ValueType.DURATION, new DurationConverter() );
+ converters.registerConverter( ValueType.PERIOD, new PeriodConverter() );
+ }
+
+ private static abstract class ToStringConverter<T> implements Converter<T>
+ {
+ @Override
+ public String toString( T object )
+ {
+ return object.toString();
+ }
+ }
+
+ private static class IdentityConverter extends ToStringConverter<Identity>
+ {
+ @Override
+ public Class<Identity> type()
+ {
+ return Identity.class;
+ }
+
+ @Override
+ public Identity fromString( String string )
+ {
+ return StringIdentity.fromString( string );
+ }
+ }
+
+ private static class EntityReferenceConverter extends ToStringConverter<EntityReference>
+ {
+ @Override
+ public Class<EntityReference> type()
+ {
+ return EntityReference.class;
+ }
+
+ @Override
+ public EntityReference fromString( String string )
+ {
+ return EntityReference.parseEntityReference( string );
+ }
+ }
+
+ private static class BigDecimalConverter extends ToStringConverter<BigDecimal>
+ {
+ @Override
+ public Class<BigDecimal> type()
+ {
+ return BigDecimal.class;
+ }
+
+ @Override
+ public BigDecimal fromString( String string )
+ {
+ return new BigDecimal( string );
+ }
+ }
+
+ private static class BigIntegerConverter extends ToStringConverter<BigInteger>
+ {
+ @Override
+ public Class<BigInteger> type()
+ {
+ return BigInteger.class;
+ }
+
+ @Override
+ public BigInteger fromString( String string )
+ {
+ return new BigInteger( string );
+ }
+ }
+
+ private static class PeriodConverter extends ToStringConverter<Period>
+ {
+ @Override
+ public Class<Period> type() { return Period.class; }
+
+ @Override
+ public Period fromString( String string )
+ {
+ return Period.parse( string );
+ }
+ }
+
+ private static class DurationConverter extends ToStringConverter<Duration>
+ {
+ @Override
+ public Class<Duration> type() { return Duration.class; }
+
+ @Override
+ public Duration fromString( String string )
+ {
+ return Duration.parse( string );
+ }
+ }
+
+ private static class LocalTimeConverter extends ToStringConverter<LocalTime>
+ {
+ @Override
+ public Class<LocalTime> type() { return LocalTime.class; }
+
+ @Override
+ public LocalTime fromString( String string )
+ {
+ return LocalTime.parse( string );
+ }
+ }
+
+ private static class LocalDateConverter extends ToStringConverter<LocalDate>
+ {
+ @Override
+ public Class<LocalDate> type() { return LocalDate.class; }
+
+ @Override
+ public LocalDate fromString( String string )
+ {
+ return LocalDate.parse( string );
+ }
+ }
+
+ private static class LocalDateTimeConverter extends ToStringConverter<LocalDateTime>
+ {
+ @Override
+ public Class<LocalDateTime> type() { return LocalDateTime.class; }
+
+ @Override
+ public LocalDateTime fromString( String string )
+ {
+ return LocalDateTime.parse( string );
+ }
+ }
+
+ private static class OffsetDateTimeConverter extends ToStringConverter<OffsetDateTime>
+ {
+ @Override
+ public Class<OffsetDateTime> type() { return OffsetDateTime.class; }
+
+ @Override
+ public OffsetDateTime fromString( String string )
+ {
+ return OffsetDateTime.parse( string );
+ }
+ }
+
+ private static class ZonedDateTimeConverter extends ToStringConverter<ZonedDateTime>
+ {
+ @Override
+ public Class<ZonedDateTime> type() { return ZonedDateTime.class; }
+
+ @Override
+ public ZonedDateTime fromString( String string )
+ {
+ return ZonedDateTime.parse( string );
+ }
+ }
+
+ private static class InstantConverter extends ToStringConverter<Instant>
+ {
+ @Override
+ public Class<Instant> type() { return Instant.class; }
+
+ @Override
+ public Instant fromString( String string )
+ {
+ return Instant.parse( string );
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/55916ef8/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
index 25f5a22..f477a8c 100644
--- a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDeserializer.java
@@ -41,6 +41,8 @@ import org.apache.polygene.api.entity.EntityReference;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.injection.scope.Uses;
import org.apache.polygene.api.property.PropertyDescriptor;
+import org.apache.polygene.api.serialization.Converter;
+import org.apache.polygene.api.serialization.Converters;
import org.apache.polygene.api.serialization.SerializationException;
import org.apache.polygene.api.service.ServiceDescriptor;
import org.apache.polygene.api.structure.ModuleDescriptor;
@@ -69,6 +71,9 @@ public class JavaxXmlDeserializer extends AbstractTextDeserializer implements Xm
private static final String NULL_ELEMENT_NAME = "null";
@This
+ private Converters converters;
+
+ @This
private JavaxXmlAdapters adapters;
@Uses
@@ -97,6 +102,11 @@ public class JavaxXmlDeserializer extends AbstractTextDeserializer implements Xm
{
return null;
}
+ Converter<Object> converter = converters.converterFor( valueType );
+ if( converter != null )
+ {
+ return (T) converter.fromString( doDeserialize( module, ValueType.STRING, xml ).toString() );
+ }
JavaxXmlAdapter<?> adapter = adapters.adapterFor( valueType );
if( adapter != null )
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/55916ef8/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializationService.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializationService.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializationService.java
index 3917340..10b692e 100644
--- a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializationService.java
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializationService.java
@@ -17,27 +17,16 @@
*/
package org.apache.polygene.serialization.javaxxml;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.time.Duration;
-import java.time.Instant;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.LocalTime;
-import java.time.OffsetDateTime;
-import java.time.Period;
-import java.time.ZonedDateTime;
import java.util.function.BiFunction;
import java.util.function.Function;
-import org.apache.polygene.api.entity.EntityReference;
-import org.apache.polygene.api.identity.Identity;
-import org.apache.polygene.api.identity.StringIdentity;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.injection.scope.Uses;
import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.serialization.Converters;
import org.apache.polygene.api.service.ServiceActivation;
import org.apache.polygene.api.service.ServiceDescriptor;
import org.apache.polygene.api.type.ValueType;
+import org.apache.polygene.spi.serialization.BuiltInConverters;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
@@ -50,6 +39,12 @@ public interface JavaxXmlSerializationService extends JavaxXmlSerialization, Ser
private ServiceDescriptor descriptor;
@This
+ private BuiltInConverters builtInConverters;
+
+ @This
+ private Converters converters;
+
+ @This
private JavaxXmlAdapters adapters;
private boolean registrationDone = false;
@@ -59,6 +54,8 @@ public interface JavaxXmlSerializationService extends JavaxXmlSerialization, Ser
{
if( !registrationDone )
{
+ registerCustomConverters();
+ registerBuiltInConverters();
registerCustomAdapters();
registerBaseAdapters();
registrationDone = true;
@@ -68,6 +65,16 @@ public interface JavaxXmlSerializationService extends JavaxXmlSerialization, Ser
@Override
public void passivateService() {}
+ private void registerCustomConverters()
+ {
+ // TODO register custom converters
+ }
+
+ private void registerBuiltInConverters()
+ {
+ builtInConverters.registerBuiltInConverters( converters );
+ }
+
private void registerCustomAdapters()
{
JavaxXmlSettings.orDefault( descriptor.metaInfo( JavaxXmlSettings.class ) )
@@ -87,24 +94,6 @@ public interface JavaxXmlSerializationService extends JavaxXmlSerialization, Ser
adapters.registerAdapter( ValueType.BYTE, new ByteAdapter() );
adapters.registerAdapter( ValueType.FLOAT, new FloatAdapter() );
adapters.registerAdapter( ValueType.DOUBLE, new DoubleAdapter() );
-
- // Number types
- adapters.registerAdapter( ValueType.BIG_DECIMAL, new BigDecimalAdapter() );
- adapters.registerAdapter( ValueType.BIG_INTEGER, new BigIntegerAdapter() );
-
- // Date types
- adapters.registerAdapter( ValueType.INSTANT, new InstantAdapter() );
- adapters.registerAdapter( ValueType.ZONED_DATE_TIME, new ZonedDateTimeAdapter() );
- adapters.registerAdapter( ValueType.OFFSET_DATE_TIME, new OffsetDateTimeAdapter() );
- adapters.registerAdapter( ValueType.LOCAL_DATE_TIME, new LocalDateTimeAdapter() );
- adapters.registerAdapter( ValueType.LOCAL_DATE, new LocalDateAdapter() );
- adapters.registerAdapter( ValueType.LOCAL_TIME, new LocalTimeAdapter() );
- adapters.registerAdapter( ValueType.DURATION, new DurationAdapter() );
- adapters.registerAdapter( ValueType.PERIOD, new PeriodAdapter() );
-
- // Other supported types
- adapters.registerAdapter( ValueType.IDENTITY, new IdentityAdapter() );
- adapters.registerAdapter( ValueType.ENTITY_REFERENCE, new EntityReferenceAdapter() );
}
private static abstract class ToStringTextNodeAdapter<T> implements JavaxXmlAdapter<T>
@@ -224,149 +213,5 @@ public interface JavaxXmlSerializationService extends JavaxXmlSerialization, Ser
return Double.valueOf( node.getNodeValue() );
}
}
-
- private static class BigDecimalAdapter extends ToStringTextNodeAdapter<BigDecimal>
- {
- @Override
- public Class<BigDecimal> type() { return BigDecimal.class; }
-
- @Override
- public BigDecimal deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
- {
- return new BigDecimal( node.getNodeValue() );
- }
- }
-
- private static class BigIntegerAdapter extends ToStringTextNodeAdapter<BigInteger>
- {
- @Override
- public Class<BigInteger> type() { return BigInteger.class; }
-
- @Override
- public BigInteger deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
- {
- return new BigInteger( node.getNodeValue() );
- }
- }
-
- private static class InstantAdapter extends ToStringTextNodeAdapter<Instant>
- {
- @Override
- public Class<Instant> type() { return Instant.class; }
-
- @Override
- public Instant deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
- {
- return Instant.parse( node.getNodeValue() );
- }
- }
-
- private static class ZonedDateTimeAdapter extends ToStringTextNodeAdapter<ZonedDateTime>
- {
- @Override
- public Class<ZonedDateTime> type() { return ZonedDateTime.class; }
-
- @Override
- public ZonedDateTime deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
- {
- return ZonedDateTime.parse( node.getNodeValue() );
- }
- }
-
- private static class OffsetDateTimeAdapter extends ToStringTextNodeAdapter<OffsetDateTime>
- {
- @Override
- public Class<OffsetDateTime> type() { return OffsetDateTime.class; }
-
- @Override
- public OffsetDateTime deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
- {
- return OffsetDateTime.parse( node.getNodeValue() );
- }
- }
-
- private static class LocalDateTimeAdapter extends ToStringTextNodeAdapter<LocalDateTime>
- {
- @Override
- public Class<LocalDateTime> type() { return LocalDateTime.class; }
-
- @Override
- public LocalDateTime deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
- {
- return LocalDateTime.parse( node.getNodeValue() );
- }
- }
-
- private static class LocalDateAdapter extends ToStringTextNodeAdapter<LocalDate>
- {
- @Override
- public Class<LocalDate> type() { return LocalDate.class; }
-
- @Override
- public LocalDate deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
- {
- return LocalDate.parse( node.getNodeValue() );
- }
- }
-
- private static class LocalTimeAdapter extends ToStringTextNodeAdapter<LocalTime>
- {
- @Override
- public Class<LocalTime> type() { return LocalTime.class; }
-
- @Override
- public LocalTime deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
- {
- return LocalTime.parse( node.getNodeValue() );
- }
- }
-
- private static class DurationAdapter extends ToStringTextNodeAdapter<Duration>
- {
- @Override
- public Class<Duration> type() { return Duration.class; }
-
- @Override
- public Duration deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
- {
- return Duration.parse( node.getNodeValue() );
- }
- }
-
- private static class PeriodAdapter extends ToStringTextNodeAdapter<Period>
- {
- @Override
- public Class<Period> type() { return Period.class; }
-
- @Override
- public Period deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
- {
- return Period.parse( node.getNodeValue() );
- }
- }
-
- private static class IdentityAdapter extends ToStringTextNodeAdapter<Identity>
- {
- @Override
- public Class<Identity> type() { return Identity.class; }
-
- @Override
- public Identity deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
- {
- return StringIdentity.fromString( node.getNodeValue() );
- }
- }
-
- private static class EntityReferenceAdapter extends ToStringTextNodeAdapter<EntityReference>
- {
- @Override
- public Class<EntityReference> type() { return EntityReference.class; }
-
- @Override
- public EntityReference deserialize( Node node, BiFunction<Node, ValueType, Object> deserializationFunction )
- {
- return EntityReference.parseEntityReference( node.getNodeValue() );
- }
- }
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/55916ef8/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java
index f0ce0fa..49f1fa0 100644
--- a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java
@@ -34,6 +34,8 @@ import org.apache.polygene.api.composite.CompositeInstance;
import org.apache.polygene.api.entity.EntityReference;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.injection.scope.Uses;
+import org.apache.polygene.api.serialization.Converter;
+import org.apache.polygene.api.serialization.Converters;
import org.apache.polygene.api.serialization.SerializationException;
import org.apache.polygene.api.service.ServiceDescriptor;
import org.apache.polygene.api.type.ArrayType;
@@ -61,6 +63,9 @@ public class JavaxXmlSerializer extends AbstractTextSerializer implements XmlSer
private static final String NULL_ELEMENT_NAME = "null";
@This
+ private Converters converters;
+
+ @This
private JavaxXmlAdapters adapters;
@Uses
@@ -99,6 +104,11 @@ public class JavaxXmlSerializer extends AbstractTextSerializer implements XmlSer
return document.createElement( NULL_ELEMENT_NAME );
}
Class<?> objectClass = object.getClass();
+ Converter<Object> converter = converters.converterFor( objectClass );
+ if( converter != null )
+ {
+ return doSerialize( document, options, converter.toString( object ), false );
+ }
JavaxXmlAdapter<?> adapter = adapters.adapterFor( objectClass );
if( adapter != null )
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/55916ef8/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
index 70b4b8a..7a82751 100644
--- a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
+++ b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
@@ -39,6 +39,8 @@ import org.apache.polygene.api.entity.EntityReference;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.property.PropertyDescriptor;
+import org.apache.polygene.api.serialization.Converter;
+import org.apache.polygene.api.serialization.Converters;
import org.apache.polygene.api.serialization.Deserializer;
import org.apache.polygene.api.serialization.SerializationException;
import org.apache.polygene.api.structure.ModuleDescriptor;
@@ -70,6 +72,9 @@ public interface MessagePackDeserializer extends Deserializer
class Mixin extends AbstractBinaryDeserializer
{
@This
+ private Converters converters;
+
+ @This
private MessagePackAdapters adapters;
@Override
@@ -100,6 +105,11 @@ public interface MessagePackDeserializer extends Deserializer
{
return null;
}
+ Converter<Object> converter = converters.converterFor( valueType );
+ if( converter != null )
+ {
+ return (T) converter.fromString( doDeserialize( module, ValueType.STRING, value ).toString() );
+ }
MessagePackAdapter<?> adapter = adapters.adapterFor( valueType );
if( adapter != null )
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/55916ef8/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializationService.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializationService.java b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializationService.java
index 4cd23b7..51badc3 100644
--- a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializationService.java
+++ b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializationService.java
@@ -17,27 +17,16 @@
*/
package org.apache.polygene.serialization.msgpack;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.time.Duration;
-import java.time.Instant;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.LocalTime;
-import java.time.OffsetDateTime;
-import java.time.Period;
-import java.time.ZonedDateTime;
import java.util.function.BiFunction;
import java.util.function.Function;
-import org.apache.polygene.api.entity.EntityReference;
-import org.apache.polygene.api.identity.Identity;
-import org.apache.polygene.api.identity.StringIdentity;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.injection.scope.Uses;
import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.serialization.Converters;
import org.apache.polygene.api.service.ServiceActivation;
import org.apache.polygene.api.service.ServiceDescriptor;
import org.apache.polygene.api.type.ValueType;
+import org.apache.polygene.spi.serialization.BuiltInConverters;
import org.msgpack.value.Value;
import org.msgpack.value.ValueFactory;
@@ -50,6 +39,12 @@ public interface MessagePackSerializationService extends MessagePackSerializatio
private ServiceDescriptor descriptor;
@This
+ private BuiltInConverters builtInConverters;
+
+ @This
+ private Converters converters;
+
+ @This
private MessagePackAdapters adapters;
private boolean registrationDone = false;
@@ -59,6 +54,8 @@ public interface MessagePackSerializationService extends MessagePackSerializatio
{
if( !registrationDone )
{
+ registerCustomConverters();
+ registerBuiltInConverters();
registerCustomAdapters();
registerBaseAdapters();
registrationDone = true;
@@ -68,6 +65,16 @@ public interface MessagePackSerializationService extends MessagePackSerializatio
@Override
public void passivateService() {}
+ private void registerCustomConverters()
+ {
+ // TODO register custom converters
+ }
+
+ private void registerBuiltInConverters()
+ {
+ builtInConverters.registerBuiltInConverters( converters );
+ }
+
private void registerCustomAdapters()
{
MessagePackSettings.orDefault( descriptor.metaInfo( MessagePackSettings.class ) )
@@ -87,24 +94,6 @@ public interface MessagePackSerializationService extends MessagePackSerializatio
adapters.registerAdapter( ValueType.BYTE, new ByteAdapter() );
adapters.registerAdapter( ValueType.FLOAT, new FloatAdapter() );
adapters.registerAdapter( ValueType.DOUBLE, new DoubleAdapter() );
-
- // Number types
- adapters.registerAdapter( ValueType.BIG_DECIMAL, new BigDecimalAdapter() );
- adapters.registerAdapter( ValueType.BIG_INTEGER, new BigIntegerAdapter() );
-
- // Date types
- adapters.registerAdapter( ValueType.INSTANT, new InstantAdapter() );
- adapters.registerAdapter( ValueType.ZONED_DATE_TIME, new ZonedDateTimeAdapter() );
- adapters.registerAdapter( ValueType.OFFSET_DATE_TIME, new OffsetDateTimeAdapter() );
- adapters.registerAdapter( ValueType.LOCAL_DATE_TIME, new LocalDateTimeAdapter() );
- adapters.registerAdapter( ValueType.LOCAL_DATE, new LocalDateAdapter() );
- adapters.registerAdapter( ValueType.LOCAL_TIME, new LocalTimeAdapter() );
- adapters.registerAdapter( ValueType.DURATION, new DurationAdapter() );
- adapters.registerAdapter( ValueType.PERIOD, new PeriodAdapter() );
-
- // Other supported types
- adapters.registerAdapter( ValueType.IDENTITY, new IdentityAdapter() );
- adapters.registerAdapter( ValueType.ENTITY_REFERENCE, new EntityReferenceAdapter() );
}
private static abstract class ToStringAdapter<T> implements MessagePackAdapter<T>
@@ -266,149 +255,5 @@ public interface MessagePackSerializationService extends MessagePackSerializatio
return value.asFloatValue().toDouble();
}
}
-
- private static class BigDecimalAdapter extends ToStringAdapter<BigDecimal>
- {
- @Override
- public Class<BigDecimal> type() { return BigDecimal.class; }
-
- @Override
- public BigDecimal deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
- {
- return new BigDecimal( value.asStringValue().asString() );
- }
- }
-
- private static class BigIntegerAdapter extends ToStringAdapter<BigInteger>
- {
- @Override
- public Class<BigInteger> type() { return BigInteger.class; }
-
- @Override
- public BigInteger deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
- {
- return new BigInteger( value.asStringValue().asString() );
- }
- }
-
- private static class InstantAdapter extends ToStringAdapter<Instant>
- {
- @Override
- public Class<Instant> type() { return Instant.class; }
-
- @Override
- public Instant deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
- {
- return Instant.parse( value.asStringValue().asString() );
- }
- }
-
- private static class ZonedDateTimeAdapter extends ToStringAdapter<ZonedDateTime>
- {
- @Override
- public Class<ZonedDateTime> type() { return ZonedDateTime.class; }
-
- @Override
- public ZonedDateTime deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
- {
- return ZonedDateTime.parse( value.asStringValue().asString() );
- }
- }
-
- private static class OffsetDateTimeAdapter extends ToStringAdapter<OffsetDateTime>
- {
- @Override
- public Class<OffsetDateTime> type() { return OffsetDateTime.class; }
-
- @Override
- public OffsetDateTime deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
- {
- return OffsetDateTime.parse( value.asStringValue().asString() );
- }
- }
-
- private static class LocalDateTimeAdapter extends ToStringAdapter<LocalDateTime>
- {
- @Override
- public Class<LocalDateTime> type() { return LocalDateTime.class; }
-
- @Override
- public LocalDateTime deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
- {
- return LocalDateTime.parse( value.asStringValue().asString() );
- }
- }
-
- private static class LocalDateAdapter extends ToStringAdapter<LocalDate>
- {
- @Override
- public Class<LocalDate> type() { return LocalDate.class; }
-
- @Override
- public LocalDate deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
- {
- return LocalDate.parse( value.asStringValue().asString() );
- }
- }
-
- private static class LocalTimeAdapter extends ToStringAdapter<LocalTime>
- {
- @Override
- public Class<LocalTime> type() { return LocalTime.class; }
-
- @Override
- public LocalTime deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
- {
- return LocalTime.parse( value.asStringValue().asString() );
- }
- }
-
- private static class DurationAdapter extends ToStringAdapter<Duration>
- {
- @Override
- public Class<Duration> type() { return Duration.class; }
-
- @Override
- public Duration deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
- {
- return Duration.parse( value.asStringValue().asString() );
- }
- }
-
- private static class PeriodAdapter extends ToStringAdapter<Period>
- {
- @Override
- public Class<Period> type() { return Period.class; }
-
- @Override
- public Period deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
- {
- return Period.parse( value.asStringValue().asString() );
- }
- }
-
- private static class IdentityAdapter extends ToStringAdapter<Identity>
- {
- @Override
- public Class<Identity> type() { return Identity.class; }
-
- @Override
- public Identity deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
- {
- return StringIdentity.fromString( value.asStringValue().asString() );
- }
- }
-
- private static class EntityReferenceAdapter extends ToStringAdapter<EntityReference>
- {
- @Override
- public Class<EntityReference> type() { return EntityReference.class; }
-
- @Override
- public EntityReference deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
- {
- return EntityReference.parseEntityReference( value.asStringValue().asString() );
- }
- }
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/55916ef8/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java
index a8f396c..c01ef29 100644
--- a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java
+++ b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java
@@ -30,6 +30,8 @@ import org.apache.polygene.api.common.Optional;
import org.apache.polygene.api.composite.CompositeInstance;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.serialization.Converter;
+import org.apache.polygene.api.serialization.Converters;
import org.apache.polygene.api.serialization.SerializationException;
import org.apache.polygene.api.serialization.Serializer;
import org.apache.polygene.api.type.ArrayType;
@@ -57,6 +59,9 @@ public interface MessagePackSerializer extends Serializer
class Mixin extends AbstractBinarySerializer
{
@This
+ private Converters converters;
+
+ @This
private MessagePackAdapters adapters;
@Override
@@ -84,6 +89,11 @@ public interface MessagePackSerializer extends Serializer
return ValueFactory.newNil();
}
Class<?> objectClass = object.getClass();
+ Converter<Object> converter = converters.converterFor( objectClass );
+ if( converter != null )
+ {
+ return doSerialize( options, converter.toString( object ), false );
+ }
MessagePackAdapter<?> adapter = adapters.adapterFor( objectClass );
if( adapter != null )
{
[09/50] [abbrv] polygene-java git commit: Removed some warnings.
Posted by pa...@apache.org.
Removed some warnings.
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/41c759b2
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/41c759b2
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/41c759b2
Branch: refs/heads/serialization-3.0
Commit: 41c759b2c280696126fd5428af9346cecf716d5c
Parents: 1429808
Author: niclas <ni...@spicter.com>
Authored: Sat Mar 11 19:43:03 2017 +0800
Committer: niclas <ni...@spicter.com>
Committed: Sat Mar 11 19:43:03 2017 +0800
----------------------------------------------------------------------
.../index/rdf/assembly/AbstractRdfIndexingAssembler.java | 1 +
.../polygene/index/rdf/assembly/RdfIndexingAssembler.java | 1 +
.../index/rdf/assembly/RdfRdbmsSesameStoreAssembler.java | 5 +----
3 files changed, 3 insertions(+), 4 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/41c759b2/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/AbstractRdfIndexingAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/AbstractRdfIndexingAssembler.java b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/AbstractRdfIndexingAssembler.java
index b67899e..0bea34a 100644
--- a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/AbstractRdfIndexingAssembler.java
+++ b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/AbstractRdfIndexingAssembler.java
@@ -21,6 +21,7 @@ package org.apache.polygene.index.rdf.assembly;
import org.apache.polygene.bootstrap.Assemblers;
+@SuppressWarnings( "WeakerAccess" )
public abstract class AbstractRdfIndexingAssembler<AssemblerType>
extends Assemblers.VisibilityIdentityConfig<AssemblerType>
{
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/41c759b2/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfIndexingAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfIndexingAssembler.java b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfIndexingAssembler.java
index fff60a6..05fcc42 100644
--- a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfIndexingAssembler.java
+++ b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfIndexingAssembler.java
@@ -23,6 +23,7 @@ package org.apache.polygene.index.rdf.assembly;
* This is a dummy Assembler to support the Yeoman Polygene Generator, which require naming conventions for
* the systems that it supports.
*/
+@SuppressWarnings( "unused" )
public class RdfIndexingAssembler extends RdfNativeSesameStoreAssembler
{
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/41c759b2/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfRdbmsSesameStoreAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfRdbmsSesameStoreAssembler.java b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfRdbmsSesameStoreAssembler.java
index 12e8681..5629697 100644
--- a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfRdbmsSesameStoreAssembler.java
+++ b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfRdbmsSesameStoreAssembler.java
@@ -20,18 +20,14 @@
package org.apache.polygene.index.rdf.assembly;
import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.bootstrap.Assembler;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.index.rdf.RdfIndexingEngineService;
import org.apache.polygene.index.rdf.query.RdfQueryParserFactory;
import org.apache.polygene.library.rdf.entity.EntityStateSerializer;
import org.apache.polygene.library.rdf.entity.EntityTypeSerializer;
-import org.apache.polygene.library.rdf.repository.NativeConfiguration;
import org.apache.polygene.library.rdf.repository.RdbmsRepositoryConfiguration;
import org.apache.polygene.library.rdf.repository.RdbmsRepositoryService;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
public class RdfRdbmsSesameStoreAssembler extends AbstractRdfIndexingAssembler<RdfNativeSesameStoreAssembler>
{
@@ -42,6 +38,7 @@ public class RdfRdbmsSesameStoreAssembler extends AbstractRdfIndexingAssembler<
this( Visibility.application, Visibility.module );
}
+ @SuppressWarnings( "WeakerAccess" )
public RdfRdbmsSesameStoreAssembler( Visibility indexingVisibility, Visibility repositoryVisibility )
{
visibleIn( indexingVisibility );
[18/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-client/src/test/java/org/apache/polygene/library/rest/client/ContinuousIntegrationTest.java
----------------------------------------------------------------------
diff --git a/libraries/rest-client/src/test/java/org/apache/polygene/library/rest/client/ContinuousIntegrationTest.java b/libraries/rest-client/src/test/java/org/apache/polygene/library/rest/client/ContinuousIntegrationTest.java
index 69d460e..9d66d36 100644
--- a/libraries/rest-client/src/test/java/org/apache/polygene/library/rest/client/ContinuousIntegrationTest.java
+++ b/libraries/rest-client/src/test/java/org/apache/polygene/library/rest/client/ContinuousIntegrationTest.java
@@ -19,13 +19,6 @@
*/
package org.apache.polygene.library.rest.client;
-import org.apache.polygene.test.AbstractPolygeneTest;
-import org.apache.polygene.test.util.FreePortFinder;
-import org.hamcrest.CoreMatchers;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
import org.apache.polygene.api.common.Optional;
import org.apache.polygene.api.injection.scope.Structure;
import org.apache.polygene.api.property.Property;
@@ -53,7 +46,13 @@ import org.apache.polygene.library.rest.server.api.ContextRestlet;
import org.apache.polygene.library.rest.server.assembler.RestServerAssembler;
import org.apache.polygene.library.rest.server.restlet.NullCommandResult;
import org.apache.polygene.library.rest.server.spi.CommandResult;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
+import org.apache.polygene.test.AbstractPolygeneTest;
+import org.apache.polygene.test.util.FreePortFinder;
+import org.hamcrest.CoreMatchers;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
import org.restlet.Client;
import org.restlet.Request;
import org.restlet.Response;
@@ -89,7 +88,6 @@ public class ContinuousIntegrationTest
throws AssemblyException
{
// General setup of client and server
- new OrgJsonValueSerializationAssembler().assemble( module );
new ClientAssembler().assemble( module );
new ValueAssembler().assemble( module );
new RestServerAssembler().assemble( module );
@@ -434,12 +432,12 @@ public class ContinuousIntegrationTest
public BuildResult buildStatus( BuildSpec build )
{
String buildNo = build.buildNo().get(); // or lookup by tag
- return module.newValueFromSerializedState( BuildResult.class, "{ 'buildNo':'" + buildNo + "', 'testsPassed': 37, 'testsFailed': 1}" );
+ return module.newValueFromSerializedState( BuildResult.class, "{ \"buildNo\":\"" + buildNo + "\", \"testsPassed\": 37, \"testsFailed\": 1}" );
}
public ServerStatus serverStatus()
{
- return module.newValueFromSerializedState( ServerStatus.class, "{'currentStatus':'Idle', 'availableAgents': 2 }" );
+ return module.newValueFromSerializedState( ServerStatus.class, "{\"currentStatus\":\"Idle\", \"availableAgents\": 2 }" );
}
public void tagBuild( TagBuildCommand command )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-client/src/test/java/org/apache/polygene/library/rest/client/RssReaderTest.java
----------------------------------------------------------------------
diff --git a/libraries/rest-client/src/test/java/org/apache/polygene/library/rest/client/RssReaderTest.java b/libraries/rest-client/src/test/java/org/apache/polygene/library/rest/client/RssReaderTest.java
index a5344d8..bb241df 100644
--- a/libraries/rest-client/src/test/java/org/apache/polygene/library/rest/client/RssReaderTest.java
+++ b/libraries/rest-client/src/test/java/org/apache/polygene/library/rest/client/RssReaderTest.java
@@ -27,8 +27,6 @@ import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
-import org.junit.BeforeClass;
-import org.junit.Test;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.library.rest.client.api.ContextResourceClient;
@@ -40,7 +38,8 @@ import org.apache.polygene.library.rest.client.spi.ResponseReader;
import org.apache.polygene.library.rest.client.spi.ResultHandler;
import org.apache.polygene.library.rest.common.ValueAssembler;
import org.apache.polygene.test.AbstractPolygeneTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
+import org.junit.BeforeClass;
+import org.junit.Test;
import org.restlet.Client;
import org.restlet.Response;
import org.restlet.data.Protocol;
@@ -75,7 +74,6 @@ public class RssReaderTest
throws AssemblyException
{
// General setup of client
- new OrgJsonValueSerializationAssembler().assemble( module );
new ClientAssembler().assemble( module );
new ValueAssembler().assemble( module );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-common/src/main/java/org/apache/polygene/library/rest/common/Resource.java
----------------------------------------------------------------------
diff --git a/libraries/rest-common/src/main/java/org/apache/polygene/library/rest/common/Resource.java b/libraries/rest-common/src/main/java/org/apache/polygene/library/rest/common/Resource.java
index 454a961..d9d17d7 100644
--- a/libraries/rest-common/src/main/java/org/apache/polygene/library/rest/common/Resource.java
+++ b/libraries/rest-common/src/main/java/org/apache/polygene/library/rest/common/Resource.java
@@ -55,7 +55,7 @@ public interface Resource
Link resource(String relation);
@Optional
- Property<ValueComposite> index();
+ Property<Object> index();
abstract class Mixin
implements Resource
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/api/ContextResource.java
----------------------------------------------------------------------
diff --git a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/api/ContextResource.java b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/api/ContextResource.java
index a50f29c..25cb0df 100644
--- a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/api/ContextResource.java
+++ b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/api/ContextResource.java
@@ -428,7 +428,7 @@ public class ContextResource
if( index != null && index instanceof ValueComposite )
{
- builder.prototype().index().set( (ValueComposite) index );
+ builder.prototype().index().set( index );
}
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/requestreader/DefaultRequestReader.java
----------------------------------------------------------------------
diff --git a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/requestreader/DefaultRequestReader.java b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/requestreader/DefaultRequestReader.java
index b4736af..48c32b0 100644
--- a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/requestreader/DefaultRequestReader.java
+++ b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/requestreader/DefaultRequestReader.java
@@ -41,14 +41,14 @@ import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.injection.scope.Structure;
import org.apache.polygene.api.property.PropertyDescriptor;
import org.apache.polygene.api.service.qualifier.Tagged;
+import org.apache.polygene.api.serialization.Deserializer;
+import org.apache.polygene.api.serialization.Serialization;
+import org.apache.polygene.api.serialization.SerializationException;
import org.apache.polygene.api.structure.ModuleDescriptor;
import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
import org.apache.polygene.api.value.ValueBuilder;
import org.apache.polygene.api.value.ValueBuilderFactory;
import org.apache.polygene.api.value.ValueComposite;
-import org.apache.polygene.api.value.ValueDeserializer;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.api.value.ValueSerializationException;
import org.apache.polygene.library.rest.server.spi.RequestReader;
import org.restlet.Request;
import org.restlet.Response;
@@ -86,8 +86,8 @@ public class DefaultRequestReader
private ValueBuilderFactory vbf;
@Service
- @Tagged( ValueSerialization.Formats.JSON )
- private ValueDeserializer valueDeserializer;
+ @Tagged( Serialization.Formats.JSON )
+ private Deserializer deserializer;
@Override
@SuppressWarnings( "unchecked" )
@@ -303,9 +303,9 @@ public class DefaultRequestReader
{
try
{
- return valueDeserializer.deserialize( module, propertyDescriptor.valueType(), value );
+ return deserializer.deserialize( module, propertyDescriptor.valueType(), value );
}
- catch( ValueSerializationException e )
+ catch( SerializationException e )
{
throw new IllegalArgumentException( "Query parameter has invalid JSON format", e );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/AbstractResponseWriter.java
----------------------------------------------------------------------
diff --git a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/AbstractResponseWriter.java b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/AbstractResponseWriter.java
index 7a8458e..358d81d 100644
--- a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/AbstractResponseWriter.java
+++ b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/AbstractResponseWriter.java
@@ -20,7 +20,6 @@
package org.apache.polygene.library.rest.server.restlet.responsewriter;
-import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.polygene.library.rest.server.spi.ResponseWriter;
@@ -36,7 +35,7 @@ import org.restlet.representation.Variant;
public abstract class AbstractResponseWriter
implements ResponseWriter
{
- protected static List<Language> ENGLISH = Arrays.asList( Language.ENGLISH );
+ protected static List<Language> ENGLISH = Collections.singletonList( Language.ENGLISH );
protected Variant getVariant( Request request,
List<Language> possibleLanguages,
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/DefaultResponseWriter.java
----------------------------------------------------------------------
diff --git a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/DefaultResponseWriter.java b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/DefaultResponseWriter.java
index 8e480bf..1091612 100644
--- a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/DefaultResponseWriter.java
+++ b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/DefaultResponseWriter.java
@@ -20,7 +20,7 @@
package org.apache.polygene.library.rest.server.restlet.responsewriter;
-import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
import org.restlet.Response;
import org.restlet.data.MediaType;
@@ -33,7 +33,7 @@ import org.restlet.resource.ResourceException;
public class DefaultResponseWriter
extends AbstractResponseWriter
{
- private static final List<MediaType> supportedMediaTypes = Arrays.asList( MediaType.APPLICATION_JSON );
+ private static final List<MediaType> supportedMediaTypes = Collections.singletonList( MediaType.APPLICATION_JSON );
@Override
public boolean writeResponse( final Object result, final Response response )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/FormResponseWriter.java
----------------------------------------------------------------------
diff --git a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/FormResponseWriter.java b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/FormResponseWriter.java
index 233a80b..f59d166 100644
--- a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/FormResponseWriter.java
+++ b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/FormResponseWriter.java
@@ -29,8 +29,10 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.json.JSONException;
-import org.json.JSONObject;
+import javax.json.Json;
+import javax.json.JsonException;
+import javax.json.JsonObjectBuilder;
+import javax.json.JsonValue;
import org.apache.polygene.api.injection.scope.Service;
import org.restlet.Response;
import org.restlet.data.Form;
@@ -47,7 +49,8 @@ import org.restlet.resource.ResourceException;
public class FormResponseWriter
extends AbstractResponseWriter
{
- private static final List<MediaType> supportedMediaTypes = Arrays.asList( MediaType.TEXT_HTML, MediaType.APPLICATION_JSON );
+ private static final List<MediaType> supportedMediaTypes = Arrays.asList( MediaType.TEXT_HTML,
+ MediaType.APPLICATION_JSON );
@Service
private Configuration cfg;
@@ -61,7 +64,7 @@ public class FormResponseWriter
MediaType type = getVariant( response.getRequest(), ENGLISH, supportedMediaTypes ).getMediaType();
if( MediaType.APPLICATION_JSON.equals( type ) )
{
- JSONObject json = new JSONObject();
+ JsonObjectBuilder builder = Json.createObjectBuilder();
Form form = (Form) result;
try
{
@@ -70,21 +73,21 @@ public class FormResponseWriter
String value = parameter.getValue();
if( value == null )
{
- json.put( parameter.getName(), JSONObject.NULL );
+ builder.add( parameter.getName(), JsonValue.NULL );
}
else
{
- json.put( parameter.getName(), value );
+ builder.add( parameter.getName(), value );
}
}
}
- catch( JSONException e )
+ catch( JsonException e )
{
e.printStackTrace();
}
- StringRepresentation representation
- = new StringRepresentation( json.toString(), MediaType.APPLICATION_JSON );
+ StringRepresentation representation = new StringRepresentation( builder.build().toString(),
+ MediaType.APPLICATION_JSON );
response.setEntity( representation );
return true;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/JSONResponseWriter.java
----------------------------------------------------------------------
diff --git a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/JSONResponseWriter.java b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/JSONResponseWriter.java
index 86fc8d6..6b9af86 100644
--- a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/JSONResponseWriter.java
+++ b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/JSONResponseWriter.java
@@ -22,7 +22,7 @@ package org.apache.polygene.library.rest.server.restlet.responsewriter;
import java.util.Arrays;
import java.util.List;
-import org.json.JSONObject;
+import javax.json.JsonObject;
import org.restlet.Response;
import org.restlet.data.MediaType;
import org.restlet.representation.StringRepresentation;
@@ -33,28 +33,28 @@ import org.restlet.resource.ResourceException;
*/
public class JSONResponseWriter extends AbstractResponseWriter
{
- private static final List<MediaType> supportedMediaTypes = Arrays.asList( MediaType.TEXT_HTML, MediaType.APPLICATION_JSON );
+ private static final List<MediaType> supportedMediaTypes = Arrays.asList( MediaType.TEXT_HTML,
+ MediaType.APPLICATION_JSON );
@Override
- public boolean writeResponse( final Object result, final Response response )
- throws ResourceException
+ public boolean writeResponse( Object result, Response response ) throws ResourceException
{
- if( result instanceof JSONObject )
+ if( result instanceof JsonObject )
{
MediaType type = getVariant( response.getRequest(), ENGLISH, supportedMediaTypes ).getMediaType();
if( MediaType.APPLICATION_JSON.equals( type ) )
{
- JSONObject json = (JSONObject) result;
- StringRepresentation representation
- = new StringRepresentation( json.toString(), MediaType.APPLICATION_JSON );
+ JsonObject json = (JsonObject) result;
+ StringRepresentation representation = new StringRepresentation( json.toString(),
+ MediaType.APPLICATION_JSON );
response.setEntity( representation );
return true;
}
else if( MediaType.TEXT_HTML.equals( type ) )
{
- JSONObject json = (JSONObject) result;
- StringRepresentation representation
- = new StringRepresentation( json.toString(), MediaType.TEXT_HTML );
+ JsonObject json = (JsonObject) result;
+ StringRepresentation representation = new StringRepresentation( json.toString(),
+ MediaType.TEXT_HTML );
response.setEntity( representation );
return true;
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/LinksResponseWriter.java
----------------------------------------------------------------------
diff --git a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/LinksResponseWriter.java b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/LinksResponseWriter.java
index dea6f15..dcac1db 100644
--- a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/LinksResponseWriter.java
+++ b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/LinksResponseWriter.java
@@ -25,6 +25,7 @@ import freemarker.template.TemplateException;
import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
+import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -46,7 +47,7 @@ import org.restlet.resource.ResourceException;
public class LinksResponseWriter
extends AbstractResponseWriter
{
- private static final List<MediaType> supportedLinkMediaTypes = Arrays.asList( MediaType.APPLICATION_JSON );
+ private static final List<MediaType> supportedLinkMediaTypes = Collections.singletonList( MediaType.APPLICATION_JSON );
private static final List<MediaType> supportedLinksMediaTypes = Arrays.asList( MediaType.TEXT_HTML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM );
@Service
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/TableResponseWriter.java
----------------------------------------------------------------------
diff --git a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/TableResponseWriter.java b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/TableResponseWriter.java
index a2ec82b..bbe758c 100644
--- a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/TableResponseWriter.java
+++ b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/TableResponseWriter.java
@@ -28,13 +28,18 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import javax.json.Json;
+import javax.json.JsonArrayBuilder;
+import javax.json.JsonException;
+import javax.json.JsonObjectBuilder;
import org.apache.polygene.api.injection.scope.Service;
+import org.apache.polygene.api.injection.scope.Structure;
+import org.apache.polygene.api.structure.ModuleDescriptor;
import org.apache.polygene.library.rest.common.table.Cell;
import org.apache.polygene.library.rest.common.table.Column;
import org.apache.polygene.library.rest.common.table.Row;
import org.apache.polygene.library.rest.common.table.Table;
-import org.json.JSONException;
-import org.json.JSONWriter;
+import org.apache.polygene.spi.serialization.JsonSerializer;
import org.restlet.Response;
import org.restlet.data.CharacterSet;
import org.restlet.data.MediaType;
@@ -47,7 +52,14 @@ import org.restlet.resource.ResourceException;
*/
public class TableResponseWriter extends AbstractResponseWriter
{
- private static final List<MediaType> supportedMediaTypes = Arrays.asList( MediaType.TEXT_HTML, MediaType.APPLICATION_JSON );
+ private static final List<MediaType> supportedMediaTypes = Arrays.asList( MediaType.TEXT_HTML,
+ MediaType.APPLICATION_JSON );
+
+ @Structure
+ private ModuleDescriptor module;
+
+ @Service
+ private JsonSerializer jsonSerializer;
@Service
private Configuration cfg;
@@ -61,7 +73,6 @@ public class TableResponseWriter extends AbstractResponseWriter
MediaType type = getVariant( response.getRequest(), ENGLISH, supportedMediaTypes ).getMediaType();
if( MediaType.APPLICATION_JSON.equals( type ) )
{
-
response.setEntity( new WriterRepresentation( MediaType.APPLICATION_JSON )
{
@Override
@@ -70,11 +81,12 @@ public class TableResponseWriter extends AbstractResponseWriter
{
try
{
- JSONWriter json = new JSONWriter( writer );
+ JsonObjectBuilder builder = Json.createObjectBuilder();
Table tableValue = (Table) result;
// Parse parameters
- String tqx = response.getRequest().getResourceRef().getQueryAsForm().getFirstValue( "tqx" );
+ String tqx = response.getRequest().getResourceRef().getQueryAsForm()
+ .getFirstValue( "tqx" );
String reqId = null;
if( tqx != null )
{
@@ -92,77 +104,71 @@ public class TableResponseWriter extends AbstractResponseWriter
}
}
- json.object().key( "version" ).value( "0.6" );
+ builder.add( "version", "0.6" );
if( reqId != null )
{
- json.key( "reqId" ).value( reqId );
+ builder.add( "reqId", reqId );
}
- json.key( "status" ).value( "ok" );
- json.key( "table" ).object();
+ builder.add( "status", "ok" );
+
+ JsonObjectBuilder tableBuilder = Json.createObjectBuilder();
+ JsonArrayBuilder colsBuilder = Json.createArrayBuilder();
List<Column> columnList = tableValue.cols().get();
- json.key( "cols" ).array();
for( Column columnValue : columnList )
{
- json.object().
- key( "id" ).value( columnValue.id().get() ).
- key( "label" ).value( columnValue.label().get() ).
- key( "type" ).value( columnValue.columnType().get() ).
- endObject();
+ colsBuilder.add( Json.createObjectBuilder()
+ .add( "id", columnValue.id().get() )
+ .add( "label", columnValue.label().get() )
+ .add( "type", columnValue.columnType().get() )
+ .build() );
}
- json.endArray();
+ tableBuilder.add( "cols", colsBuilder.build() );
- json.key( "rows" ).array();
+ JsonArrayBuilder rowsBuilder = Json.createArrayBuilder();
for( Row rowValue : tableValue.rows().get() )
{
- json.object();
- json.key( "c" ).array();
+ JsonArrayBuilder cellsBuilder = Json.createArrayBuilder();
int idx = 0;
for( Cell cellValue : rowValue.c().get() )
{
- json.object();
Object value = cellValue.v().get();
- if( columnList.get( idx )
- .columnType()
- .get()
- .equals( Table.DATETIME ) && value != null )
+ if( columnList.get( idx ).columnType().get().equals( Table.DATETIME )
+ && value != null )
{
value = value.toString();
}
- else if( columnList.get( idx )
- .columnType()
- .get()
- .equals( Table.DATE ) && value != null )
+ else if( columnList.get( idx ).columnType().get().equals( Table.DATE )
+ && value != null )
{
value = value.toString();
}
- else if( columnList.get( idx )
- .columnType()
- .get()
- .equals( Table.TIME_OF_DAY ) && value != null )
+ else if( columnList.get( idx ).columnType().get().equals( Table.TIME_OF_DAY )
+ && value != null )
{
value = value.toString();
}
+ JsonObjectBuilder cellBuilder = Json.createObjectBuilder();
if( value != null )
{
- json.key( "v" ).value( value );
+ cellBuilder.add( "v", jsonSerializer.toJson( value ) );
}
if( cellValue.f().get() != null )
{
- json.key( "f" ).value( cellValue.f().get() );
+ cellBuilder.add( "f", cellValue.f().get() );
}
- json.endObject();
-
+ cellsBuilder.add( cellBuilder.build() );
idx++;
}
- json.endArray();
- json.endObject();
+ JsonObjectBuilder rowBuilder = Json.createObjectBuilder();
+ rowBuilder.add( "c", cellsBuilder.build() );
+ rowsBuilder.add( rowBuilder.build() );
}
- json.endArray();
- json.endObject();
- json.endObject();
+ tableBuilder.add( "rows", rowsBuilder.build() );
+ builder.add( "table", tableBuilder.build() );
+ writer.write( builder.build().toString() );
}
- catch( JSONException e )
+ catch( JsonException e )
{
throw new IOException( e );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/ValueCompositeResponseWriter.java
----------------------------------------------------------------------
diff --git a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/ValueCompositeResponseWriter.java b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/ValueCompositeResponseWriter.java
index 9978b29..a50e9ca 100644
--- a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/ValueCompositeResponseWriter.java
+++ b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/ValueCompositeResponseWriter.java
@@ -32,9 +32,9 @@ import java.util.List;
import java.util.Map;
import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.service.qualifier.Tagged;
+import org.apache.polygene.api.serialization.Serialization;
+import org.apache.polygene.api.serialization.Serializer;
import org.apache.polygene.api.value.ValueComposite;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.api.value.ValueSerializer;
import org.restlet.Response;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
@@ -53,8 +53,8 @@ public class ValueCompositeResponseWriter extends AbstractResponseWriter
private Configuration cfg;
@Service
- @Tagged( ValueSerialization.Formats.JSON )
- private ValueSerializer valueSerializer;
+ @Tagged( Serialization.Formats.JSON )
+ private Serializer serializer;
@Override
public boolean writeResponse( final Object result, final Response response )
@@ -65,7 +65,7 @@ public class ValueCompositeResponseWriter extends AbstractResponseWriter
MediaType type = getVariant( response.getRequest(), ENGLISH, supportedMediaTypes ).getMediaType();
if( MediaType.APPLICATION_JSON.equals( type ) )
{
- StringRepresentation representation = new StringRepresentation( valueSerializer.serialize( result ),
+ StringRepresentation representation = new StringRepresentation( serializer.serialize( result ),
MediaType.APPLICATION_JSON );
response.setEntity( representation );
return true;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/ValueDescriptorResponseWriter.java
----------------------------------------------------------------------
diff --git a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/ValueDescriptorResponseWriter.java b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/ValueDescriptorResponseWriter.java
index 7ff8a84..c438a5b 100644
--- a/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/ValueDescriptorResponseWriter.java
+++ b/libraries/rest-server/src/main/java/org/apache/polygene/library/rest/server/restlet/responsewriter/ValueDescriptorResponseWriter.java
@@ -28,12 +28,14 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import javax.json.Json;
+import javax.json.JsonException;
+import javax.json.JsonObjectBuilder;
+import javax.json.JsonValue;
import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.injection.scope.Structure;
import org.apache.polygene.api.structure.ModuleDescriptor;
import org.apache.polygene.api.value.ValueDescriptor;
-import org.json.JSONException;
-import org.json.JSONObject;
import org.restlet.Response;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
@@ -41,12 +43,15 @@ import org.restlet.representation.StringRepresentation;
import org.restlet.representation.WriterRepresentation;
import org.restlet.resource.ResourceException;
+import static org.restlet.data.MediaType.APPLICATION_JSON;
+import static org.restlet.data.MediaType.TEXT_HTML;
+
/**
* JAVADOC
*/
public class ValueDescriptorResponseWriter extends AbstractResponseWriter
{
- private static final List<MediaType> supportedMediaTypes = Arrays.asList( MediaType.TEXT_HTML, MediaType.APPLICATION_JSON );
+ private static final List<MediaType> supportedMediaTypes = Arrays.asList( TEXT_HTML, APPLICATION_JSON );
@Structure
private ModuleDescriptor module;
@@ -61,36 +66,38 @@ public class ValueDescriptorResponseWriter extends AbstractResponseWriter
if( result instanceof ValueDescriptor )
{
MediaType type = getVariant( response.getRequest(), ENGLISH, supportedMediaTypes ).getMediaType();
- if( MediaType.APPLICATION_JSON.equals( type ) )
+ if( APPLICATION_JSON.equals( type ) )
{
- JSONObject json = new JSONObject();
ValueDescriptor vd = (ValueDescriptor) result;
- vd.state().properties().forEach( propertyDescriptor -> {
- try
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ vd.state().properties().forEach(
+ property ->
{
- Object o = propertyDescriptor.resolveInitialValue(module);
- if( o == null )
+ try
{
- json.put( propertyDescriptor.qualifiedName().name(), JSONObject.NULL );
+ Object o = property.resolveInitialValue( module );
+ if( o == null )
+ {
+ builder.add( property.qualifiedName().name(), JsonValue.NULL );
+ }
+ else
+ {
+ builder.add( property.qualifiedName().name(), o.toString() );
+ }
}
- else
+ catch( JsonException ex )
{
- json.put( propertyDescriptor.qualifiedName().name(), o.toString() );
+ throw new RestResponseException( "Unable to serialize " + vd, ex );
}
- }
- catch( JSONException e )
- {
- throw new RestResponseException( "Unable to serialize " + vd, e);
- }
- } );
- StringRepresentation representation
- = new StringRepresentation( json.toString(), MediaType.APPLICATION_JSON );
+ } );
+ StringRepresentation representation = new StringRepresentation( builder.build().toString(),
+ APPLICATION_JSON );
response.setEntity( representation );
return true;
}
- else if( MediaType.TEXT_HTML.equals( type ) )
+ else if( TEXT_HTML.equals( type ) )
{
- Representation rep = new WriterRepresentation( MediaType.TEXT_HTML )
+ Representation rep = new WriterRepresentation( TEXT_HTML )
{
@Override
public void write( Writer writer )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest/build.gradle
----------------------------------------------------------------------
diff --git a/libraries/rest/build.gradle b/libraries/rest/build.gradle
index 8383383..6ca051d 100644
--- a/libraries/rest/build.gradle
+++ b/libraries/rest/build.gradle
@@ -27,8 +27,9 @@ jar { manifest { name = "Apache Polygene\u2122 Library - REST" } }
dependencies {
compileOnly libraries.servlet_api
+ api libraries.restlet
+
implementation polygene.extension( 'indexing-rdf' )
- implementation libraries.restlet
implementation libraries.sparql
implementation libraries.velocity
@@ -36,7 +37,6 @@ dependencies {
testImplementation polygene.core.testsupport
testImplementation polygene.library( 'http' )
- testImplementation polygene.extension( 'valueserialization-orgjson' )
testImplementation libraries.http_client
testRuntimeOnly libraries.logback
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest/src/main/java/org/apache/polygene/library/rest/admin/EntitiesResource.java
----------------------------------------------------------------------
diff --git a/libraries/rest/src/main/java/org/apache/polygene/library/rest/admin/EntitiesResource.java b/libraries/rest/src/main/java/org/apache/polygene/library/rest/admin/EntitiesResource.java
index b0eb71e..0b07b3e 100644
--- a/libraries/rest/src/main/java/org/apache/polygene/library/rest/admin/EntitiesResource.java
+++ b/libraries/rest/src/main/java/org/apache/polygene/library/rest/admin/EntitiesResource.java
@@ -22,6 +22,7 @@ package org.apache.polygene.library.rest.admin;
import java.io.IOException;
import java.io.OutputStream;
+import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Arrays;
@@ -31,7 +32,7 @@ import java.util.stream.Stream;
import org.apache.polygene.api.entity.EntityComposite;
import org.apache.polygene.api.entity.EntityReference;
import org.apache.polygene.api.injection.scope.Service;
-import org.apache.polygene.api.value.ValueSerialization;
+import org.apache.polygene.api.serialization.Serialization;
import org.apache.polygene.spi.query.EntityFinder;
import org.apache.polygene.spi.query.EntityFinderException;
import org.restlet.data.CharacterSet;
@@ -64,7 +65,7 @@ public class EntitiesResource
@Service
private EntityFinder entityFinder;
@Service
- private ValueSerialization valueSerialization;
+ private Serialization stateSerialization;
public EntitiesResource()
{
@@ -117,7 +118,7 @@ public class EntitiesResource
public void write( OutputStream outputStream )
throws IOException
{
- valueSerialization.serialize( query, outputStream );
+ stateSerialization.serialize( new OutputStreamWriter( outputStream ), query );
}
};
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest/src/main/java/org/apache/polygene/library/rest/admin/EntityResource.java
----------------------------------------------------------------------
diff --git a/libraries/rest/src/main/java/org/apache/polygene/library/rest/admin/EntityResource.java b/libraries/rest/src/main/java/org/apache/polygene/library/rest/admin/EntityResource.java
index cbdb34d..9eb3c17 100644
--- a/libraries/rest/src/main/java/org/apache/polygene/library/rest/admin/EntityResource.java
+++ b/libraries/rest/src/main/java/org/apache/polygene/library/rest/admin/EntityResource.java
@@ -38,12 +38,11 @@ import org.apache.polygene.api.identity.StringIdentity;
import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.injection.scope.Structure;
import org.apache.polygene.api.injection.scope.Uses;
+import org.apache.polygene.api.serialization.SerializationException;
import org.apache.polygene.api.structure.ModuleDescriptor;
import org.apache.polygene.api.time.SystemTime;
import org.apache.polygene.api.usecase.Usecase;
import org.apache.polygene.api.usecase.UsecaseBuilder;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.api.value.ValueSerializationException;
import org.apache.polygene.library.rdf.entity.EntityStateSerializer;
import org.apache.polygene.library.rdf.serializer.RdfXmlSerializer;
import org.apache.polygene.spi.entity.EntityState;
@@ -54,6 +53,7 @@ import org.apache.polygene.spi.entitystore.EntityNotFoundException;
import org.apache.polygene.spi.entitystore.EntityStore;
import org.apache.polygene.spi.entitystore.EntityStoreUnitOfWork;
import org.apache.polygene.spi.entitystore.helpers.JSONEntityState;
+import org.apache.polygene.spi.serialization.JsonSerialization;
import org.openrdf.model.Statement;
import org.openrdf.rio.RDFHandlerException;
import org.restlet.data.CharacterSet;
@@ -79,7 +79,7 @@ public class EntityResource
private EntityStore entityStore;
@Service
- private ValueSerialization valueSerialization;
+ private JsonSerialization serialization;
@Structure
private ModuleDescriptor module;
@@ -231,7 +231,7 @@ public class EntityResource
+ "type=\"text\" "
+ ( persistentProperty.isImmutable() ? "readonly=\"true\" " : "" )
+ "name=\"" + persistentProperty.qualifiedName() + "\" "
- + "value=\"" + ( value == null ? "" : valueSerialization.serialize( value ) )
+ + "value=\"" + ( value == null ? "" : serialization.serialize( value ) )
+ "\"/></td></tr>" );
} );
out.println( "</table></fieldset>\n" );
@@ -308,6 +308,7 @@ public class EntityResource
private Representation representJson( EntityState entityState )
{
+ // TODO This guy needs to represent an Entity as JSON
if( entityState instanceof JSONEntityState )
{
JSONEntityState jsonState = (JSONEntityState) entityState;
@@ -377,7 +378,7 @@ public class EntityResource
{
entity.setPropertyValue(
persistentProperty.qualifiedName(),
- valueSerialization.deserialize( module, persistentProperty.valueType(), formValue ) );
+ serialization.deserialize( module, persistentProperty.valueType(), formValue ) );
}
}
} );
@@ -503,7 +504,7 @@ public class EntityResource
}
} );
}
- catch( ValueSerializationException | IllegalArgumentException e )
+ catch( SerializationException | IllegalArgumentException e )
{
throw new ResourceException( Status.SERVER_ERROR_INTERNAL, e );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/rest/src/test/java/org/apache/polygene/library/rest/admin/RDFAssembler.java
----------------------------------------------------------------------
diff --git a/libraries/rest/src/test/java/org/apache/polygene/library/rest/admin/RDFAssembler.java b/libraries/rest/src/test/java/org/apache/polygene/library/rest/admin/RDFAssembler.java
index f028d77..654f0d1 100644
--- a/libraries/rest/src/test/java/org/apache/polygene/library/rest/admin/RDFAssembler.java
+++ b/libraries/rest/src/test/java/org/apache/polygene/library/rest/admin/RDFAssembler.java
@@ -26,7 +26,6 @@ import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.library.rdf.entity.EntityStateSerializer;
import org.apache.polygene.library.rdf.entity.EntityTypeSerializer;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
/**
* JAVADOC
@@ -37,7 +36,6 @@ class RDFAssembler
public void assemble( ModuleAssembly module )
throws AssemblyException
{
- new OrgJsonValueSerializationAssembler().assemble( module );
module.objects( EntityStateSerializer.class ).visibleIn( Visibility.application );
module.objects( EntityTypeSerializer.class ).visibleIn( Visibility.application );
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/restlet/build.gradle
----------------------------------------------------------------------
diff --git a/libraries/restlet/build.gradle b/libraries/restlet/build.gradle
index ed8ca1a..95ab44b 100644
--- a/libraries/restlet/build.gradle
+++ b/libraries/restlet/build.gradle
@@ -30,9 +30,8 @@ dependencies {
api polygene.core.bootstrap
- implementation polygene.extension( 'valueserialization-jackson' )
- implementation polygene.extension( 'indexing-rdf' )
implementation polygene.extension( 'entitystore-file' )
+ implementation polygene.extension( 'indexing-rdf' )
implementation libraries.restlet
runtimeOnly polygene.core.runtime
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/RestletCrudConnectivityAssembler.java
----------------------------------------------------------------------
diff --git a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/RestletCrudConnectivityAssembler.java b/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/RestletCrudConnectivityAssembler.java
index 21a2e0c..815691a 100644
--- a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/RestletCrudConnectivityAssembler.java
+++ b/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/RestletCrudConnectivityAssembler.java
@@ -38,7 +38,6 @@ import org.apache.polygene.library.restlet.resource.EntryPointResource;
import org.apache.polygene.library.restlet.resource.ResourceBuilder;
import org.apache.polygene.library.restlet.serialization.FormRepresentation;
import org.apache.polygene.library.restlet.serialization.JsonRepresentation;
-import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
public class RestletCrudConnectivityAssembler
implements Assembler
@@ -65,6 +64,5 @@ public class RestletCrudConnectivityAssembler
PolygeneEntityRestlet.class )
.visibleIn( Visibility.layer );
module.services( ResourceBuilder.class ).visibleIn( Visibility.layer );
- new JacksonValueSerializationAssembler().assemble( module );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/configuration/ConfigurationModule.java
----------------------------------------------------------------------
diff --git a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/configuration/ConfigurationModule.java b/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/configuration/ConfigurationModule.java
index e564c0d..1050e8a 100644
--- a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/configuration/ConfigurationModule.java
+++ b/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/configuration/ConfigurationModule.java
@@ -26,7 +26,6 @@ import org.apache.polygene.bootstrap.LayerAssembly;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.bootstrap.layered.ModuleAssembler;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
-import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
public class ConfigurationModule
implements ModuleAssembler
@@ -37,7 +36,6 @@ public class ConfigurationModule
throws AssemblyException
{
module.services( MemoryEntityStoreService.class ).visibleIn( Visibility.layer );
- new JacksonValueSerializationAssembler().visibleIn( Visibility.layer ).assemble( module );
return module;
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/infrastructue/SerializationModule.java
----------------------------------------------------------------------
diff --git a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/infrastructue/SerializationModule.java b/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/infrastructue/SerializationModule.java
index 77d1166..275cb27 100644
--- a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/infrastructue/SerializationModule.java
+++ b/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/assembly/infrastructue/SerializationModule.java
@@ -20,12 +20,10 @@
package org.apache.polygene.library.restlet.assembly.infrastructue;
-import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.LayerAssembly;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.bootstrap.layered.ModuleAssembler;
-import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
public class SerializationModule
implements ModuleAssembler
@@ -36,9 +34,6 @@ public class SerializationModule
public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
throws AssemblyException
{
- new JacksonValueSerializationAssembler()
- .visibleIn( Visibility.layer )
- .assemble( module );
return module;
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/serialization/JsonRepresentation.java
----------------------------------------------------------------------
diff --git a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/serialization/JsonRepresentation.java b/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/serialization/JsonRepresentation.java
index 74acdf8..ea0929b 100644
--- a/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/serialization/JsonRepresentation.java
+++ b/libraries/restlet/src/main/java/org/apache/polygene/library/restlet/serialization/JsonRepresentation.java
@@ -21,14 +21,15 @@
package org.apache.polygene.library.restlet.serialization;
import java.io.IOException;
+import java.io.InputStreamReader;
import java.io.OutputStream;
+import java.io.OutputStreamWriter;
import org.apache.polygene.api.common.Optional;
import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.injection.scope.Structure;
import org.apache.polygene.api.injection.scope.Uses;
+import org.apache.polygene.api.serialization.Serialization;
import org.apache.polygene.api.structure.ModuleDescriptor;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.api.value.ValueSerializer;
import org.apache.polygene.spi.PolygeneSPI;
import org.restlet.data.MediaType;
import org.restlet.representation.OutputRepresentation;
@@ -42,13 +43,11 @@ import org.restlet.representation.Representation;
public class JsonRepresentation<T> extends OutputRepresentation
{
- private static final ValueSerializer.Options OPTIONS_NO_TYPE = new ValueSerializer.Options().withoutTypeInfo().withMapEntriesAsObjects();
-
@Structure
private PolygeneSPI spi;
@Service
- private ValueSerialization serializer;
+ private Serialization stateSerialization;
@Structure
private ModuleDescriptor module;
@@ -98,7 +97,8 @@ public class JsonRepresentation<T> extends OutputRepresentation
}
else if( this.representation != null )
{
- result = serializer.deserialize( module, objectClass, this.representation.getStream() );
+ result = stateSerialization.deserialize( module, objectClass,
+ new InputStreamReader( this.representation.getStream() ) );
}
return result;
}
@@ -123,7 +123,8 @@ public class JsonRepresentation<T> extends OutputRepresentation
}
else if( object != null )
{
- serializer.serialize( OPTIONS_NO_TYPE, object, outputStream );
+ // TODO was WITHOUT TYPE INFO
+ stateSerialization.serialize( new OutputStreamWriter( outputStream ), object );
outputStream.write( '\n' );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/sql-liquibase/build.gradle
----------------------------------------------------------------------
diff --git a/libraries/sql-liquibase/build.gradle b/libraries/sql-liquibase/build.gradle
index ffedb52..4d94e30 100644
--- a/libraries/sql-liquibase/build.gradle
+++ b/libraries/sql-liquibase/build.gradle
@@ -34,6 +34,7 @@ dependencies {
testImplementation polygene.core.testsupport
testImplementation polygene.library( 'sql-dbcp' )
+ testImplementation libraries.jooq
testRuntimeOnly libraries.derby
testRuntimeOnly libraries.logback
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/sql-liquibase/src/test/java/org/apache/polygene/library/sql/liquibase/LiquibaseServiceTest.java
----------------------------------------------------------------------
diff --git a/libraries/sql-liquibase/src/test/java/org/apache/polygene/library/sql/liquibase/LiquibaseServiceTest.java b/libraries/sql-liquibase/src/test/java/org/apache/polygene/library/sql/liquibase/LiquibaseServiceTest.java
index 807990d..108a187 100644
--- a/libraries/sql-liquibase/src/test/java/org/apache/polygene/library/sql/liquibase/LiquibaseServiceTest.java
+++ b/libraries/sql-liquibase/src/test/java/org/apache/polygene/library/sql/liquibase/LiquibaseServiceTest.java
@@ -20,14 +20,10 @@
package org.apache.polygene.library.sql.liquibase;
import java.io.IOException;
-import java.sql.ResultSet;
import java.sql.SQLException;
-import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import javax.sql.DataSource;
-import org.apache.polygene.api.activation.ActivationEvent;
-import org.apache.polygene.api.activation.ActivationEventListener;
import org.apache.polygene.api.activation.ActivationException;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.api.property.Property;
@@ -39,13 +35,22 @@ import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.bootstrap.SingletonAssembler;
import org.apache.polygene.library.sql.assembly.DataSourceAssembler;
-import org.apache.polygene.library.sql.common.Databases;
-import org.apache.polygene.library.sql.common.SQLUtil;
import org.apache.polygene.library.sql.dbcp.DBCPDataSourceServiceAssembler;
import org.apache.polygene.test.EntityTestAssembler;
+import org.jooq.DSLContext;
+import org.jooq.Field;
+import org.jooq.InsertValuesStep2;
+import org.jooq.Record;
+import org.jooq.SQLDialect;
+import org.jooq.Table;
+import org.jooq.impl.DSL;
import org.junit.Test;
+import static java.util.stream.Collectors.toList;
import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.jooq.impl.DSL.field;
+import static org.jooq.impl.DSL.table;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@@ -68,23 +73,23 @@ public class LiquibaseServiceTest
// Create in-memory store for configurations
new EntityTestAssembler().assemble( configModule );
- new DBCPDataSourceServiceAssembler().
- identifiedBy( "datasource-service" ).
- withConfig( configModule, Visibility.layer ).
- assemble( module );
- new DataSourceAssembler().
- withDataSourceServiceIdentity( "datasource-service" ).
- identifiedBy( "testds-liquibase" ).
- withCircuitBreaker().
- assemble( module );
+ new DBCPDataSourceServiceAssembler()
+ .identifiedBy( "datasource-service" )
+ .withConfig( configModule, Visibility.layer )
+ .assemble( module );
+ new DataSourceAssembler()
+ .withDataSourceServiceIdentity( "datasource-service" )
+ .identifiedBy( "testds-liquibase" )
+ .withCircuitBreaker()
+ .assemble( module );
module.values( SomeValue.class );
// Set up Liquibase service that will create the tables
// START SNIPPET: assembly
- new LiquibaseAssembler().
- withConfig( configModule, Visibility.layer ).
- assemble( module );
+ new LiquibaseAssembler()
+ .withConfig( configModule, Visibility.layer )
+ .assemble( module );
// END SNIPPET: assembly
module.forMixin( LiquibaseConfiguration.class ).declareDefaults().enabled().set( true );
module.forMixin( LiquibaseConfiguration.class ).declareDefaults().changeLog().set( "changelog.xml" );
@@ -93,78 +98,48 @@ public class LiquibaseServiceTest
@Override
public void beforeActivation( Application application )
{
- application.registerActivationEventListener( new ActivationEventListener()
- {
-
- @Override
- public void onEvent( ActivationEvent event )
- {
- System.out.println( event );
- }
-
- } );
+ application.registerActivationEventListener( System.out::println );
}
-
};
Module module = assembler.module();
- // START SNIPPET: io
// Look up the DataSource
DataSource ds = module.findService( DataSource.class ).get();
- // Instanciate Databases helper
- Databases database = new Databases( ds );
+ // Prepare jOOQ and the schema model
+ DSLContext jooq = DSL.using( ds, SQLDialect.DERBY );
+ Table<Record> testTable = table( "TEST" );
+ Field<String> idColumn = field( "ID", String.class );
+ Field<String> fooColumn = field( "FOO", String.class );
// Assert that insertion works
- assertTrue( database.update( "insert into test values ('someid', 'bar')" ) == 1 );
- // END SNIPPET: io
-
- database.query( "select * from test", new Databases.ResultSetVisitor()
- {
- @Override
- public boolean visit( ResultSet visited )
- throws SQLException
- {
- assertThat( visited.getString( "id" ), equalTo( "someid" ) );
- assertThat( visited.getString( "foo" ), equalTo( "bar" ) );
+ InsertValuesStep2 insert = jooq.insertInto( testTable )
+ .columns( idColumn, fooColumn )
+ .values( "someid", "bar" );
+ assertTrue( insert.execute() == 1 );
- return true;
- }
- } );
+ List<Record> records = jooq.selectFrom( testTable ).stream().collect( toList() );
+ assertThat( records.size(), is( 1 ) );
+ assertThat( records.get( 0 ).get( idColumn ), equalTo( "someid" ) );
+ assertThat( records.get( 0 ).get( fooColumn ), equalTo( "bar" ) );
- Function<ResultSet, SomeValue> toValue = new Function<ResultSet, SomeValue>()
+ Function<Record, SomeValue> toValue = record ->
{
- @Override
- public SomeValue apply( ResultSet resultSet )
- {
- ValueBuilder<SomeValue> builder = assembler.module().newValueBuilder( SomeValue.class );
- try
- {
- builder.prototype().id().set( resultSet.getString( "id" ) );
- builder.prototype().foo().set( resultSet.getString( "foo" ) );
- }
- catch( SQLException e )
- {
- throw new IllegalArgumentException( "Could not convert to SomeValue",
- SQLUtil.withAllSQLExceptions( e ) );
- }
-
- return builder.newInstance();
- }
+ ValueBuilder<SomeValue> builder = assembler.module().newValueBuilder( SomeValue.class );
+ builder.prototype().id().set( record.get( idColumn ) );
+ builder.prototype().foo().set( record.get( fooColumn ) );
+ return builder.newInstance();
};
- List<SomeValue> rows = new ArrayList<SomeValue>();
- database.query( "select * from test", new Databases.ResultSetVisitor() {
- @Override
- public boolean visit( final ResultSet resultSet ) throws SQLException
- {
- rows.add( toValue.apply( resultSet ) );
- return true;
- }
- } );
+ List<SomeValue> values = jooq.selectFrom( testTable ).stream()
+ .map( toValue )
+ .peek( System.out::println )
+ .collect( toList() );
- rows.forEach( System.out::println );
+ assertThat( values.size(), is( 1 ) );
+ assertThat( values.get( 0 ).id().get(), equalTo( "someid" ) );
+ assertThat( values.get( 0 ).foo().get(), equalTo( "bar" ) );
}
interface SomeValue
@@ -174,5 +149,4 @@ public class LiquibaseServiceTest
Property<String> foo();
}
-
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/sql/src/main/java/org/apache/polygene/library/sql/common/Databases.java
----------------------------------------------------------------------
diff --git a/libraries/sql/src/main/java/org/apache/polygene/library/sql/common/Databases.java b/libraries/sql/src/main/java/org/apache/polygene/library/sql/common/Databases.java
index ebed162..7710444 100644
--- a/libraries/sql/src/main/java/org/apache/polygene/library/sql/common/Databases.java
+++ b/libraries/sql/src/main/java/org/apache/polygene/library/sql/common/Databases.java
@@ -29,6 +29,7 @@ import org.apache.polygene.api.util.Visitor;
/**
* Utility methods for performing SQL calls wrapping a given DataSource.
*/
+// TODO Remove me!
public class Databases
{
DataSource source;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/libraries/uowfile/src/main/java/org/apache/polygene/library/uowfile/internal/ConcurrentUoWFileModificationException.java
----------------------------------------------------------------------
diff --git a/libraries/uowfile/src/main/java/org/apache/polygene/library/uowfile/internal/ConcurrentUoWFileModificationException.java b/libraries/uowfile/src/main/java/org/apache/polygene/library/uowfile/internal/ConcurrentUoWFileModificationException.java
index b604702..b27c067 100644
--- a/libraries/uowfile/src/main/java/org/apache/polygene/library/uowfile/internal/ConcurrentUoWFileModificationException.java
+++ b/libraries/uowfile/src/main/java/org/apache/polygene/library/uowfile/internal/ConcurrentUoWFileModificationException.java
@@ -32,7 +32,7 @@ public class ConcurrentUoWFileModificationException
ConcurrentUoWFileModificationException( Iterable<UoWFile> concurrentlyModifiedFiles, Usecase usecase )
{
- super( Collections.<EntityComposite,HasTypes>emptyMap(), usecase );
+ super( Collections.emptyMap(), usecase );
this.concurrentlyModifiedFiles = concurrentlyModifiedFiles;
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/manual/src/docs/userguide/extensions.txt
----------------------------------------------------------------------
diff --git a/manual/src/docs/userguide/extensions.txt b/manual/src/docs/userguide/extensions.txt
index 524fec2..42f216e 100644
--- a/manual/src/docs/userguide/extensions.txt
+++ b/manual/src/docs/userguide/extensions.txt
@@ -28,7 +28,7 @@ We try to keep the Polygene\u2122 Core Runtime as lean as possible, and a lot of th
Extension SPI, which defines clear ways to extend the platform. There are currently the following Extensions types,
each with possibly more than one implementation;
- * Value Serialization
+ * Serialization
* Entity Stores
* Index / Query Engines
* Entity Caches
@@ -45,23 +45,15 @@ for our users.
:leveloffset: 2
-include::../../../../extensions/valueserialization-orgjson/src/docs/vs-orgjson.txt[]
+include::../../../../extensions/serialization-javaxjson/src/docs/serialization-javaxjson.txt[]
:leveloffset: 2
-include::../../../../extensions/valueserialization-jackson/src/docs/vs-jackson.txt[]
+include::../../../../extensions/serialization-javaxxml/src/docs/serialization-javaxxml.txt[]
:leveloffset: 2
-include::../../../../extensions/valueserialization-stax/src/docs/vs-stax.txt[]
-
-:leveloffset: 2
-
-include::../../../../extensions/cache-ehcache/src/docs/cache-ehcache.txt[]
-
-:leveloffset: 2
-
-include::../../../../extensions/cache-memcache/src/docs/cache-memcache.txt[]
+include::../../../../extensions/serialization-msgpack/src/docs/serialization-msgpack.txt[]
:leveloffset: 2
@@ -113,6 +105,14 @@ include::../../../../extensions/entitystore-sql/src/docs/es-sql.txt[]
:leveloffset: 2
+include::../../../../extensions/cache-ehcache/src/docs/cache-ehcache.txt[]
+
+:leveloffset: 2
+
+include::../../../../extensions/cache-memcache/src/docs/cache-memcache.txt[]
+
+:leveloffset: 2
+
include::../../../../extensions/indexing-elasticsearch/src/docs/index-elasticsearch.txt[]
:leveloffset: 2
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/samples/forum/build.gradle
----------------------------------------------------------------------
diff --git a/samples/forum/build.gradle b/samples/forum/build.gradle
index be78ca2..f11dcfe 100644
--- a/samples/forum/build.gradle
+++ b/samples/forum/build.gradle
@@ -29,7 +29,6 @@ dependencies {
implementation polygene.core.bootstrap
implementation polygene.library( 'rest-server' )
implementation polygene.library( 'fileconfig' )
- implementation polygene.extension( 'valueserialization-orgjson' )
implementation polygene.extension( 'entitystore-memory' )
implementation polygene.extension( 'entitystore-file' )
implementation polygene.extension( 'indexing-rdf' )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/samples/forum/src/main/java/org/apache/polygene/sample/forum/assembler/ForumAssembler.java
----------------------------------------------------------------------
diff --git a/samples/forum/src/main/java/org/apache/polygene/sample/forum/assembler/ForumAssembler.java b/samples/forum/src/main/java/org/apache/polygene/sample/forum/assembler/ForumAssembler.java
index e3435b1..5f3b0cc 100644
--- a/samples/forum/src/main/java/org/apache/polygene/sample/forum/assembler/ForumAssembler.java
+++ b/samples/forum/src/main/java/org/apache/polygene/sample/forum/assembler/ForumAssembler.java
@@ -50,7 +50,6 @@ import org.apache.polygene.sample.forum.domainevent.ParameterValue;
import org.apache.polygene.sample.forum.rest.ForumRestlet;
import org.apache.polygene.sample.forum.rest.resource.RootResource;
import org.apache.polygene.sample.forum.service.BootstrapData;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
import org.restlet.service.MetadataService;
import static java.util.stream.Collectors.toList;
@@ -75,18 +74,12 @@ public class ForumAssembler
LayerAssembly configuration = assembly.layer( "Configuration" );
{
configModule = configuration.module( "Configuration" );
- new OrgJsonValueSerializationAssembler().assemble( configModule );
new MemoryEntityStoreAssembler().assemble( configModule );
new FileConfigurationAssembler().visibleIn( Visibility.application ).assemble( configModule );
}
LayerAssembly infrastructure = assembly.layer( "Infrastructure" ).uses( configuration );
{
- ModuleAssembly serialization = infrastructure.module( "Serialization" );
- new OrgJsonValueSerializationAssembler().
- visibleIn( Visibility.application ).
- assemble( serialization );
-
ModuleAssembly entityStore = infrastructure.module( "EntityStore" );
new FileEntityStoreAssembler()
.visibleIn( Visibility.application )
@@ -133,8 +126,8 @@ public class ForumAssembler
contexts.services( EventsService.class );
context.module( "Domain events" )
- .values( DomainEventValue.class, ParameterValue.class )
- .visibleIn( Visibility.application );
+ .values( DomainEventValue.class, ParameterValue.class )
+ .visibleIn( Visibility.application );
}
LayerAssembly services = assembly.layer( "Service" ).uses( data );
@@ -154,12 +147,12 @@ public class ForumAssembler
{
new RestServerAssembler().assemble( transformation );
transformation.objects( RequestReaderDelegator.class, ResponseWriterDelegator.class )
- .visibleIn( Visibility.layer );
- new OrgJsonValueSerializationAssembler().assemble( transformation );
+ .visibleIn( Visibility.layer );
}
ModuleAssembly resources = rest.module( "Resources" );
- List<? extends Class<?>> resourceClasses = ClassScanner.findClasses( RootResource.class ).collect( toList() );
+ List<? extends Class<?>> resourceClasses = ClassScanner.findClasses( RootResource.class )
+ .collect( toList() );
for( Class<?> resourceClass : resourceClasses )
{
resources.objects( resourceClass ).visibleIn( Visibility.layer );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/samples/rental/build.gradle
----------------------------------------------------------------------
diff --git a/samples/rental/build.gradle b/samples/rental/build.gradle
index 1f083e4..31c502c 100644
--- a/samples/rental/build.gradle
+++ b/samples/rental/build.gradle
@@ -33,7 +33,6 @@ jar { manifest { name = "Apache Polygene\u2122 Sample - Car Rental" } }
dependencies {
implementation polygene.core.bootstrap
- implementation polygene.extension( 'valueserialization-orgjson' )
providedCompile libraries.servlet_api
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/samples/rental/src/main/java/org/apache/polygene/sample/rental/web/assembly/StorageModule.java
----------------------------------------------------------------------
diff --git a/samples/rental/src/main/java/org/apache/polygene/sample/rental/web/assembly/StorageModule.java b/samples/rental/src/main/java/org/apache/polygene/sample/rental/web/assembly/StorageModule.java
index 7fd88ab..a7ca995 100644
--- a/samples/rental/src/main/java/org/apache/polygene/sample/rental/web/assembly/StorageModule.java
+++ b/samples/rental/src/main/java/org/apache/polygene/sample/rental/web/assembly/StorageModule.java
@@ -24,19 +24,14 @@ import org.apache.polygene.bootstrap.Assembler;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
public class StorageModule
implements Assembler
{
-
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.services( MemoryEntityStoreService.class ).visibleIn( Visibility.application );
- new OrgJsonValueSerializationAssembler().
- visibleIn( Visibility.application ).
- assemble( module );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/samples/sql-support/src/main/java/org/apache/polygene/sample/sqlsupport/AppAssembler.java
----------------------------------------------------------------------
diff --git a/samples/sql-support/src/main/java/org/apache/polygene/sample/sqlsupport/AppAssembler.java b/samples/sql-support/src/main/java/org/apache/polygene/sample/sqlsupport/AppAssembler.java
index c6c7624..9c9fee6 100644
--- a/samples/sql-support/src/main/java/org/apache/polygene/sample/sqlsupport/AppAssembler.java
+++ b/samples/sql-support/src/main/java/org/apache/polygene/sample/sqlsupport/AppAssembler.java
@@ -20,7 +20,6 @@
package org.apache.polygene.sample.sqlsupport;
import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.api.value.ValueSerialization;
import org.apache.polygene.bootstrap.ApplicationAssembler;
import org.apache.polygene.bootstrap.ApplicationAssembly;
import org.apache.polygene.bootstrap.ApplicationAssemblyFactory;
@@ -33,7 +32,6 @@ import org.apache.polygene.index.sql.assembly.PostgreSQLIndexQueryAssembler;
import org.apache.polygene.library.sql.assembly.DataSourceAssembler;
import org.apache.polygene.library.sql.datasource.DataSources;
import org.apache.polygene.library.sql.dbcp.DBCPDataSourceServiceAssembler;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
/**
* Assemble the Application.
@@ -56,8 +54,6 @@ public class AppAssembler
LayerAssembly configLayer = appAss.layer( "config" );
ModuleAssembly configModule = configLayer.module( "config" );
{
- configModule.services( OrgJsonValueSerializationService.class ).
- taggedWith( ValueSerialization.Formats.JSON );
configModule.services( MemoryEntityStoreService.class ).
visibleIn( Visibility.module );
// Use a PreferenceEntityStore instead if you want the configuration to be persistent
@@ -68,9 +64,6 @@ public class AppAssembler
LayerAssembly infraLayer = appAss.layer( "infra" );
ModuleAssembly persistenceModule = infraLayer.module( "persistence" );
{
- persistenceModule.services( OrgJsonValueSerializationService.class ).
- taggedWith( ValueSerialization.Formats.JSON );
-
// SQL DataSource Service
String dataSourceServiceIdentity = "postgresql-datasource-service";
new DBCPDataSourceServiceAssembler().
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/settings.gradle
----------------------------------------------------------------------
diff --git a/settings.gradle b/settings.gradle
index f33d3eb..e0b6b7d 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -76,9 +76,9 @@ include 'core:api',
'extensions:metrics-codahale',
'extensions:migration',
'extensions:reindexer',
- 'extensions:valueserialization-orgjson',
- 'extensions:valueserialization-jackson',
- 'extensions:valueserialization-stax',
+ 'extensions:serialization-javaxjson',
+ 'extensions:serialization-javaxxml',
+ 'extensions:serialization-msgpack',
'tools:model-detail',
'tools:envisage',
// 'tools:generator-polygene',
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/tests/performance/build.gradle
----------------------------------------------------------------------
diff --git a/tests/performance/build.gradle b/tests/performance/build.gradle
index aeb44ec..1ff9b45 100644
--- a/tests/performance/build.gradle
+++ b/tests/performance/build.gradle
@@ -32,7 +32,6 @@ dependencies {
perfImplementation polygene.core.testsupport
perfImplementation polygene.library( 'sql-dbcp' )
- perfImplementation polygene.extension( 'valueserialization-orgjson' )
perfImplementation polygene.extension( 'entitystore-memory' )
perfImplementation polygene.extension( 'entitystore-jdbm' )
perfImplementation polygene.extension( 'entitystore-sql' )
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/jdbm/JdbmEntityStorePerformanceTest.java
----------------------------------------------------------------------
diff --git a/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/jdbm/JdbmEntityStorePerformanceTest.java b/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/jdbm/JdbmEntityStorePerformanceTest.java
index 047ffef..006cf85 100644
--- a/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/jdbm/JdbmEntityStorePerformanceTest.java
+++ b/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/jdbm/JdbmEntityStorePerformanceTest.java
@@ -29,7 +29,6 @@ import org.apache.polygene.entitystore.jdbm.JdbmConfiguration;
import org.apache.polygene.entitystore.jdbm.assembly.JdbmEntityStoreAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.performance.entitystore.AbstractEntityStorePerformanceTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
/**
* Performance test for JdbmEntityStoreComposite
@@ -51,7 +50,6 @@ public class JdbmEntityStorePerformanceTest
throws AssemblyException
{
new JdbmEntityStoreAssembler().assemble( module );
- new OrgJsonValueSerializationAssembler().assemble( module );
ModuleAssembly configModule = module.layer().module( "Config" );
configModule.entities( JdbmConfiguration.class ).visibleIn( Visibility.layer );
new EntityTestAssembler().assemble( configModule );
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/memory/MemoryEntityStorePerformanceTest.java
----------------------------------------------------------------------
diff --git a/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/memory/MemoryEntityStorePerformanceTest.java b/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/memory/MemoryEntityStorePerformanceTest.java
index bd664e1..956cc7a 100644
--- a/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/memory/MemoryEntityStorePerformanceTest.java
+++ b/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/memory/MemoryEntityStorePerformanceTest.java
@@ -21,11 +21,10 @@ import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.bootstrap.Assembler;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.entitystore.memory.assembly.MemoryEntityStoreAssembler;
import org.apache.polygene.entitystore.memory.MemoryEntityStoreService;
+import org.apache.polygene.entitystore.memory.assembly.MemoryEntityStoreAssembler;
import org.apache.polygene.spi.entitystore.helpers.MapEntityStoreMixin;
import org.apache.polygene.test.performance.entitystore.AbstractEntityStorePerformanceTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
public class MemoryEntityStorePerformanceTest
extends AbstractEntityStorePerformanceTest
@@ -45,7 +44,6 @@ public class MemoryEntityStorePerformanceTest
throws AssemblyException
{
new MemoryEntityStoreAssembler().assemble( module );
- new OrgJsonValueSerializationAssembler().assemble( module );
}
};
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/sql/DerbySQLEntityStorePerformanceTest.java
----------------------------------------------------------------------
diff --git a/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/sql/DerbySQLEntityStorePerformanceTest.java b/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/sql/DerbySQLEntityStorePerformanceTest.java
index d1ea720..5906307 100644
--- a/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/sql/DerbySQLEntityStorePerformanceTest.java
+++ b/tests/performance/src/perf/java/org/apache/polygene/test/performance/entitystore/sql/DerbySQLEntityStorePerformanceTest.java
@@ -34,7 +34,6 @@ import org.apache.polygene.library.sql.common.SQLUtil;
import org.apache.polygene.library.sql.dbcp.DBCPDataSourceServiceAssembler;
import org.apache.polygene.test.EntityTestAssembler;
import org.apache.polygene.test.performance.entitystore.AbstractEntityStorePerformanceTest;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
/**
* Performance test for DerbySQLEntityStore.
@@ -59,8 +58,6 @@ public class DerbySQLEntityStorePerformanceTest
ModuleAssembly config = module.layer().module( "config" );
new EntityTestAssembler().assemble( config );
- new OrgJsonValueSerializationAssembler().assemble( module );
-
// DataSourceService
new DBCPDataSourceServiceAssembler().
identifiedBy( "derby-datasource-service" ).
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/tests/performance/src/perf/java/org/apache/polygene/test/performance/indexing/rdf/QueryPerformanceTest.java
----------------------------------------------------------------------
diff --git a/tests/performance/src/perf/java/org/apache/polygene/test/performance/indexing/rdf/QueryPerformanceTest.java b/tests/performance/src/perf/java/org/apache/polygene/test/performance/indexing/rdf/QueryPerformanceTest.java
index a8e54ee..c83356a 100644
--- a/tests/performance/src/perf/java/org/apache/polygene/test/performance/indexing/rdf/QueryPerformanceTest.java
+++ b/tests/performance/src/perf/java/org/apache/polygene/test/performance/indexing/rdf/QueryPerformanceTest.java
@@ -19,12 +19,6 @@ package org.apache.polygene.test.performance.indexing.rdf;
import java.io.File;
import org.apache.derby.iapi.services.io.FileUtil;
-import org.apache.polygene.api.query.QueryBuilderFactory;
-import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.api.entity.EntityBuilder;
import org.apache.polygene.api.entity.EntityComposite;
@@ -33,12 +27,14 @@ import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.property.Property;
import org.apache.polygene.api.query.Query;
import org.apache.polygene.api.query.QueryBuilder;
+import org.apache.polygene.api.query.QueryBuilderFactory;
import org.apache.polygene.api.service.ServiceComposite;
import org.apache.polygene.api.service.ServiceReference;
import org.apache.polygene.api.structure.Application;
import org.apache.polygene.api.structure.Module;
import org.apache.polygene.api.unitofwork.UnitOfWork;
import org.apache.polygene.api.unitofwork.UnitOfWorkCompletionException;
+import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
import org.apache.polygene.bootstrap.ApplicationAssembler;
import org.apache.polygene.bootstrap.ApplicationAssembly;
import org.apache.polygene.bootstrap.ApplicationAssemblyFactory;
@@ -52,7 +48,10 @@ import org.apache.polygene.index.rdf.indexing.RdfIndexingService;
import org.apache.polygene.index.rdf.query.SesameExpressions;
import org.apache.polygene.library.rdf.repository.NativeConfiguration;
import org.apache.polygene.test.EntityTestAssembler;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationAssembler;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
import static org.apache.polygene.api.query.QueryExpressions.eq;
import static org.apache.polygene.api.query.QueryExpressions.templateFor;
@@ -300,7 +299,6 @@ public class QueryPerformanceTest
new RdfNativeSesameStoreAssembler().assemble( persistenceModule );
// Entity store
- new OrgJsonValueSerializationAssembler().assemble( persistenceModule );
new MemoryEntityStoreAssembler().visibleIn( Visibility.application ).assemble( persistenceModule );
return infrastructureLayer;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/tools/generator-polygene/app/index.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/index.js b/tools/generator-polygene/app/index.js
index b1a12c1..a0631e5 100644
--- a/tools/generator-polygene/app/index.js
+++ b/tools/generator-polygene/app/index.js
@@ -151,9 +151,8 @@ module.exports = generators.Base.extend(
type: 'list',
name: 'serialization',
choices: [
- 'Jackson',
- // 'Johnzon',
- 'Stax'
+ 'JavaxJson',
+ 'JavaxXml'
],
message: 'Which serialization system do you want to use?',
default: polygene.serialization ? polygene.serialization : "Jackson"
[20/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/package.html
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/package.html b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/package.html
new file mode 100644
index 0000000..16c905a
--- /dev/null
+++ b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/package.html
@@ -0,0 +1,24 @@
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ ~
+ ~
+ -->
+<html>
+ <body>
+ <h2>MessagePack Serialization.</h2>
+ </body>
+</html>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackCollectionSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackCollectionSerializationTest.java b/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackCollectionSerializationTest.java
new file mode 100644
index 0000000..6ade37f
--- /dev/null
+++ b/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackCollectionSerializationTest.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.msgpack;
+
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.test.serialization.AbstractCollectionSerializationTest;
+
+public class MessagePackCollectionSerializationTest extends AbstractCollectionSerializationTest
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ new MessagePackSerializationAssembler().assemble( module );
+ super.assemble( module );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackDateFormatSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackDateFormatSerializationTest.java b/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackDateFormatSerializationTest.java
new file mode 100644
index 0000000..083d418
--- /dev/null
+++ b/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackDateFormatSerializationTest.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.msgpack;
+
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.test.serialization.AbstractDateFormatSerializationTest;
+import org.junit.Ignore;
+
+@Ignore( "Super test assume text" )
+public class MessagePackDateFormatSerializationTest extends AbstractDateFormatSerializationTest
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ new MessagePackSerializationAssembler().assemble( module );
+ super.assemble( module );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackPlainValueSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackPlainValueSerializationTest.java b/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackPlainValueSerializationTest.java
new file mode 100644
index 0000000..3940b64
--- /dev/null
+++ b/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackPlainValueSerializationTest.java
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.serialization.msgpack;
+
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.test.serialization.AbstractPlainValueSerializationTest;
+import org.junit.Ignore;
+
+@Ignore( "Super test assume text" )
+public class MessagePackPlainValueSerializationTest extends AbstractPlainValueSerializationTest
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ new MessagePackSerializationAssembler().assemble( module );
+ super.assemble( module );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackValueCompositeSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackValueCompositeSerializationTest.java b/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackValueCompositeSerializationTest.java
new file mode 100644
index 0000000..204f991
--- /dev/null
+++ b/extensions/serialization-msgpack/src/test/java/org/apache/polygene/serialization/msgpack/MessagePackValueCompositeSerializationTest.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.msgpack;
+
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.test.serialization.AbstractValueCompositeSerializationTest;
+
+public class MessagePackValueCompositeSerializationTest extends AbstractValueCompositeSerializationTest
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ new MessagePackSerializationAssembler().assemble( module );
+ super.assemble( module );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-jackson/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/build.gradle b/extensions/valueserialization-jackson/build.gradle
deleted file mode 100644
index fa23ac3..0000000
--- a/extensions/valueserialization-jackson/build.gradle
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-
-apply plugin: 'polygene-extension'
-
-description = "Apache Polygene\u2122 Jackson ValueSerialization Extension"
-
-jar { manifest { name = "Apache Polygene\u2122 Extension - ValueSerialization - Jackson" } }
-
-dependencies {
- api polygene.core.bootstrap
-
- implementation libraries.jackson_mapper
-
- runtimeOnly polygene.core.runtime
-
- testImplementation polygene.core.testsupport
-
- testRuntimeOnly libraries.logback
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-jackson/dev-status.xml
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/dev-status.xml b/extensions/valueserialization-jackson/dev-status.xml
deleted file mode 100644
index 7fa50ff..0000000
--- a/extensions/valueserialization-jackson/dev-status.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one
- ~ or more contributor license agreements. See the NOTICE file
- ~ distributed with this work for additional information
- ~ regarding copyright ownership. The ASF licenses this file
- ~ to you under the Apache License, Version 2.0 (the
- ~ "License"); you may not use this file except in compliance
- ~ with the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- ~
- ~
- -->
-<module xmlns="http://polygene.apache.org/schemas/2008/dev-status/1"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://polygene.apache.org/schemas/2008/dev-status/1
- http://polygene.apache.org/schemas/2008/dev-status/1/dev-status.xsd">
- <status>
- <codebase>beta</codebase>
- <!--none,early,beta,stable,mature-->
- <documentation>good</documentation>
- <!-- none, brief, good, complete -->
- <unittests>complete</unittests>
- <!-- none, some, good, complete -->
- </status>
- <licenses>
- <license>ALv2</license>
- </licenses>
-</module>
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-jackson/src/docs/vs-jackson.txt
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/docs/vs-jackson.txt b/extensions/valueserialization-jackson/src/docs/vs-jackson.txt
deleted file mode 100644
index 8605125..0000000
--- a/extensions/valueserialization-jackson/src/docs/vs-jackson.txt
+++ /dev/null
@@ -1,43 +0,0 @@
-///////////////////////////////////////////////////////////////
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
-///////////////////////////////////////////////////////////////
-
-[[extension-vs-jackson, Jackson ValueSerialization]]
-= Jackson ValueSerialization =
-
-[devstatus]
---------------
-source=extensions/valueserialization-jackson/dev-status.xml
---------------
-
-ValueSerialization Service backed by http://wiki.fasterxml.com/JacksonHome[Jackson].
-
-include::../../build/docs/buildinfo/artifact.txt[]
-
-== Assembly ==
-
-Assembly is done as follows:
-
-[snippet,java]
-----
-source=extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonPlainValueSerializationTest.java
-tag=assembly
-----
-
-See the ValueSerialization <<core-api-value,API>> and <<core-spi-valueserialization,SPI>> documentation for details and
-usage.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/JacksonValueDeserializer.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/JacksonValueDeserializer.java b/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/JacksonValueDeserializer.java
deleted file mode 100644
index 256cbe7..0000000
--- a/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/JacksonValueDeserializer.java
+++ /dev/null
@@ -1,379 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.jackson;
-
-import com.fasterxml.jackson.core.JsonFactory;
-import com.fasterxml.jackson.core.JsonParser;
-import com.fasterxml.jackson.core.JsonToken;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.MappingJsonFactory;
-import com.fasterxml.jackson.databind.node.ArrayNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-import java.io.InputStream;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.function.Function;
-import org.apache.polygene.api.structure.ModuleDescriptor;
-import org.apache.polygene.api.type.ValueType;
-import org.apache.polygene.api.value.ValueSerializationException;
-import org.apache.polygene.spi.value.ValueDeserializerAdapter;
-
-/**
- * ValueDeserializer reading Values from JSON documents using Jackson.
- */
-public class JacksonValueDeserializer
- extends ValueDeserializerAdapter<JsonParser, JsonNode>
-{
-
- private final JsonFactory jsonFactory = new MappingJsonFactory();
-
- @Override
- protected JsonParser adaptInput( ModuleDescriptor module, InputStream input )
- throws Exception
- {
- return jsonFactory.createParser( input );
- }
-
- @Override
- protected void onDeserializationEnd( ModuleDescriptor module, ValueType valueType, JsonParser input )
- throws Exception
- {
- input.close();
- }
-
- @Override
- protected Object readPlainValue( ModuleDescriptor module, JsonParser input )
- throws Exception
- {
- JsonNode jsonNode = input.readValueAsTree();
- if( jsonNode.isArray() || jsonNode.isObject() )
- {
- throw new ValueSerializationException( "Asked for a Value but found an Object or an Array at "
- + input.getCurrentLocation().toString() );
- }
- if( jsonNode.isDouble() )
- {
- return jsonNode.asDouble();
- }
- if( jsonNode.isLong() )
- {
- return jsonNode.asLong();
- }
- if( jsonNode.isInt() )
- {
- return jsonNode.asInt();
- }
- if( jsonNode.isBoolean() )
- {
- return jsonNode.asBoolean();
- }
- if( jsonNode.isNull() )
- {
- return null;
- }
- return jsonNode.asText();
- }
-
- @Override
- protected <T> Collection<T> readArrayInCollection( ModuleDescriptor module,
- JsonParser input,
- Function<JsonParser, T> deserializer,
- Collection<T> collection
- )
- throws Exception
- {
- JsonToken token = input.getCurrentToken();
- if( token == JsonToken.VALUE_NULL )
- {
- return null;
- }
- if( token != JsonToken.START_ARRAY )
- {
- token = input.nextToken();
- }
- if( token == JsonToken.VALUE_NULL )
- {
- return null;
- }
- if( token != JsonToken.START_ARRAY )
- {
- throw new ValueSerializationException( "Expected an array start at "
- + input.getCurrentLocation().toString() );
- }
- while( input.nextToken() != JsonToken.END_ARRAY )
- {
- T element = deserializer.apply( input );
- collection.add( element );
- }
- return collection;
- }
-
- @Override
- protected <K, V> Map<K, V> readMapInMap( ModuleDescriptor module,
- JsonParser input,
- Function<JsonParser, K> keyDeserializer,
- Function<JsonParser, V> valueDeserializer,
- Map<K, V> map
- )
- throws Exception
- {
- JsonToken token = input.getCurrentToken();
- if( token == JsonToken.VALUE_NULL )
- {
- return null;
- }
- if( token != JsonToken.START_ARRAY )
- {
- token = input.nextToken();
- }
- if( token == JsonToken.VALUE_NULL )
- {
- return null;
- }
- if( token != JsonToken.START_ARRAY )
- {
- throw new ValueSerializationException( "Expected an array start at "
- + input.getCurrentLocation().toString() );
- }
- JsonToken currentToken = input.nextToken();
- while( currentToken != JsonToken.END_ARRAY )
- {
- if( currentToken != JsonToken.START_OBJECT )
- {
- throw new ValueSerializationException( "Expected an object start at "
- + input.getCurrentLocation().toString() );
- }
- currentToken = input.nextToken();
- K key = null;
- V value = null;
- while( currentToken != JsonToken.END_OBJECT )
- {
- String objectKey = input.getCurrentName();
- input.nextToken();
- if( "key".equals( objectKey ) )
- {
- key = keyDeserializer.apply( input );
- }
- else if( "value".equals( objectKey ) )
- {
- value = valueDeserializer.apply( input );
- }
- else
- {
- //input.nextToken();
- input.skipChildren();
- }
- currentToken = input.nextToken();
- }
- if( key != null )
- {
- map.put( key, value );
- }
- currentToken = input.nextToken();
- }
- return map;
- }
-
- @Override
- protected ObjectNode readObjectTree( ModuleDescriptor module, JsonParser input )
- throws Exception
- {
- JsonToken token = input.getCurrentToken();
- if( token == JsonToken.VALUE_NULL )
- {
- return null;
- }
- if( token != JsonToken.START_OBJECT )
- {
- token = input.nextToken();
- }
- if( token != JsonToken.START_OBJECT )
- {
- String message = "Expected an object start at " + input.getCurrentLocation().toString();
- throw new ValueSerializationException( message );
- }
- return (ObjectNode) input.readValueAsTree();
- }
-
- @Override
- protected Object asSimpleValue( ModuleDescriptor module, JsonNode inputNode )
- throws Exception
- {
- if( isNullOrMissing( inputNode ) )
- {
- return null;
- }
- if( !inputNode.isValueNode() )
- {
- throw new ValueSerializationException( "Expected a value node but got a container node " + inputNode );
- }
- if( inputNode.isDouble() )
- {
- return inputNode.asDouble();
- }
- if( inputNode.isLong() )
- {
- return inputNode.asLong();
- }
- if( inputNode.isInt() )
- {
- return inputNode.asInt();
- }
- if( inputNode.isBoolean() )
- {
- return inputNode.asBoolean();
- }
- return inputNode.asText();
- }
-
- @Override
- @SuppressWarnings( "SimplifiableIfStatement" )
- protected boolean isObjectValue( ModuleDescriptor module, JsonNode inputNode )
- throws Exception
- {
- if( isNullOrMissing( inputNode ) )
- {
- return false;
- }
- return inputNode.isObject();
- }
-
- @Override
- protected boolean objectHasField( ModuleDescriptor module, JsonNode inputNode, String key )
- throws Exception
- {
- if( isNullOrMissing( inputNode ) )
- {
- return false;
- }
- if( !inputNode.isObject() )
- {
- throw new ValueSerializationException( "Expected an object but got " + inputNode );
- }
- return inputNode.has( key );
- }
-
- @Override
- protected <T> T getObjectFieldValue( ModuleDescriptor module,
- JsonNode inputNode,
- String key,
- Function<JsonNode, T> valueDeserializer
- )
- throws Exception
- {
- JsonNode valueNode = inputNode.get( key );
- if( isNullOrMissing( valueNode ) )
- {
- return null;
- }
- return valueDeserializer.apply( valueNode );
- }
-
- @Override
- protected <T> void putArrayNodeInCollection( ModuleDescriptor module,
- JsonNode inputNode,
- Function<JsonNode, T> deserializer,
- Collection<T> collection
- )
- throws Exception
- {
- if( isNullOrMissing( inputNode ) )
- {
- return;
- }
- if( !inputNode.isArray() )
- {
- throw new ValueSerializationException( "Expected an array but got " + inputNode );
- }
- ArrayNode array = (ArrayNode) inputNode;
- for( JsonNode item : array )
- {
- T value = deserializer.apply( item );
- collection.add( value );
- }
- }
-
- @Override
- protected <K, V> void putArrayNodeInMap( ModuleDescriptor module,
- JsonNode inputNode,
- Function<JsonNode, K> keyDeserializer,
- Function<JsonNode, V> valueDeserializer,
- Map<K, V> map
- )
- throws Exception
- {
- if( isNullOrMissing( inputNode ) )
- {
- return;
- }
- if( !inputNode.isArray() )
- {
- throw new ValueSerializationException( "Expected an array but got " + inputNode );
- }
- ArrayNode array = (ArrayNode) inputNode;
- for( JsonNode item : array )
- {
- if( !item.isObject() )
- {
- throw new ValueSerializationException( "Expected an object but got " + inputNode );
- }
- JsonNode keyNode = item.get( "key" );
- JsonNode valueNode = item.get( "value" );
- K key = keyDeserializer.apply( keyNode );
- V value = valueDeserializer.apply( valueNode );
- if( key != null )
- {
- map.put( key, value );
- }
- }
- }
-
- @Override
- protected <V> void putObjectNodeInMap( ModuleDescriptor module,
- JsonNode inputNode,
- Function<JsonNode, V> valueDeserializer,
- Map<String, V> map
- )
- throws Exception
- {
- if( isNullOrMissing( inputNode ) )
- {
- return;
- }
- if( !inputNode.isObject() )
- {
- throw new ValueSerializationException( "Expected an object but got " + inputNode );
- }
- ObjectNode object = (ObjectNode) inputNode;
- Iterator<Map.Entry<String, JsonNode>> fields = object.fields();
- while( fields.hasNext() )
- {
- Map.Entry<String, JsonNode> entry = fields.next();
- V value = valueDeserializer.apply( entry.getValue() );
- map.put( entry.getKey(), value );
- }
- }
-
- private static boolean isNullOrMissing( JsonNode inputNode )
- {
- return inputNode == null || inputNode.isNull() || inputNode.isMissingNode();
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/JacksonValueSerializationService.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/JacksonValueSerializationService.java b/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/JacksonValueSerializationService.java
deleted file mode 100644
index b05c7d9..0000000
--- a/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/JacksonValueSerializationService.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.jackson;
-
-import org.apache.polygene.api.mixin.Mixins;
-import org.apache.polygene.api.value.ValueSerialization;
-
-/**
- * ValueSerialization Service producing and consuming JSON documents using Jackson.
- */
-@Mixins( { JacksonValueSerializer.class, JacksonValueDeserializer.class } )
-public interface JacksonValueSerializationService
- extends ValueSerialization
-{
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/JacksonValueSerializer.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/JacksonValueSerializer.java b/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/JacksonValueSerializer.java
deleted file mode 100644
index a52b030..0000000
--- a/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/JacksonValueSerializer.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.jackson;
-
-import com.fasterxml.jackson.core.JsonFactory;
-import com.fasterxml.jackson.core.JsonGenerator;
-import com.fasterxml.jackson.databind.MappingJsonFactory;
-import java.io.OutputStream;
-import org.apache.polygene.spi.value.ValueSerializerAdapter;
-
-/**
- * ValueSerializer producing Values state as JSON documents using Jackson.
- */
-public class JacksonValueSerializer
- extends ValueSerializerAdapter<JsonGenerator>
-{
-
- private final JsonFactory jsonFactory = new MappingJsonFactory();
-
- @Override
- protected JsonGenerator adaptOutput( OutputStream output )
- throws Exception
- {
- return jsonFactory.createGenerator( output );
- }
-
- @Override
- protected void onSerializationEnd( Object object, JsonGenerator output )
- throws Exception
- {
- output.close();
- }
-
- @Override
- protected void onArrayStart( JsonGenerator output )
- throws Exception
- {
- output.writeStartArray();
- }
-
- @Override
- protected void onArrayEnd( JsonGenerator output )
- throws Exception
- {
- output.writeEndArray();
- }
-
- @Override
- protected void onObjectStart( JsonGenerator output )
- throws Exception
- {
- output.writeStartObject();
- }
-
- @Override
- protected void onObjectEnd( JsonGenerator output )
- throws Exception
- {
- output.writeEndObject();
- }
-
- @Override
- protected void onFieldStart( JsonGenerator output, String fieldName )
- throws Exception
- {
- output.writeFieldName( fieldName );
- }
-
- @Override
- protected void onValue( JsonGenerator output, Object value )
- throws Exception
- {
- output.writeObject( value );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/assembly/JacksonValueSerializationAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/assembly/JacksonValueSerializationAssembler.java b/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/assembly/JacksonValueSerializationAssembler.java
deleted file mode 100644
index 7bff000..0000000
--- a/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/assembly/JacksonValueSerializationAssembler.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.jackson.assembly;
-
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.bootstrap.Assemblers;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.valueserialization.jackson.JacksonValueSerializationService;
-
-/**
- * Assemble a ValueSerialization Service producing and consuming JSON documents.
- */
-public class JacksonValueSerializationAssembler
- extends Assemblers.Visibility<JacksonValueSerializationAssembler>
-{
- @Override
- public void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- module.services( JacksonValueSerializationService.class )
- .visibleIn( visibility() )
- .taggedWith( ValueSerialization.Formats.JSON );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/package.html
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/package.html b/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/package.html
deleted file mode 100644
index d229040..0000000
--- a/extensions/valueserialization-jackson/src/main/java/org/apache/polygene/valueserialization/jackson/package.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one
- ~ or more contributor license agreements. See the NOTICE file
- ~ distributed with this work for additional information
- ~ regarding copyright ownership. The ASF licenses this file
- ~ to you under the Apache License, Version 2.0 (the
- ~ "License"); you may not use this file except in compliance
- ~ with the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- ~
- ~
- -->
-<html>
- <body>
- <h2>Jackson Value Serializer.</h2>
- </body>
-</html>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonCollectionSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonCollectionSerializationTest.java b/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonCollectionSerializationTest.java
deleted file mode 100644
index f4069c3..0000000
--- a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonCollectionSerializationTest.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.jackson;
-
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.value.AbstractCollectionSerializationTest;
-import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
-
-public class JacksonCollectionSerializationTest
- extends AbstractCollectionSerializationTest
-{
-
- @Override
- public void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- super.assemble( module );
- new JacksonValueSerializationAssembler().assemble( module );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonConfigurationDeserializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonConfigurationDeserializationTest.java b/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonConfigurationDeserializationTest.java
deleted file mode 100644
index 1948d62..0000000
--- a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonConfigurationDeserializationTest.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-
-package org.apache.polygene.valueserialization.jackson;
-
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.entity.AbstractConfigurationDeserializationTest;
-import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
-
-public class JacksonConfigurationDeserializationTest
- extends AbstractConfigurationDeserializationTest
-{
- @Override
- public void assemble( final ModuleAssembly module )
- throws AssemblyException
- {
- super.assemble( module );
- new JacksonValueSerializationAssembler()
- .assemble( module );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonJsonDateFormatTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonJsonDateFormatTest.java b/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonJsonDateFormatTest.java
deleted file mode 100644
index bbc141d..0000000
--- a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonJsonDateFormatTest.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.jackson;
-
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.value.AbstractJsonDateFormatTest;
-import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
-
-public class JacksonJsonDateFormatTest
- extends AbstractJsonDateFormatTest
-{
-
- @Override
- public void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- super.assemble( module );
- new JacksonValueSerializationAssembler().assemble( module );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonPlainValueSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonPlainValueSerializationTest.java b/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonPlainValueSerializationTest.java
deleted file mode 100644
index cdcce17..0000000
--- a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonPlainValueSerializationTest.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.jackson;
-
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.value.AbstractPlainValueSerializationTest;
-import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
-
-public class JacksonPlainValueSerializationTest
- extends AbstractPlainValueSerializationTest
-{
- // START SNIPPET: assembly
- @Override
- public void assemble( ModuleAssembly module )
- {
- new JacksonValueSerializationAssembler().assemble( module );
- }
- // END SNIPPET: assembly
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonValueCompositeSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonValueCompositeSerializationTest.java b/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonValueCompositeSerializationTest.java
deleted file mode 100644
index 2a757ab..0000000
--- a/extensions/valueserialization-jackson/src/test/java/org/apache/polygene/valueserialization/jackson/JacksonValueCompositeSerializationTest.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.jackson;
-
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.value.AbstractValueCompositeSerializationTest;
-import org.apache.polygene.valueserialization.jackson.assembly.JacksonValueSerializationAssembler;
-
-public class JacksonValueCompositeSerializationTest
- extends AbstractValueCompositeSerializationTest
-{
-
- @Override
- public void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- super.assemble( module );
- new JacksonValueSerializationAssembler().assemble( module );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-jackson/src/test/resources/configtest.json
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-jackson/src/test/resources/configtest.json b/extensions/valueserialization-jackson/src/test/resources/configtest.json
deleted file mode 100644
index d48a241..0000000
--- a/extensions/valueserialization-jackson/src/test/resources/configtest.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "identity" : "configtest",
- "host": {
- "ip": "12.23.34.45",
- "port": 1234
- },
- "name": "main"
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-orgjson/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-orgjson/build.gradle b/extensions/valueserialization-orgjson/build.gradle
deleted file mode 100644
index 5431ec5..0000000
--- a/extensions/valueserialization-orgjson/build.gradle
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-
-apply plugin: 'polygene-extension'
-
-description = "Apache Polygene\u2122 org.json ValueSerialization Extension"
-
-jar { manifest { name = "Apache Polygene\u2122 Extension - ValueSerialization - org.json" } }
-
-dependencies {
- api polygene.core.bootstrap
-
- runtimeOnly polygene.core.runtime
-
- testImplementation polygene.core.testsupport
-
- testRuntimeOnly libraries.logback
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-orgjson/dev-status.xml
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-orgjson/dev-status.xml b/extensions/valueserialization-orgjson/dev-status.xml
deleted file mode 100644
index dbb4472..0000000
--- a/extensions/valueserialization-orgjson/dev-status.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one
- ~ or more contributor license agreements. See the NOTICE file
- ~ distributed with this work for additional information
- ~ regarding copyright ownership. The ASF licenses this file
- ~ to you under the Apache License, Version 2.0 (the
- ~ "License"); you may not use this file except in compliance
- ~ with the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- ~
- ~
- -->
-<module xmlns="http://polygene.apache.org/schemas/2008/dev-status/1"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://polygene.apache.org/schemas/2008/dev-status/1
- http://polygene.apache.org/schemas/2008/dev-status/1/dev-status.xsd">
- <status>
- <codebase>stable</codebase>
- <!--none,early,beta,stable,mature-->
- <documentation>good</documentation>
- <!-- none, brief, good, complete -->
- <unittests>complete</unittests>
- <!-- none, some, good, complete -->
- </status>
- <licenses>
- <license>ALv2</license>
- </licenses>
-</module>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-orgjson/src/docs/vs-orgjson.txt
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-orgjson/src/docs/vs-orgjson.txt b/extensions/valueserialization-orgjson/src/docs/vs-orgjson.txt
deleted file mode 100644
index bbf50f7..0000000
--- a/extensions/valueserialization-orgjson/src/docs/vs-orgjson.txt
+++ /dev/null
@@ -1,43 +0,0 @@
-///////////////////////////////////////////////////////////////
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
-///////////////////////////////////////////////////////////////
-
-[[extension-vs-orgjson, org.json ValueSerialization]]
-= org.json ValueSerialization =
-
-[devstatus]
---------------
-source=extensions/valueserialization-orgjson/dev-status.xml
---------------
-
-ValueSerialization Service backed by https://github.com/douglascrockford/JSON-java[org.json].
-
-include::../../build/docs/buildinfo/artifact.txt[]
-
-== Assembly ==
-
-Assembly is done as follows:
-
-[snippet,java]
-----
-source=extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonPlainValueSerializationTest.java
-tag=assembly
-----
-
-See the ValueSerialization <<core-api-value,API>> and <<core-spi-valueserialization,SPI>> documentation for details and
-usage.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-orgjson/src/main/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueSerializationAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-orgjson/src/main/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueSerializationAssembler.java b/extensions/valueserialization-orgjson/src/main/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueSerializationAssembler.java
deleted file mode 100644
index 07e5151..0000000
--- a/extensions/valueserialization-orgjson/src/main/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueSerializationAssembler.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.orgjson;
-
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.bootstrap.Assemblers;
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-
-/**
- * Assemble a ValueSerialization Service producing and consuming JSON documents.
- */
-public class OrgJsonValueSerializationAssembler
- extends Assemblers.Visibility<OrgJsonValueSerializationAssembler>
-{
- @Override
- public void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- module.services( OrgJsonValueSerializationService.class ).
- visibleIn( visibility() ).
- taggedWith( ValueSerialization.Formats.JSON );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-orgjson/src/main/java/org/apache/polygene/valueserialization/orgjson/package.html
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-orgjson/src/main/java/org/apache/polygene/valueserialization/orgjson/package.html b/extensions/valueserialization-orgjson/src/main/java/org/apache/polygene/valueserialization/orgjson/package.html
deleted file mode 100644
index 4799b58..0000000
--- a/extensions/valueserialization-orgjson/src/main/java/org/apache/polygene/valueserialization/orgjson/package.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one
- ~ or more contributor license agreements. See the NOTICE file
- ~ distributed with this work for additional information
- ~ regarding copyright ownership. The ASF licenses this file
- ~ to you under the Apache License, Version 2.0 (the
- ~ "License"); you may not use this file except in compliance
- ~ with the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- ~
- ~
- -->
-<html>
- <body>
- <h2>org.json Value Serialization.</h2>
- </body>
-</html>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonCollectionSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonCollectionSerializationTest.java b/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonCollectionSerializationTest.java
deleted file mode 100644
index a109c5f..0000000
--- a/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonCollectionSerializationTest.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.orgjson;
-
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.value.AbstractCollectionSerializationTest;
-
-public class OrgJsonCollectionSerializationTest
- extends AbstractCollectionSerializationTest
-{
-
- @Override
- public void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- super.assemble( module );
- new OrgJsonValueSerializationAssembler().assemble( module );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonConfigurationDeserializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonConfigurationDeserializationTest.java b/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonConfigurationDeserializationTest.java
deleted file mode 100644
index c22f58f..0000000
--- a/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonConfigurationDeserializationTest.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-
-package org.apache.polygene.valueserialization.orgjson;
-
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.entity.AbstractConfigurationDeserializationTest;
-
-public class OrgJsonConfigurationDeserializationTest
- extends AbstractConfigurationDeserializationTest
-{
- @Override
- public void assemble( final ModuleAssembly module )
- throws AssemblyException
- {
- super.assemble( module );
- new OrgJsonValueSerializationAssembler()
- .assemble( module );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonDateFormatTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonDateFormatTest.java b/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonDateFormatTest.java
deleted file mode 100644
index 23695ff..0000000
--- a/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonDateFormatTest.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.orgjson;
-
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.value.AbstractJsonDateFormatTest;
-
-public class OrgJsonDateFormatTest
- extends AbstractJsonDateFormatTest
-{
-
- @Override
- public void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- super.assemble( module );
- new OrgJsonValueSerializationAssembler().assemble( module );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonPlainValueSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonPlainValueSerializationTest.java b/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonPlainValueSerializationTest.java
deleted file mode 100644
index ef1f928..0000000
--- a/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonPlainValueSerializationTest.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.orgjson;
-
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.value.AbstractPlainValueSerializationTest;
-
-public class OrgJsonPlainValueSerializationTest
- extends AbstractPlainValueSerializationTest
-{
- // START SNIPPET: assembly
- @Override
- public void assemble( ModuleAssembly module )
- {
- new OrgJsonValueSerializationAssembler().assemble( module );
- }
- // END SNIPPET: assembly
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueCompositeSerializationTest.java
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueCompositeSerializationTest.java b/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueCompositeSerializationTest.java
deleted file mode 100644
index ca791a4..0000000
--- a/extensions/valueserialization-orgjson/src/test/java/org/apache/polygene/valueserialization/orgjson/OrgJsonValueCompositeSerializationTest.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-package org.apache.polygene.valueserialization.orgjson;
-
-import org.apache.polygene.bootstrap.AssemblyException;
-import org.apache.polygene.bootstrap.ModuleAssembly;
-import org.apache.polygene.test.value.AbstractValueCompositeSerializationTest;
-
-public class OrgJsonValueCompositeSerializationTest
- extends AbstractValueCompositeSerializationTest
-{
-
- @Override
- public void assemble( ModuleAssembly module )
- throws AssemblyException
- {
- super.assemble( module );
- new OrgJsonValueSerializationAssembler().assemble( module );
- }
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-orgjson/src/test/resources/configtest.json
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-orgjson/src/test/resources/configtest.json b/extensions/valueserialization-orgjson/src/test/resources/configtest.json
deleted file mode 100644
index d48a241..0000000
--- a/extensions/valueserialization-orgjson/src/test/resources/configtest.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "identity" : "configtest",
- "host": {
- "ip": "12.23.34.45",
- "port": 1234
- },
- "name": "main"
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-stax/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/build.gradle b/extensions/valueserialization-stax/build.gradle
deleted file mode 100644
index 83e6175..0000000
--- a/extensions/valueserialization-stax/build.gradle
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *
- */
-
-apply plugin: 'polygene-extension'
-
-description = "Apache Polygene\u2122 StaX ValueSerialization Extension"
-
-jar { manifest { name = "Apache Polygene\u2122 Extension - ValueSerialization - StaX" } }
-
-dependencies {
- api polygene.core.bootstrap
-
- implementation libraries.commons_lang
-
- runtimeOnly polygene.core.runtime
-
- testImplementation polygene.core.testsupport
-
- testRuntimeOnly libraries.logback
-}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-stax/dev-status.xml
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/dev-status.xml b/extensions/valueserialization-stax/dev-status.xml
deleted file mode 100644
index 7fa50ff..0000000
--- a/extensions/valueserialization-stax/dev-status.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one
- ~ or more contributor license agreements. See the NOTICE file
- ~ distributed with this work for additional information
- ~ regarding copyright ownership. The ASF licenses this file
- ~ to you under the Apache License, Version 2.0 (the
- ~ "License"); you may not use this file except in compliance
- ~ with the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- ~
- ~
- -->
-<module xmlns="http://polygene.apache.org/schemas/2008/dev-status/1"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://polygene.apache.org/schemas/2008/dev-status/1
- http://polygene.apache.org/schemas/2008/dev-status/1/dev-status.xsd">
- <status>
- <codebase>beta</codebase>
- <!--none,early,beta,stable,mature-->
- <documentation>good</documentation>
- <!-- none, brief, good, complete -->
- <unittests>complete</unittests>
- <!-- none, some, good, complete -->
- </status>
- <licenses>
- <license>ALv2</license>
- </licenses>
-</module>
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/valueserialization-stax/src/docs/vs-stax.txt
----------------------------------------------------------------------
diff --git a/extensions/valueserialization-stax/src/docs/vs-stax.txt b/extensions/valueserialization-stax/src/docs/vs-stax.txt
deleted file mode 100644
index 416caf4..0000000
--- a/extensions/valueserialization-stax/src/docs/vs-stax.txt
+++ /dev/null
@@ -1,43 +0,0 @@
-///////////////////////////////////////////////////////////////
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
-///////////////////////////////////////////////////////////////
-
-[[extension-vs-stax, StAX ValueSerialization]]
-= StAX ValueSerialization =
-
-[devstatus]
---------------
-source=extensions/valueserialization-stax/dev-status.xml
---------------
-
-ValueSerialization Service backed by http://jcp.org/en/jsr/detail?id=173[StAX].
-
-include::../../build/docs/buildinfo/artifact.txt[]
-
-== Assembly ==
-
-Assembly is done as follows:
-
-[snippet,java]
-----
-source=extensions/valueserialization-stax/src/test/java/org/apache/polygene/valueserialization/stax/StaxPlainValueSerializationTest.java
-tag=assembly
-----
-
-See the ValueSerialization <<core-api-value,API>> and <<core-spi-valueserialization,SPI>> documentation for details and
-usage.
[21/50] [abbrv] polygene-java git commit: New (de)serialization API
and SPI & new implementations
Posted by pa...@apache.org.
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java
new file mode 100644
index 0000000..bf26f0c
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSerializer.java
@@ -0,0 +1,271 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxxml;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+import java.io.UncheckedIOException;
+import java.util.Base64;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import org.apache.polygene.api.PolygeneAPI;
+import org.apache.polygene.api.association.AssociationStateHolder;
+import org.apache.polygene.api.composite.CompositeInstance;
+import org.apache.polygene.api.entity.EntityReference;
+import org.apache.polygene.api.injection.scope.This;
+import org.apache.polygene.api.injection.scope.Uses;
+import org.apache.polygene.api.serialization.SerializationException;
+import org.apache.polygene.api.service.ServiceDescriptor;
+import org.apache.polygene.api.type.EnumType;
+import org.apache.polygene.api.type.MapType;
+import org.apache.polygene.api.type.ValueCompositeType;
+import org.apache.polygene.api.value.ValueComposite;
+import org.apache.polygene.api.value.ValueDescriptor;
+import org.apache.polygene.spi.serialization.AbstractTextSerializer;
+import org.apache.polygene.spi.serialization.XmlSerializer;
+import org.w3c.dom.DOMException;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.apache.polygene.api.util.Collectors.toMap;
+
+/**
+ * XML Serializer.
+ */
+public class JavaxXmlSerializer extends AbstractTextSerializer implements XmlSerializer
+{
+ private static final String NULL_ELEMENT_NAME = "null";
+
+ @This
+ private JavaxXmlAdapters adapters;
+
+ @Uses
+ private ServiceDescriptor descriptor;
+
+ @Override
+ public <T> Function<T, Document> toXmlFunction( Options options )
+ {
+ return object -> doSerializeRoot( options, object );
+ }
+
+ private <T> Document doSerializeRoot( Options options, T object )
+ {
+ try
+ {
+ Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
+ doc.setXmlVersion( "1.1" );
+ doc.setXmlStandalone( true );
+ Element stateElement = doc.createElement( getSettings().getRootTagName() );
+ Node node = doSerialize( doc, options, object, true );
+ stateElement.appendChild( node );
+ doc.appendChild( stateElement );
+ return doc;
+ }
+ catch( ParserConfigurationException ex )
+ {
+ throw new SerializationException( "Unable to create XML document. "
+ + "Is your javax.xml subsystem correctly set up?", ex );
+ }
+ }
+
+ private <T> Node doSerialize( Document document, Options options, T object, boolean root )
+ {
+ if( object == null )
+ {
+ return document.createElement( NULL_ELEMENT_NAME );
+ }
+ Class<?> objectClass = object.getClass();
+ JavaxXmlAdapter<?> adapter = adapters.adapterFor( objectClass );
+ if( adapter != null )
+ {
+ return adapter.serialize( document, object, value -> doSerialize( document, options, value, false ) );
+ }
+ if( EnumType.isEnum( objectClass ) )
+ {
+ return document.createTextNode( object.toString() );
+ }
+ if( ValueCompositeType.isValueComposite( objectClass ) )
+ {
+ return serializeValueComposite( document, options, object, root );
+ }
+ if( MapType.isMap( objectClass ) )
+ {
+ return serializeMap( document, options, (Map<?, ?>) object );
+ }
+ if( Iterable.class.isAssignableFrom( objectClass ) )
+ {
+ return serializeIterable( document, options, (Iterable<?>) object );
+ }
+ if( Stream.class.isAssignableFrom( objectClass ) )
+ {
+ return serializeStream( document, options, (Stream<?>) object );
+ }
+ // Fallback to Java Serialization in Base 64
+ // Include all arrays!
+ return serializeBase64( document, object );
+ }
+
+ private <T> Node serializeValueComposite( Document document, Options options, T composite, boolean root )
+ {
+ CompositeInstance instance = PolygeneAPI.FUNCTION_COMPOSITE_INSTANCE_OF.apply( (ValueComposite) composite );
+ ValueDescriptor descriptor = (ValueDescriptor) instance.descriptor();
+ AssociationStateHolder state = (AssociationStateHolder) instance.state();
+ ValueCompositeType valueType = descriptor.valueType();
+
+ Element valueElement = document.createElement( getSettings().getValueTagName() );
+ valueType.properties().forEach(
+ property ->
+ {
+ Object value = state.propertyFor( property.accessor() ).get();
+ Element element = document.createElement( property.qualifiedName().name() );
+ element.appendChild( doSerialize( document, options, value, false ) );
+ valueElement.appendChild( element );
+ } );
+ valueType.associations().forEach(
+ association ->
+ {
+ EntityReference value = state.associationFor( association.accessor() ).reference();
+ Element element = document.createElement( association.qualifiedName().name() );
+ element.appendChild( doSerialize( document, options, value, false ) );
+ valueElement.appendChild( element );
+ }
+ );
+ valueType.manyAssociations().forEach(
+ association ->
+ {
+ Stream<EntityReference> value = state.manyAssociationFor( association.accessor() ).references();
+ Element element = document.createElement( association.qualifiedName().name() );
+ element.appendChild( doSerialize( document, options, value, false ) );
+ valueElement.appendChild( element );
+ }
+ );
+ valueType.namedAssociations().forEach(
+ association ->
+ {
+ Map<String, EntityReference> value = state.namedAssociationFor( association.accessor() ).references()
+ .collect( toMap() );
+ Element element = document.createElement( association.qualifiedName().name() );
+ element.appendChild( doSerialize( document, options, value, false ) );
+ valueElement.appendChild( element );
+ }
+ );
+ if( !root && options.includeTypeInfo() )
+ {
+ valueElement.setAttribute( getSettings().getTypeInfoTagName(), valueType.primaryType().getName() );
+ }
+ return valueElement;
+ }
+
+ private Node serializeMap( Document document, Options options, Map<?, ?> map )
+ {
+ JavaxXmlSettings settings = getSettings();
+ Element mapElement = document.createElement( settings.getMapTagName() );
+ if( map.isEmpty() )
+ {
+ return mapElement;
+ }
+ Function<Map.Entry, Node> complexMapping = entry ->
+ {
+ Element entryElement = document.createElement( settings.getMapEntryTagName() );
+
+ Element keyElement = document.createElement( "key" );
+ keyElement.appendChild( doSerialize( document, options, entry.getKey(), false ) );
+ entryElement.appendChild( keyElement );
+
+ Element valueElement = document.createElement( "value" );
+ valueElement.appendChild( doSerialize( document, options, entry.getValue(), false ) );
+ entryElement.appendChild( valueElement );
+
+ return entryElement;
+ };
+
+ if( map.keySet().iterator().next() instanceof CharSequence )
+ {
+ map.entrySet().stream()
+ .map( entry ->
+ {
+ try
+ {
+ Element element = document.createElement( entry.getKey().toString() );
+ element.appendChild( doSerialize( document, options, entry.getValue(), false ) );
+ return element;
+ }
+ catch( DOMException ex )
+ {
+ // The key name cannot be encoded as a tag name, fallback to complex mapping
+ // Tag names cannot start with a digit, some characters cannot be escaped etc...
+ return complexMapping.apply( entry );
+ }
+ } )
+ .forEach( mapElement::appendChild );
+ }
+ else
+ {
+ map.entrySet().stream()
+ .map( complexMapping )
+ .forEach( mapElement::appendChild );
+ }
+ return mapElement;
+ }
+
+ private Node serializeIterable( Document document, Options options, Iterable<?> object )
+ {
+ return serializeStream( document, options, StreamSupport.stream( object.spliterator(), false ) );
+ }
+
+ private Node serializeStream( Document document, Options options, Stream<?> object )
+ {
+ JavaxXmlSettings settings = getSettings();
+ Element collectionElement = document.createElement( settings.getCollectionTagName() );
+ object.map( each -> doSerialize( document, options, each, false ) )
+ .forEach( itemValueNode ->
+ {
+ Element itemElement = document.createElement( settings.getCollectionElementTagName() );
+ itemElement.appendChild( itemValueNode );
+ collectionElement.appendChild( itemElement );
+ } );
+ return collectionElement;
+ }
+
+ private <T> Node serializeBase64( Document document, T object )
+ {
+ ByteArrayOutputStream bout = new ByteArrayOutputStream();
+ try( ObjectOutputStream out = new ObjectOutputStream( bout ) )
+ {
+ out.writeUnshared( object );
+ byte[] bytes = Base64.getEncoder().encode( bout.toByteArray() );
+ return document.createCDATASection( new String( bytes, UTF_8 ) );
+ }
+ catch( IOException ex )
+ {
+ throw new UncheckedIOException( ex );
+ }
+ }
+
+ private JavaxXmlSettings getSettings()
+ {
+ return JavaxXmlSettings.orDefault( descriptor.metaInfo( JavaxXmlSettings.class ) );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSettings.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSettings.java b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSettings.java
new file mode 100644
index 0000000..b5c5702
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/JavaxXmlSettings.java
@@ -0,0 +1,134 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxxml;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.apache.polygene.api.type.ValueType;
+
+/**
+ * javax.xml settings.
+ *
+ * Must be registered as meta-info at assembly time.
+ */
+// TODO javax.xml properties
+public class JavaxXmlSettings
+{
+ public static final JavaxXmlSettings DEFAULT = new JavaxXmlSettings();
+
+ public static JavaxXmlSettings orDefault( JavaxXmlSettings settings )
+ {
+ return settings != null ? settings : DEFAULT;
+ }
+
+ private String rootTagName;
+ private String collectionTagName;
+ private String collectionElementTagName;
+ private String mapTagName;
+ private String mapEntryTagName;
+ private String valueTagName;
+ private String typeInfoTagName;
+ private Map<ValueType, JavaxXmlAdapter<?>> adapters;
+
+ public JavaxXmlSettings()
+ {
+ rootTagName = "state";
+ collectionTagName = "collection";
+ collectionElementTagName = "element";
+ mapTagName = "map";
+ mapEntryTagName = "entry";
+ valueTagName = "value";
+ typeInfoTagName = "_type";
+ adapters = new LinkedHashMap<>();
+ }
+
+ public String getRootTagName()
+ {
+ return rootTagName;
+ }
+
+ public void setRootTagName( final String rootTagName )
+ {
+ this.rootTagName = rootTagName;
+ }
+
+ public String getCollectionTagName()
+ {
+ return collectionTagName;
+ }
+
+ public void setCollectionTagName( final String collectionTagName )
+ {
+ this.collectionTagName = collectionTagName;
+ }
+
+ public String getCollectionElementTagName()
+ {
+ return collectionElementTagName;
+ }
+
+ public void setCollectionElementTagName( final String collectionElementTagName )
+ {
+ this.collectionElementTagName = collectionElementTagName;
+ }
+
+ public String getMapTagName()
+ {
+ return mapTagName;
+ }
+
+ public void setMapTagName( final String mapTagName )
+ {
+ this.mapTagName = mapTagName;
+ }
+
+ public String getMapEntryTagName()
+ {
+ return mapEntryTagName;
+ }
+
+ public void setMapEntryTagName( final String mapEntryTagName )
+ {
+ this.mapEntryTagName = mapEntryTagName;
+ }
+
+ public String getValueTagName()
+ {
+ return valueTagName;
+ }
+
+ public void setValueTagName( final String valueTagName )
+ {
+ this.valueTagName = valueTagName;
+ }
+
+ public String getTypeInfoTagName()
+ {
+ return typeInfoTagName;
+ }
+
+ public void setTypeInfoTagName( final String typeInfoTagName )
+ {
+ this.typeInfoTagName = typeInfoTagName;
+ }
+
+ public Map<ValueType, JavaxXmlAdapter<?>> getAdapters()
+ {
+ return adapters;
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/package.html
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/package.html b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/package.html
new file mode 100644
index 0000000..f81a030
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/main/java/org/apache/polygene/serialization/javaxxml/package.html
@@ -0,0 +1,24 @@
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ ~
+ ~
+ -->
+<html>
+ <body>
+ <h2>javax.xml Serialization.</h2>
+ </body>
+</html>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlAdaptersTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlAdaptersTest.java b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlAdaptersTest.java
new file mode 100644
index 0000000..16a2fb3
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlAdaptersTest.java
@@ -0,0 +1,39 @@
+package org.apache.polygene.serialization.javaxxml;
+
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import org.apache.polygene.api.injection.scope.Service;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.test.AbstractPolygeneTest;
+import org.junit.Test;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertThat;
+
+public class JavaxXmlAdaptersTest extends AbstractPolygeneTest
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ new JavaxXmlSerializationAssembler().assemble( module );
+ module.services( JavaxXmlSerializationService.class )
+ .withTypes( JavaxXmlAdapters.class );
+ }
+
+ @Service
+ private JavaxXmlAdapters adapters;
+
+ @Test
+ public void test() throws ParserConfigurationException
+ {
+ JavaxXmlAdapter<String> adapter = adapters.adapterFor( String.class );
+ Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
+ String original = "Cou<cou>\u20ac���#\u2030��";
+ Node node = adapter.serialize( doc, original, null );
+ assertThat( node.getNodeValue(), equalTo( original ) );
+ String result = adapter.deserialize( node, null );
+ assertThat( result, equalTo( original ) );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlCollectionTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlCollectionTest.java b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlCollectionTest.java
new file mode 100644
index 0000000..5f0bf3c
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlCollectionTest.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxxml;
+
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.test.serialization.AbstractCollectionSerializationTest;
+
+public class JavaxXmlCollectionTest extends AbstractCollectionSerializationTest
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ new JavaxXmlSerializationAssembler().assemble( module );
+ super.assemble( module );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDateFormatTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDateFormatTest.java b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDateFormatTest.java
new file mode 100644
index 0000000..6f69bbe
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlDateFormatTest.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxxml;
+
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.test.serialization.AbstractDateFormatSerializationTest;
+import org.junit.Ignore;
+
+@Ignore( "Super test assume JSON" )
+public class JavaxXmlDateFormatTest extends AbstractDateFormatSerializationTest
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ new JavaxXmlSerializationAssembler().assemble( module );
+ super.assemble( module );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlPlainValueTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlPlainValueTest.java b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlPlainValueTest.java
new file mode 100644
index 0000000..51d8e8a
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlPlainValueTest.java
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.serialization.javaxxml;
+
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.test.serialization.AbstractPlainValueSerializationTest;
+import org.junit.Ignore;
+
+@Ignore( "Super test assume JSON" )
+public class JavaxXmlPlainValueTest extends AbstractPlainValueSerializationTest
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ new JavaxXmlSerializationAssembler().assemble( module );
+ super.assemble( module );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeTest.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeTest.java b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeTest.java
new file mode 100644
index 0000000..59d0e3e
--- /dev/null
+++ b/extensions/serialization-javaxxml/src/test/java/org/apache/polygene/serialization/javaxxml/JavaxXmlValueCompositeTest.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.javaxxml;
+
+import org.apache.polygene.api.injection.scope.Service;
+import org.apache.polygene.api.unitofwork.UnitOfWork;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.spi.serialization.XmlSerialization;
+import org.apache.polygene.test.serialization.AbstractValueCompositeSerializationTest;
+import org.junit.Test;
+import org.xmlunit.diff.DefaultNodeMatcher;
+import org.xmlunit.diff.ElementSelectors;
+
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertThat;
+import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
+
+public class JavaxXmlValueCompositeTest extends AbstractValueCompositeSerializationTest
+{
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ new JavaxXmlSerializationAssembler().assemble( module );
+ super.assemble( module );
+ }
+
+ @Service
+ XmlSerialization xmlSerialization;
+
+ @Test
+ public void valueCompositeXmlEquality()
+ {
+ try( UnitOfWork uow = unitOfWorkFactory.newUnitOfWork() )
+ {
+ Some some = buildSomeValue( moduleInstance, uow, "23" );
+
+ // Serialize using injected service
+ String stateString = serialization.serialize( some );
+ System.out.println( stateString );
+
+ // Deserialize using Module API
+ Some some2 = moduleInstance.newValueFromSerializedState( Some.class, stateString );
+
+ assertThat( "Value equality", some, equalTo( some2 ) );
+
+ // Need to loosely compare because of HashMaps not retaining order
+ assertThat( "XML equality",
+ stateString,
+ isSimilarTo( some2.toString() )
+ .withNodeMatcher( new DefaultNodeMatcher( ElementSelectors.byNameAndAllAttributes ) ) );
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-msgpack/build.gradle
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/build.gradle b/extensions/serialization-msgpack/build.gradle
new file mode 100644
index 0000000..6f51948
--- /dev/null
+++ b/extensions/serialization-msgpack/build.gradle
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+apply plugin: 'polygene-extension'
+
+description = "Apache Polygene\u2122 MessagePack Serialization Extension"
+
+jar { manifest { name = "Apache Polygene\u2122 Extension - Serialization - MessagePack" } }
+
+dependencies {
+ api polygene.core.bootstrap
+ api libraries.msgpack
+
+ implementation libraries.commons_lang
+
+ runtimeOnly polygene.core.runtime
+
+ testImplementation polygene.core.testsupport
+
+ testRuntimeOnly libraries.logback
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-msgpack/dev-status.xml
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/dev-status.xml b/extensions/serialization-msgpack/dev-status.xml
new file mode 100644
index 0000000..8086fb0
--- /dev/null
+++ b/extensions/serialization-msgpack/dev-status.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ ~
+ ~
+ -->
+<module xmlns="http://polygene.apache.org/schemas/2008/dev-status/1"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://polygene.apache.org/schemas/2008/dev-status/1
+ http://polygene.apache.org/schemas/2008/dev-status/1/dev-status.xsd">
+ <status>
+ <!--none,early,beta,stable,mature-->
+ <codebase>early</codebase>
+
+ <!-- none, brief, good, complete -->
+ <documentation>none</documentation>
+
+ <!-- none, some, good, complete -->
+ <unittests>some</unittests>
+ </status>
+ <licenses>
+ <license>ALv2</license>
+ </licenses>
+</module>
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-msgpack/src/docs/serialization-msgpack.txt
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/docs/serialization-msgpack.txt b/extensions/serialization-msgpack/src/docs/serialization-msgpack.txt
new file mode 100644
index 0000000..ad50c08
--- /dev/null
+++ b/extensions/serialization-msgpack/src/docs/serialization-msgpack.txt
@@ -0,0 +1,30 @@
+///////////////////////////////////////////////////////////////
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+///////////////////////////////////////////////////////////////
+
+[[extension-serialization-msgpack,MessagePack serialization]]
+= MessagePack serialization =
+
+[devstatus]
+--------------
+source=extensions/serialization-msgpack/dev-status.xml
+--------------
+
+// TODO Document usage of MessagePackSerialization
+// TODO Include sample model and its output from test code & resources
+// TODO Assembly - Serialization extension or sole Service, settings & adapters
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackAdapter.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackAdapter.java b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackAdapter.java
new file mode 100644
index 0000000..6d99e69
--- /dev/null
+++ b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackAdapter.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.msgpack;
+
+import java.io.IOException;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import org.apache.polygene.api.type.ValueType;
+import org.msgpack.value.Value;
+
+/**
+ * Adapter for MessagePack (de)serialization.
+ *
+ * @param <T> the adapted type
+ */
+public interface MessagePackAdapter<T>
+{
+ /**
+ * @return the adapted type
+ */
+ Class<T> type();
+
+ /**
+ * Serialize.
+ *
+ * @param object Object to serialize, never null
+ * @param serializeFunction Serialization function for nested structure serialization
+ * @return MessagePack Value
+ */
+ Value serialize( Object object, Function<Object, Value> serializeFunction )
+ throws IOException;
+
+ /**
+ * Deserialize.
+ *
+ * @param value MessagePack value
+ * @param deserializeFunction Deserialization function for nested structure deserialization
+ * @return Deserialized object
+ */
+ T deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ throws IOException;
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackAdapters.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackAdapters.java b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackAdapters.java
new file mode 100644
index 0000000..892b389
--- /dev/null
+++ b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackAdapters.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.msgpack;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.type.ValueType;
+
+import static org.apache.polygene.api.type.HasTypesCollectors.closestType;
+
+@Mixins( MessagePackAdapters.Mixin.class )
+public interface MessagePackAdapters
+{
+ void registerAdapter( ValueType valueType, MessagePackAdapter<?> adapter );
+
+ <T> MessagePackAdapter<T> adapterFor( ValueType valueType );
+
+ default <T> MessagePackAdapter<T> adapterFor( Class<T> type )
+ {
+ return adapterFor( ValueType.of( type ) );
+ }
+
+ class Mixin implements MessagePackAdapters
+ {
+ private Map<ValueType, MessagePackAdapter<?>> adapters = new LinkedHashMap<>();
+
+ @Override
+ public void registerAdapter( ValueType valueType, MessagePackAdapter<?> adapter )
+ {
+ adapters.put( valueType, adapter );
+ }
+
+ @Override
+ public <T> MessagePackAdapter<T> adapterFor( final ValueType valueType )
+ {
+ return castAdapter( adapters.keySet().stream()
+ .collect( closestType( valueType ) )
+ .map( adapters::get )
+ .orElse( null ) );
+ }
+
+ @SuppressWarnings( "unchecked" )
+ private <T> MessagePackAdapter<T> castAdapter( MessagePackAdapter<?> adapter )
+ {
+ return (MessagePackAdapter<T>) adapter;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
new file mode 100644
index 0000000..84508a4
--- /dev/null
+++ b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackDeserializer.java
@@ -0,0 +1,295 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.msgpack;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.util.AbstractMap;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Stream;
+import org.apache.polygene.api.association.AssociationDescriptor;
+import org.apache.polygene.api.entity.EntityReference;
+import org.apache.polygene.api.injection.scope.This;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.property.PropertyDescriptor;
+import org.apache.polygene.api.serialization.Deserializer;
+import org.apache.polygene.api.serialization.SerializationException;
+import org.apache.polygene.api.structure.ModuleDescriptor;
+import org.apache.polygene.api.type.CollectionType;
+import org.apache.polygene.api.type.EnumType;
+import org.apache.polygene.api.type.MapType;
+import org.apache.polygene.api.type.ValueCompositeType;
+import org.apache.polygene.api.type.ValueType;
+import org.apache.polygene.api.value.ValueBuilder;
+import org.apache.polygene.api.value.ValueDescriptor;
+import org.apache.polygene.spi.serialization.AbstractBinaryDeserializer;
+import org.msgpack.core.MessagePack;
+import org.msgpack.core.MessageUnpacker;
+import org.msgpack.value.ArrayValue;
+import org.msgpack.value.BinaryValue;
+import org.msgpack.value.ImmutableValue;
+import org.msgpack.value.MapValue;
+import org.msgpack.value.Value;
+
+import static java.util.Collections.unmodifiableList;
+import static java.util.Collections.unmodifiableMap;
+import static java.util.Collections.unmodifiableSet;
+import static org.apache.polygene.api.util.Collectors.toMap;
+
+// TODO Test all deserializations for: missing & spurious entries
+@Mixins( MessagePackDeserializer.Mixin.class )
+public interface MessagePackDeserializer extends Deserializer
+{
+ class Mixin extends AbstractBinaryDeserializer
+ {
+ @This
+ private MessagePackAdapters adapters;
+
+ @Override
+ public <T> T deserialize( ModuleDescriptor module, ValueType valueType, InputStream state )
+ {
+ MessageUnpacker unpacker = MessagePack.newDefaultUnpacker( state );
+ try
+ {
+ if( !unpacker.hasNext() )
+ {
+ return null;
+ }
+ ImmutableValue value = unpacker.unpackValue();
+ return doDeserialize( module, valueType, value );
+ }
+ catch( IOException e )
+ {
+ throw new SerializationException( "Unable to deserialize " + valueType );
+ }
+ }
+
+ @SuppressWarnings( "unchecked" )
+ private <T> T doDeserialize( ModuleDescriptor module, ValueType valueType, Value value )
+ {
+ try
+ {
+ if( value.isNilValue() )
+ {
+ return null;
+ }
+ MessagePackAdapter<?> adapter = adapters.adapterFor( valueType );
+ if( adapter != null )
+ {
+ return (T) adapter.deserialize( value, ( val, type ) -> doDeserialize( module, valueType, val ) );
+ }
+ if( EnumType.class.isAssignableFrom( valueType.getClass() ) )
+ {
+ return (T) Enum.valueOf( (Class) valueType.primaryType(), value.asStringValue().asString() );
+ }
+ if( CollectionType.class.isAssignableFrom( valueType.getClass() ) )
+ {
+ return (T) deserializeCollection( module, (CollectionType) valueType, value.asArrayValue() );
+ }
+ if( MapType.class.isAssignableFrom( valueType.getClass() ) )
+ {
+ return (T) deserializeMap( module, (MapType) valueType, value.asMapValue() );
+ }
+ if( ValueCompositeType.class.isAssignableFrom( valueType.getClass() ) )
+ {
+ return (T) deserializeValueComposite( module, (ValueCompositeType) valueType, value.asMapValue() );
+ }
+ return (T) doGuessDeserialize( module, valueType, value );
+ }
+ catch( IOException | ClassNotFoundException ex )
+ {
+ throw new SerializationException( "Unable to deserialize " + valueType + " from: " + value );
+ }
+ }
+
+ private Collection<?> deserializeCollection( ModuleDescriptor module, CollectionType collectionType,
+ ArrayValue value ) throws IOException
+ {
+ Collection<?> collection = collectionType.isSet() ? new LinkedHashSet( value.size() )
+ : new ArrayList( value.size() );
+ for( Value element : value.list() )
+ {
+ collection.add( doDeserialize( module, collectionType.collectedType(), element ) );
+ }
+ return collection;
+ }
+
+ private Map<Object, Object> deserializeMap( ModuleDescriptor module, MapType mapType, MapValue value )
+ throws IOException
+ {
+ Map<Object, Object> map = new LinkedHashMap<>( value.size() );
+ for( Map.Entry<Value, Value> entry : value.entrySet() )
+ {
+ Object key = doDeserialize( module, mapType.keyType(), entry.getKey() );
+ Object val = doDeserialize( module, mapType.valueType(), entry.getValue() );
+ map.put( key, val );
+ }
+ return map;
+ }
+
+ private Object deserializeValueComposite( ModuleDescriptor module, ValueCompositeType valueType,
+ MapValue value ) throws IOException
+ {
+ Map<String, Value> namedValues = value.map().entrySet().stream().map(
+ entry ->
+ {
+ String key = doDeserialize( module, ValueType.STRING, entry.getKey() );
+ return new AbstractMap.SimpleImmutableEntry<>( key, entry.getValue() );
+ }
+ ).collect( toMap( HashMap::new ) );
+
+ String typeInfo = null;
+ if( namedValues.containsKey( "_type" ) )
+ {
+ typeInfo = doDeserialize( module, ValueType.STRING, namedValues.get( "_type" ) );
+ }
+ if( typeInfo != null )
+ {
+ ValueDescriptor descriptor = module.valueDescriptor( typeInfo );
+ if( descriptor == null )
+ {
+ throw new SerializationException(
+ "_type: " + typeInfo + " could not be resolved while deserializing " + value );
+ }
+ valueType = descriptor.valueType();
+ }
+
+ ValueBuilder builder = module.instance().newValueBuilderWithState(
+ valueType.primaryType(),
+ propertyFunction( module, namedValues ),
+ associationFunction( module, namedValues ),
+ manyAssociationFunction( module, namedValues ),
+ namedAssociationFunction( module, namedValues ) );
+ return builder.newInstance();
+ }
+
+ private Function<PropertyDescriptor, Object> propertyFunction( ModuleDescriptor module,
+ Map<String, Value> namedValues )
+ {
+ return property ->
+ {
+ Value value = namedValues.get( property.qualifiedName().name() );
+ if( value != null )
+ {
+ Object propertyValue = doDeserialize( module, property.valueType(), value );
+ if( property.isImmutable() )
+ {
+ if( propertyValue instanceof Set )
+ {
+ return unmodifiableSet( (Set<?>) propertyValue );
+ }
+ else if( propertyValue instanceof List )
+ {
+ return unmodifiableList( (List<?>) propertyValue );
+ }
+ else if( propertyValue instanceof Map )
+ {
+ return unmodifiableMap( (Map<?, ?>) propertyValue );
+ }
+ }
+ return propertyValue;
+ }
+ return property.resolveInitialValue( module );
+ };
+ }
+
+ private Function<AssociationDescriptor, EntityReference> associationFunction( ModuleDescriptor module,
+ Map<String, Value> namedValues )
+ {
+ return association -> doDeserialize( module, ValueType.ENTITY_REFERENCE,
+ namedValues.get( association.qualifiedName().name() ) );
+ }
+
+ private Function<AssociationDescriptor, Stream<EntityReference>> manyAssociationFunction(
+ ModuleDescriptor module, Map<String, Value> namedValues )
+ {
+ return association ->
+ {
+ List list = doDeserialize( module, ENTITY_REF_LIST_VALUE_TYPE,
+ namedValues.get( association.qualifiedName().name() ) );
+ return list == null ? Stream.empty() : list.stream();
+ };
+ }
+
+ private Function<AssociationDescriptor, Stream<Map.Entry<String, EntityReference>>> namedAssociationFunction(
+ ModuleDescriptor module, Map<String, Value> namedValues )
+ {
+ return association ->
+ {
+ Map map = doDeserialize( module, ENTITY_REF_MAP_VALUE_TYPE,
+ namedValues.get( association.qualifiedName().name() ) );
+ return map == null ? Stream.empty() : map.entrySet().stream();
+ };
+ }
+
+ private Object doGuessDeserialize( ModuleDescriptor module, ValueType valueType, Value value )
+ throws IOException, ClassNotFoundException
+ {
+ switch( value.getValueType() )
+ {
+ case BINARY:
+ return deserializeJava( value.asBinaryValue() );
+ case MAP:
+ MapValue mapValue = value.asMapValue();
+ Optional<String> typeInfo = mapValue
+ .entrySet().stream()
+ .filter( entry -> entry.getKey().isStringValue() )
+ .map( entry ->
+ {
+ String key = doDeserialize( module, ValueType.STRING, entry.getKey() );
+ return new AbstractMap.SimpleImmutableEntry<>( key, entry.getValue() );
+ } )
+ .filter( entry -> "_type".equals( entry.getKey() ) )
+ .findFirst()
+ .map( entry -> doDeserialize( module, ValueType.STRING, entry.getValue() ) );
+ if( typeInfo.isPresent() )
+ {
+ ValueDescriptor valueDescriptor = module.valueDescriptor( typeInfo.get() );
+ if( valueDescriptor != null )
+ {
+ return deserializeValueComposite( module, valueDescriptor.valueType(), mapValue );
+ }
+ }
+ default:
+ throw new SerializationException( "Don't know how to deserialize " + valueType + " from " + value
+ + " (" + value.getValueType() + ")" );
+ }
+ }
+
+ private Object deserializeJava( BinaryValue value )
+ throws IOException, ClassNotFoundException
+ {
+ byte[] bytes = value.asByteArray();
+ try( ObjectInputStream oin = new ObjectInputStream( new ByteArrayInputStream( bytes ) ) )
+ {
+ return oin.readObject();
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerialization.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerialization.java b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerialization.java
new file mode 100644
index 0000000..d24d597
--- /dev/null
+++ b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerialization.java
@@ -0,0 +1,22 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.msgpack;
+
+public interface MessagePackSerialization extends MessagePackSerializer, MessagePackDeserializer
+{
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializationAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializationAssembler.java b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializationAssembler.java
new file mode 100644
index 0000000..63536cc
--- /dev/null
+++ b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializationAssembler.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.msgpack;
+
+import org.apache.polygene.api.serialization.Deserializer;
+import org.apache.polygene.api.serialization.Serialization;
+import org.apache.polygene.api.serialization.Serializer;
+import org.apache.polygene.bootstrap.Assemblers;
+import org.apache.polygene.bootstrap.ModuleAssembly;
+import org.apache.polygene.bootstrap.ServiceDeclaration;
+
+public class MessagePackSerializationAssembler extends Assemblers.VisibilityIdentity<MessagePackSerializationAssembler>
+{
+ private MessagePackSettings settings;
+
+ public MessagePackSerializationAssembler withMessagePackSettings( MessagePackSettings settings )
+ {
+ this.settings = settings;
+ return this;
+ }
+
+ @Override
+ public void assemble( ModuleAssembly module )
+ {
+ ServiceDeclaration declaration = module.services( MessagePackSerializationService.class )
+ .withTypes( Serialization.class, Serializer.class, Deserializer.class )
+ .visibleIn( visibility() );
+ if( hasIdentity() )
+ {
+ declaration.identifiedBy( identity() );
+ }
+ if( settings != null )
+ {
+ declaration.setMetaInfo( settings );
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializationService.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializationService.java b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializationService.java
new file mode 100644
index 0000000..4cd23b7
--- /dev/null
+++ b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializationService.java
@@ -0,0 +1,414 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.msgpack;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.OffsetDateTime;
+import java.time.Period;
+import java.time.ZonedDateTime;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import org.apache.polygene.api.entity.EntityReference;
+import org.apache.polygene.api.identity.Identity;
+import org.apache.polygene.api.identity.StringIdentity;
+import org.apache.polygene.api.injection.scope.This;
+import org.apache.polygene.api.injection.scope.Uses;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.service.ServiceActivation;
+import org.apache.polygene.api.service.ServiceDescriptor;
+import org.apache.polygene.api.type.ValueType;
+import org.msgpack.value.Value;
+import org.msgpack.value.ValueFactory;
+
+@Mixins( MessagePackSerializationService.Activation.class )
+public interface MessagePackSerializationService extends MessagePackSerialization, ServiceActivation
+{
+ class Activation implements ServiceActivation
+ {
+ @Uses
+ private ServiceDescriptor descriptor;
+
+ @This
+ private MessagePackAdapters adapters;
+
+ private boolean registrationDone = false;
+
+ @Override
+ public void activateService()
+ {
+ if( !registrationDone )
+ {
+ registerCustomAdapters();
+ registerBaseAdapters();
+ registrationDone = true;
+ }
+ }
+
+ @Override
+ public void passivateService() {}
+
+ private void registerCustomAdapters()
+ {
+ MessagePackSettings.orDefault( descriptor.metaInfo( MessagePackSettings.class ) )
+ .getAdapters()
+ .forEach( ( valueType, adapter ) -> adapters.registerAdapter( valueType, adapter ) );
+ }
+
+ private void registerBaseAdapters()
+ {
+ // Primitive Value types
+ adapters.registerAdapter( ValueType.STRING, new StringAdapter() );
+ adapters.registerAdapter( ValueType.CHARACTER, new CharacterAdapter() );
+ adapters.registerAdapter( ValueType.BOOLEAN, new BooleanAdapter() );
+ adapters.registerAdapter( ValueType.INTEGER, new IntegerAdapter() );
+ adapters.registerAdapter( ValueType.LONG, new LongAdapter() );
+ adapters.registerAdapter( ValueType.SHORT, new ShortAdapter() );
+ adapters.registerAdapter( ValueType.BYTE, new ByteAdapter() );
+ adapters.registerAdapter( ValueType.FLOAT, new FloatAdapter() );
+ adapters.registerAdapter( ValueType.DOUBLE, new DoubleAdapter() );
+
+ // Number types
+ adapters.registerAdapter( ValueType.BIG_DECIMAL, new BigDecimalAdapter() );
+ adapters.registerAdapter( ValueType.BIG_INTEGER, new BigIntegerAdapter() );
+
+ // Date types
+ adapters.registerAdapter( ValueType.INSTANT, new InstantAdapter() );
+ adapters.registerAdapter( ValueType.ZONED_DATE_TIME, new ZonedDateTimeAdapter() );
+ adapters.registerAdapter( ValueType.OFFSET_DATE_TIME, new OffsetDateTimeAdapter() );
+ adapters.registerAdapter( ValueType.LOCAL_DATE_TIME, new LocalDateTimeAdapter() );
+ adapters.registerAdapter( ValueType.LOCAL_DATE, new LocalDateAdapter() );
+ adapters.registerAdapter( ValueType.LOCAL_TIME, new LocalTimeAdapter() );
+ adapters.registerAdapter( ValueType.DURATION, new DurationAdapter() );
+ adapters.registerAdapter( ValueType.PERIOD, new PeriodAdapter() );
+
+ // Other supported types
+ adapters.registerAdapter( ValueType.IDENTITY, new IdentityAdapter() );
+ adapters.registerAdapter( ValueType.ENTITY_REFERENCE, new EntityReferenceAdapter() );
+ }
+
+ private static abstract class ToStringAdapter<T> implements MessagePackAdapter<T>
+ {
+ @Override
+ public Value serialize( Object object, Function<Object, Value> serializeFunction )
+ {
+ return ValueFactory.newString( object.toString() );
+ }
+ }
+
+ private static class StringAdapter extends ToStringAdapter<String>
+ {
+ @Override
+ public Class<String> type() { return String.class; }
+
+ @Override
+ public String deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return value.asStringValue().asString();
+ }
+ }
+
+ private static class CharacterAdapter extends ToStringAdapter<Character>
+ {
+ @Override
+ public Class<Character> type() { return Character.class; }
+
+ @Override
+ public Character deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ String string = value.asStringValue().asString();
+ return string.isEmpty() ? null : string.charAt( 0 );
+ }
+ }
+
+ private static class BooleanAdapter implements MessagePackAdapter<Boolean>
+ {
+ @Override
+ public Class<Boolean> type() { return Boolean.class; }
+
+ @Override
+ public Value serialize( Object object, Function<Object, Value> serializeFunction )
+ {
+ return ValueFactory.newBoolean( (Boolean) object );
+ }
+
+ @Override
+ public Boolean deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return value.asBooleanValue().getBoolean();
+ }
+ }
+
+ private static class IntegerAdapter implements MessagePackAdapter<Integer>
+ {
+ @Override
+ public Class<Integer> type() { return Integer.class; }
+
+ @Override
+ public Value serialize( Object object, Function<Object, Value> serializeFunction )
+ {
+ return ValueFactory.newInteger( (Integer) object );
+ }
+
+ @Override
+ public Integer deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return value.asIntegerValue().asInt();
+ }
+ }
+
+ private static class LongAdapter implements MessagePackAdapter<Long>
+ {
+ @Override
+ public Class<Long> type() { return Long.class; }
+
+ @Override
+ public Value serialize( Object object, Function<Object, Value> serializeFunction )
+ {
+ return ValueFactory.newInteger( (Long) object );
+ }
+
+ @Override
+ public Long deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return value.asIntegerValue().asLong();
+ }
+ }
+
+ private static class ShortAdapter implements MessagePackAdapter<Short>
+ {
+ @Override
+ public Class<Short> type() { return Short.class; }
+
+ @Override
+ public Value serialize( Object object, Function<Object, Value> serializeFunction )
+ {
+ return ValueFactory.newInteger( (Short) object );
+ }
+
+ @Override
+ public Short deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return value.asIntegerValue().asShort();
+ }
+ }
+
+ private static class ByteAdapter implements MessagePackAdapter<Byte>
+ {
+ @Override
+ public Class<Byte> type() { return Byte.class; }
+
+ @Override
+ public Value serialize( Object object, Function<Object, Value> serializeFunction )
+ {
+ return ValueFactory.newInteger( (Byte) object );
+ }
+
+ @Override
+ public Byte deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return value.asIntegerValue().asByte();
+ }
+ }
+
+ private static class FloatAdapter implements MessagePackAdapter<Float>
+ {
+ @Override
+ public Class<Float> type() { return Float.class; }
+
+ @Override
+ public Value serialize( Object object, Function<Object, Value> serializeFunction )
+ {
+ return ValueFactory.newFloat( (Float) object );
+ }
+
+ @Override
+ public Float deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return value.asFloatValue().toFloat();
+ }
+ }
+
+ private static class DoubleAdapter implements MessagePackAdapter<Double>
+ {
+ @Override
+ public Class<Double> type() { return Double.class; }
+
+ @Override
+ public Value serialize( Object object, Function<Object, Value> serializeFunction )
+ {
+ return ValueFactory.newFloat( (Double) object );
+ }
+
+ @Override
+ public Double deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return value.asFloatValue().toDouble();
+ }
+ }
+
+ private static class BigDecimalAdapter extends ToStringAdapter<BigDecimal>
+ {
+ @Override
+ public Class<BigDecimal> type() { return BigDecimal.class; }
+
+ @Override
+ public BigDecimal deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return new BigDecimal( value.asStringValue().asString() );
+ }
+ }
+
+ private static class BigIntegerAdapter extends ToStringAdapter<BigInteger>
+ {
+ @Override
+ public Class<BigInteger> type() { return BigInteger.class; }
+
+ @Override
+ public BigInteger deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return new BigInteger( value.asStringValue().asString() );
+ }
+ }
+
+ private static class InstantAdapter extends ToStringAdapter<Instant>
+ {
+ @Override
+ public Class<Instant> type() { return Instant.class; }
+
+ @Override
+ public Instant deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return Instant.parse( value.asStringValue().asString() );
+ }
+ }
+
+ private static class ZonedDateTimeAdapter extends ToStringAdapter<ZonedDateTime>
+ {
+ @Override
+ public Class<ZonedDateTime> type() { return ZonedDateTime.class; }
+
+ @Override
+ public ZonedDateTime deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return ZonedDateTime.parse( value.asStringValue().asString() );
+ }
+ }
+
+ private static class OffsetDateTimeAdapter extends ToStringAdapter<OffsetDateTime>
+ {
+ @Override
+ public Class<OffsetDateTime> type() { return OffsetDateTime.class; }
+
+ @Override
+ public OffsetDateTime deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return OffsetDateTime.parse( value.asStringValue().asString() );
+ }
+ }
+
+ private static class LocalDateTimeAdapter extends ToStringAdapter<LocalDateTime>
+ {
+ @Override
+ public Class<LocalDateTime> type() { return LocalDateTime.class; }
+
+ @Override
+ public LocalDateTime deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return LocalDateTime.parse( value.asStringValue().asString() );
+ }
+ }
+
+ private static class LocalDateAdapter extends ToStringAdapter<LocalDate>
+ {
+ @Override
+ public Class<LocalDate> type() { return LocalDate.class; }
+
+ @Override
+ public LocalDate deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return LocalDate.parse( value.asStringValue().asString() );
+ }
+ }
+
+ private static class LocalTimeAdapter extends ToStringAdapter<LocalTime>
+ {
+ @Override
+ public Class<LocalTime> type() { return LocalTime.class; }
+
+ @Override
+ public LocalTime deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return LocalTime.parse( value.asStringValue().asString() );
+ }
+ }
+
+ private static class DurationAdapter extends ToStringAdapter<Duration>
+ {
+ @Override
+ public Class<Duration> type() { return Duration.class; }
+
+ @Override
+ public Duration deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return Duration.parse( value.asStringValue().asString() );
+ }
+ }
+
+ private static class PeriodAdapter extends ToStringAdapter<Period>
+ {
+ @Override
+ public Class<Period> type() { return Period.class; }
+
+ @Override
+ public Period deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return Period.parse( value.asStringValue().asString() );
+ }
+ }
+
+ private static class IdentityAdapter extends ToStringAdapter<Identity>
+ {
+ @Override
+ public Class<Identity> type() { return Identity.class; }
+
+ @Override
+ public Identity deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return StringIdentity.fromString( value.asStringValue().asString() );
+ }
+ }
+
+ private static class EntityReferenceAdapter extends ToStringAdapter<EntityReference>
+ {
+ @Override
+ public Class<EntityReference> type() { return EntityReference.class; }
+
+ @Override
+ public EntityReference deserialize( Value value, BiFunction<Value, ValueType, Object> deserializeFunction )
+ {
+ return EntityReference.parseEntityReference( value.asStringValue().asString() );
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java
new file mode 100644
index 0000000..7321e6d
--- /dev/null
+++ b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSerializer.java
@@ -0,0 +1,187 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.msgpack;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
+import java.util.Map;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+import org.apache.polygene.api.PolygeneAPI;
+import org.apache.polygene.api.association.AssociationStateHolder;
+import org.apache.polygene.api.common.Optional;
+import org.apache.polygene.api.composite.CompositeInstance;
+import org.apache.polygene.api.injection.scope.This;
+import org.apache.polygene.api.mixin.Mixins;
+import org.apache.polygene.api.serialization.SerializationException;
+import org.apache.polygene.api.serialization.Serializer;
+import org.apache.polygene.api.type.EnumType;
+import org.apache.polygene.api.type.MapType;
+import org.apache.polygene.api.type.ValueCompositeType;
+import org.apache.polygene.api.value.ValueComposite;
+import org.apache.polygene.api.value.ValueDescriptor;
+import org.apache.polygene.spi.serialization.AbstractBinarySerializer;
+import org.msgpack.core.MessagePack;
+import org.msgpack.core.MessagePacker;
+import org.msgpack.value.ArrayValue;
+import org.msgpack.value.BinaryValue;
+import org.msgpack.value.MapValue;
+import org.msgpack.value.Value;
+import org.msgpack.value.ValueFactory;
+
+import static java.util.stream.Collectors.toList;
+import static org.apache.polygene.api.util.Collectors.toMap;
+
+@Mixins( MessagePackSerializer.Mixin.class )
+public interface MessagePackSerializer extends Serializer
+{
+ class Mixin extends AbstractBinarySerializer
+ {
+ @This
+ private MessagePackAdapters adapters;
+
+ @Override
+ public void serialize( Options options, OutputStream output, @Optional Object object )
+ {
+ MessagePacker packer = MessagePack.newDefaultPacker( output );
+ Value value = doSerialize( options, object, true );
+ try
+ {
+ packer.packValue( value );
+ packer.flush();
+ }
+ catch( IOException ex )
+ {
+ throw new SerializationException( "Unable to serialize " + object, ex );
+ }
+ }
+
+ private Value doSerialize( Options options, Object object, boolean root )
+ {
+ try
+ {
+ if( object == null )
+ {
+ return ValueFactory.newNil();
+ }
+ Class<?> objectClass = object.getClass();
+ MessagePackAdapter<?> adapter = adapters.adapterFor( objectClass );
+ if( adapter != null )
+ {
+ return adapter.serialize( object, obj -> doSerialize( options, obj, false ) );
+ }
+ if( EnumType.isEnum( objectClass ) )
+ {
+ return ValueFactory.newString( object.toString() );
+ }
+ if( ValueCompositeType.isValueComposite( objectClass ) )
+ {
+ return serializeValueComposite( options, object, root );
+ }
+ if( MapType.isMap( objectClass ) )
+ {
+ return serializeMap( options, (Map<?, ?>) object );
+ }
+ if( Iterable.class.isAssignableFrom( objectClass ) )
+ {
+ return serializeIterable( options, (Iterable<?>) object );
+ }
+ if( Stream.class.isAssignableFrom( objectClass ) )
+ {
+ return serializeStream( options, (Stream<?>) object );
+ }
+ // Fallback to Java Serialization
+ // Include all arrays!
+ return serializeJava( object );
+ }
+ catch( IOException ex )
+ {
+ throw new SerializationException( "Unable to serialize " + object, ex );
+ }
+ }
+
+ private MapValue serializeValueComposite( Options options, Object composite, boolean root )
+ {
+ CompositeInstance instance = PolygeneAPI.FUNCTION_COMPOSITE_INSTANCE_OF.apply( (ValueComposite) composite );
+ ValueDescriptor descriptor = (ValueDescriptor) instance.descriptor();
+ AssociationStateHolder state = (AssociationStateHolder) instance.state();
+ ValueCompositeType valueType = descriptor.valueType();
+
+ ValueFactory.MapBuilder builder = ValueFactory.newMapBuilder();
+ valueType.properties().forEach(
+ property -> builder.put(
+ ValueFactory.newString( property.qualifiedName().name() ),
+ doSerialize( options, state.propertyFor( property.accessor() ).get(), false ) ) );
+ valueType.associations().forEach(
+ association -> builder.put(
+ ValueFactory.newString( association.qualifiedName().name() ),
+ doSerialize( options, state.associationFor( association.accessor() ).reference(), false ) ) );
+ valueType.manyAssociations().forEach(
+ association -> builder.put(
+ ValueFactory.newString( association.qualifiedName().name() ),
+ doSerialize( options,
+ state.manyAssociationFor( association.accessor() ).references().collect( toList() ),
+ false ) ) );
+ valueType.namedAssociations().forEach(
+ association -> builder.put(
+ ValueFactory.newString( association.qualifiedName().name() ),
+ doSerialize( options,
+ state.namedAssociationFor( association.accessor() ).references().collect( toMap() ),
+ false ) ) );
+
+ if( !root && options.includeTypeInfo() )
+ {
+ builder.put( ValueFactory.newString( "_type" ),
+ ValueFactory.newString( valueType.primaryType().getName() ) );
+ }
+ return builder.build();
+ }
+
+ private MapValue serializeMap( Options options, Map<?, ?> map )
+ {
+ ValueFactory.MapBuilder builder = ValueFactory.newMapBuilder();
+ map.forEach( ( key, value ) -> builder.put( doSerialize( options, key, false ),
+ doSerialize( options, value, false ) ) );
+ return builder.build();
+ }
+
+ private ArrayValue serializeIterable( Options options, Iterable<?> iterable )
+ {
+ return serializeStream( options, StreamSupport.stream( iterable.spliterator(), false ) );
+ }
+
+ private ArrayValue serializeStream( Options options, Stream<?> stream )
+ {
+ return ValueFactory.newArray( stream.map( element -> doSerialize( options, element, false ) )
+ .collect( toList() ) );
+ }
+
+ private BinaryValue serializeJava( Object object ) throws IOException
+ {
+ ByteArrayOutputStream bout = new ByteArrayOutputStream();
+ try( ObjectOutputStream out = new ObjectOutputStream( bout ) )
+ {
+ out.writeUnshared( object );
+ byte[] bytes = bout.toByteArray();
+ return ValueFactory.newBinary( bytes );
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/c9dd7229/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSettings.java
----------------------------------------------------------------------
diff --git a/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSettings.java b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSettings.java
new file mode 100644
index 0000000..8080d94
--- /dev/null
+++ b/extensions/serialization-msgpack/src/main/java/org/apache/polygene/serialization/msgpack/MessagePackSettings.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.polygene.serialization.msgpack;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.apache.polygene.api.type.ValueType;
+
+public class MessagePackSettings
+{
+ public static final MessagePackSettings DEFAULT = new MessagePackSettings();
+
+ public static MessagePackSettings orDefault( MessagePackSettings settings )
+ {
+ return settings != null ? settings : DEFAULT;
+ }
+
+ private Map<ValueType, MessagePackAdapter<?>> adapters;
+
+ public MessagePackSettings()
+ {
+ adapters = new LinkedHashMap<>();
+ }
+
+ public Map<ValueType, MessagePackAdapter<?>> getAdapters()
+ {
+ return adapters;
+ }
+}
[40/50] [abbrv] polygene-java git commit: POLYGENE-153 Fix SQL
library tests
Posted by pa...@apache.org.
POLYGENE-153 Fix SQL library tests
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/264e7043
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/264e7043
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/264e7043
Branch: refs/heads/serialization-3.0
Commit: 264e70438a108bca1ca6f4d328c0536834d683d0
Parents: afd1946
Author: Paul Merlin <pa...@apache.org>
Authored: Mon Feb 27 15:35:05 2017 +0100
Committer: Paul Merlin <pa...@apache.org>
Committed: Mon Mar 13 11:24:42 2017 +0100
----------------------------------------------------------------------
.../sql/jmx/DataSourceConfigurationManagerServiceTest.java | 3 +++
1 file changed, 3 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/264e7043/libraries/sql/src/test/java/org/apache/polygene/library/sql/jmx/DataSourceConfigurationManagerServiceTest.java
----------------------------------------------------------------------
diff --git a/libraries/sql/src/test/java/org/apache/polygene/library/sql/jmx/DataSourceConfigurationManagerServiceTest.java b/libraries/sql/src/test/java/org/apache/polygene/library/sql/jmx/DataSourceConfigurationManagerServiceTest.java
index fc2a922..882df7a 100644
--- a/libraries/sql/src/test/java/org/apache/polygene/library/sql/jmx/DataSourceConfigurationManagerServiceTest.java
+++ b/libraries/sql/src/test/java/org/apache/polygene/library/sql/jmx/DataSourceConfigurationManagerServiceTest.java
@@ -82,6 +82,7 @@ public class DataSourceConfigurationManagerServiceTest
// Set up DataSource service that will manage the connection pools
new DBCPDataSourceServiceAssembler().identifiedBy( "datasource-service" )
.visibleIn( Visibility.layer )
+ .withConfig( module, Visibility.layer )
.assemble( module );
{
@@ -96,6 +97,7 @@ public class DataSourceConfigurationManagerServiceTest
// Set up Liquibase service that will create the tables
new LiquibaseAssembler().identifiedBy( "liquibase1" )
+ .withConfig( testModule, Visibility.module )
.applyChangelogOnStartup()
.assemble( testModule );
testModule.forMixin( LiquibaseConfiguration.class ).declareDefaults()
@@ -115,6 +117,7 @@ public class DataSourceConfigurationManagerServiceTest
// Set up Liquibase service that will create the tables
new LiquibaseAssembler().identifiedBy( "liquibase2" )
+ .withConfig( testModule2, Visibility.module )
.applyChangelogOnStartup()
.assemble( testModule2 );
testModule2.forMixin( LiquibaseConfiguration.class ).declareDefaults()
[15/50] [abbrv] polygene-java git commit: Syntax errors in templates
fixed.
Posted by pa...@apache.org.
Syntax errors in templates fixed.
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/70eeb7e2
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/70eeb7e2
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/70eeb7e2
Branch: refs/heads/serialization-3.0
Commit: 70eeb7e2e88aa0309c4a609c93b44c40a5e2e5e3
Parents: f8f5c5c
Author: niclas <ni...@spicter.com>
Authored: Sun Mar 12 12:05:50 2017 +0800
Committer: niclas <ni...@spicter.com>
Committed: Sun Mar 12 12:05:50 2017 +0800
----------------------------------------------------------------------
.../app/templates/DomainLayer/SecurityModule/Group.tmpl | 2 +-
.../app/templates/DomainLayer/SecurityModule/RealmService.tmpl | 1 +
.../app/templates/DomainLayer/SecurityModule/User.tmpl | 2 +-
3 files changed, 3 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/70eeb7e2/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/Group.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/Group.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/Group.tmpl
index eb83232..8e0aba8 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/Group.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/Group.tmpl
@@ -19,7 +19,7 @@
-%>
package <%= packageName %>.model.security;
-import org.apache.polygene.api.injection.scope.This
+import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.property.Property;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/70eeb7e2/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/RealmService.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/RealmService.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/RealmService.tmpl
index d009a21..875f35b 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/RealmService.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/RealmService.tmpl
@@ -46,3 +46,4 @@ public interface RealmService
addAccount( "foo", passwordService.encryptPassword( "bar" ) );
}
}
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/70eeb7e2/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/User.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/User.tmpl b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/User.tmpl
index f5008cd..32f2db1 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/User.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/SecurityModule/User.tmpl
@@ -19,7 +19,7 @@
-%>
package <%= packageName %>.model.security;
-import org.apache.polygene.api.injection.scope.This
+import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.property.Property;
[14/50] [abbrv] polygene-java git commit: Accidentally committed
yeoman generator as a subproject. Removing that.
Posted by pa...@apache.org.
Accidentally committed yeoman generator as a subproject. Removing that.
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/f8f5c5c2
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/f8f5c5c2
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/f8f5c5c2
Branch: refs/heads/serialization-3.0
Commit: f8f5c5c26d345e4838bbce981d3e2b8acbb0750f
Parents: 1ec0faa
Author: niclas <ni...@spicter.com>
Authored: Sun Mar 12 00:05:41 2017 +0800
Committer: niclas <ni...@spicter.com>
Committed: Sun Mar 12 00:05:41 2017 +0800
----------------------------------------------------------------------
settings.gradle | 2 +-
tools/generator-polygene/build.gradle | 68 ------------------------------
2 files changed, 1 insertion(+), 69 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/f8f5c5c2/settings.gradle
----------------------------------------------------------------------
diff --git a/settings.gradle b/settings.gradle
index 5b9c045..f33d3eb 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -81,7 +81,7 @@ include 'core:api',
'extensions:valueserialization-stax',
'tools:model-detail',
'tools:envisage',
- 'tools:generator-polygene',
+// 'tools:generator-polygene',
// 'tools:qidea',
'tests:regression',
'tests:performance',
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/f8f5c5c2/tools/generator-polygene/build.gradle
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/build.gradle b/tools/generator-polygene/build.gradle
deleted file mode 100644
index 64bd9f0..0000000
--- a/tools/generator-polygene/build.gradle
+++ /dev/null
@@ -1,68 +0,0 @@
-def allEntityStores = [
- 'Cassandra',
- 'File',
- 'DerbySQL',
- 'Geode',
- 'H2SQL',
- 'Hazelcast',
- 'JClouds',
- 'Jdbm',
- 'LevelDB',
- 'Memory',
- 'MongoDB',
- 'MySQL',
- 'Preferences',
- 'Redis',
- 'Riak',
- 'PostgresSQL',
- 'SQLite'
-]
-
-def allIndexing = [
- "Rdf",
- "ElasticSearch",
- "Solr",
- "SQL"
-]
-
-def allCaching = [
- "None",
- "EhCache",
- "Memcache"
-]
-
-def allMetrics = [
- "None",
- "Codahale"
-]
-
-def allValueSerialization = [
- "Jackson",
- "Stax"
-]
-
-def featureCombinations(array, result) {
- if (array?.empty) {
- return []
- }
- return [array, featureCombinations(array.tail())]
-}
-
-def allFeatures = [
- 'rest api',
- 'jmx',
- 'security'
-].forEach( {
-
-});
-
-def allFeatureCombos = [
-
-]
-
-def allCombos = [
-
-]
-
-println allFeatures
-
[08/50] [abbrv] polygene-java git commit: Cleaning up in Yeoman
generator. Generate nicer output. Fixed RdfIndexing to use
VisibilityConfigIdentity assembler system,
and follow Yeoman generator naming conventions.
Posted by pa...@apache.org.
Cleaning up in Yeoman generator. Generate nicer output.
Fixed RdfIndexing to use VisibilityConfigIdentity assembler system, and follow Yeoman generator naming conventions.
Project: http://git-wip-us.apache.org/repos/asf/polygene-java/repo
Commit: http://git-wip-us.apache.org/repos/asf/polygene-java/commit/14298086
Tree: http://git-wip-us.apache.org/repos/asf/polygene-java/tree/14298086
Diff: http://git-wip-us.apache.org/repos/asf/polygene-java/diff/14298086
Branch: refs/heads/serialization-3.0
Commit: 142980867d950f46dce1730de91d7315ac8d19e3
Parents: a2736a6
Author: niclas <ni...@spicter.com>
Authored: Sat Mar 11 19:41:48 2017 +0800
Committer: niclas <ni...@spicter.com>
Committed: Sat Mar 11 19:41:48 2017 +0800
----------------------------------------------------------------------
.../ESFilesystemIndexQueryAssembler.java | 3 -
.../assembly/AbstractRdfIndexingAssembler.java | 31 +++++
.../rdf/assembly/RdfIndexingAssembler.java | 28 +++++
.../rdf/assembly/RdfMemoryStoreAssembler.java | 19 +--
.../assembly/RdfNativeSesameStoreAssembler.java | 27 +++--
.../assembly/RdfRdbmsSesameStoreAssembler.java | 22 ++--
tools/generator-polygene/app/index.js | 120 +++++++++++++------
.../DomainLayer/DomainModule/Configuration.tmpl | 9 +-
.../DomainLayer/DomainModule/Crud.tmpl | 8 +-
.../DomainLayer/DomainModule/Entity.tmpl | 8 +-
.../DomainLayer/DomainModule/Value.tmpl | 8 +-
.../DomainLayer/DomainModule/config.yaml.tmpl | 23 ++++
.../DomainLayer/DomainModule/module.js | 17 ++-
.../IndexingModule/bootstrap.tmpl | 2 +-
.../StorageModule/bootstrap.tmpl | 2 +-
15 files changed, 235 insertions(+), 92 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/14298086/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESFilesystemIndexQueryAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESFilesystemIndexQueryAssembler.java b/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESFilesystemIndexQueryAssembler.java
index 6b529ca..015e2b0 100644
--- a/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESFilesystemIndexQueryAssembler.java
+++ b/extensions/indexing-elasticsearch/src/main/java/org/apache/polygene/index/elasticsearch/assembly/ESFilesystemIndexQueryAssembler.java
@@ -40,9 +40,6 @@ public class ESFilesystemIndexQueryAssembler
.visibleIn( visibility() )
.instantiateOnStartup();
- module.services( OrgJsonValueSerializationService.class ).
- taggedWith( ValueSerialization.Formats.JSON );
-
if( hasConfig() )
{
configModule().entities( ElasticSearchConfiguration.class ).
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/14298086/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/AbstractRdfIndexingAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/AbstractRdfIndexingAssembler.java b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/AbstractRdfIndexingAssembler.java
new file mode 100644
index 0000000..b67899e
--- /dev/null
+++ b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/AbstractRdfIndexingAssembler.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.index.rdf.assembly;
+
+import org.apache.polygene.bootstrap.Assemblers;
+
+public abstract class AbstractRdfIndexingAssembler<AssemblerType>
+ extends Assemblers.VisibilityIdentityConfig<AssemblerType>
+{
+ public AbstractRdfIndexingAssembler()
+ {
+ identifiedBy( "rdf-indexing" );
+ }
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/14298086/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfIndexingAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfIndexingAssembler.java b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfIndexingAssembler.java
new file mode 100644
index 0000000..fff60a6
--- /dev/null
+++ b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfIndexingAssembler.java
@@ -0,0 +1,28 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+ */
+package org.apache.polygene.index.rdf.assembly;
+
+/**
+ * This is a dummy Assembler to support the Yeoman Polygene Generator, which require naming conventions for
+ * the systems that it supports.
+ */
+public class RdfIndexingAssembler extends RdfNativeSesameStoreAssembler
+{
+}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/14298086/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfMemoryStoreAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfMemoryStoreAssembler.java b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfMemoryStoreAssembler.java
index be584c4..b4738db 100644
--- a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfMemoryStoreAssembler.java
+++ b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfMemoryStoreAssembler.java
@@ -21,8 +21,6 @@
package org.apache.polygene.index.rdf.assembly;
import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.bootstrap.Assembler;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.index.rdf.RdfIndexingEngineService;
@@ -30,23 +28,20 @@ import org.apache.polygene.index.rdf.query.RdfQueryParserFactory;
import org.apache.polygene.library.rdf.entity.EntityStateSerializer;
import org.apache.polygene.library.rdf.entity.EntityTypeSerializer;
import org.apache.polygene.library.rdf.repository.MemoryRepositoryService;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
-public class RdfMemoryStoreAssembler
- implements Assembler
+public class RdfMemoryStoreAssembler extends AbstractRdfIndexingAssembler<RdfNativeSesameStoreAssembler>
{
- private Visibility indexingVisibility;
private Visibility repositoryVisibility;
public RdfMemoryStoreAssembler()
{
- this( Visibility.application, Visibility.module );
+ this(Visibility.application, Visibility.module);
}
public RdfMemoryStoreAssembler( Visibility indexingVisibility, Visibility repositoryVisibility )
{
- this.indexingVisibility = indexingVisibility;
this.repositoryVisibility = repositoryVisibility;
+ visibleIn( indexingVisibility );
}
@Override
@@ -55,14 +50,12 @@ public class RdfMemoryStoreAssembler
{
module.services( MemoryRepositoryService.class )
.visibleIn( repositoryVisibility )
- .instantiateOnStartup()
- .identifiedBy( "rdf-repository" );
+ .instantiateOnStartup();
module.services( RdfIndexingEngineService.class )
.taggedWith( "rdf", "query", "indexing" )
- .visibleIn( indexingVisibility )
+ .visibleIn( visibility() )
.instantiateOnStartup();
- module.services( RdfQueryParserFactory.class ).visibleIn( indexingVisibility );
- module.services( OrgJsonValueSerializationService.class ).taggedWith( ValueSerialization.Formats.JSON );
+ module.services( RdfQueryParserFactory.class ).visibleIn( visibility() );
module.objects( EntityStateSerializer.class, EntityTypeSerializer.class );
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/14298086/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfNativeSesameStoreAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfNativeSesameStoreAssembler.java b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfNativeSesameStoreAssembler.java
index 79ca58a..57173db 100644
--- a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfNativeSesameStoreAssembler.java
+++ b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfNativeSesameStoreAssembler.java
@@ -20,31 +20,28 @@
package org.apache.polygene.index.rdf.assembly;
import org.apache.polygene.api.common.Visibility;
-import org.apache.polygene.api.value.ValueSerialization;
-import org.apache.polygene.bootstrap.Assembler;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.index.rdf.RdfIndexingEngineService;
import org.apache.polygene.index.rdf.query.RdfQueryParserFactory;
import org.apache.polygene.library.rdf.entity.EntityStateSerializer;
import org.apache.polygene.library.rdf.entity.EntityTypeSerializer;
+import org.apache.polygene.library.rdf.repository.NativeConfiguration;
import org.apache.polygene.library.rdf.repository.NativeRepositoryService;
-import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
-public class RdfNativeSesameStoreAssembler
- implements Assembler
+public class RdfNativeSesameStoreAssembler extends AbstractRdfIndexingAssembler<RdfNativeSesameStoreAssembler>
{
- private Visibility indexingVisibility;
private Visibility repositoryVisibility;
public RdfNativeSesameStoreAssembler()
{
- this( Visibility.application, Visibility.module );
+ visibleIn( Visibility.application );
+ this.repositoryVisibility = Visibility.module;
}
public RdfNativeSesameStoreAssembler( Visibility indexingVisibility, Visibility repositoryVisibility )
{
- this.indexingVisibility = indexingVisibility;
+ visibleIn( indexingVisibility );
this.repositoryVisibility = repositoryVisibility;
}
@@ -54,14 +51,18 @@ public class RdfNativeSesameStoreAssembler
{
module.services( NativeRepositoryService.class )
.visibleIn( repositoryVisibility )
- .instantiateOnStartup()
- .identifiedBy( "rdf-indexing" );
+ .instantiateOnStartup();
module.services( RdfIndexingEngineService.class )
.taggedWith( "rdf", "query", "indexing" )
- .visibleIn( indexingVisibility )
+ .visibleIn( visibility() )
.instantiateOnStartup();
- module.services( RdfQueryParserFactory.class ).visibleIn( indexingVisibility );
- module.services( OrgJsonValueSerializationService.class ).taggedWith( ValueSerialization.Formats.JSON );
+ module.services( RdfQueryParserFactory.class ).visibleIn( visibility() );
module.objects( EntityStateSerializer.class, EntityTypeSerializer.class );
+
+ if( hasConfig() )
+ {
+ configModule().entities( NativeConfiguration.class ).
+ visibleIn( configVisibility() );
+ }
}
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/14298086/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfRdbmsSesameStoreAssembler.java
----------------------------------------------------------------------
diff --git a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfRdbmsSesameStoreAssembler.java b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfRdbmsSesameStoreAssembler.java
index dcf9ffd..12e8681 100644
--- a/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfRdbmsSesameStoreAssembler.java
+++ b/extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/assembly/RdfRdbmsSesameStoreAssembler.java
@@ -28,13 +28,13 @@ import org.apache.polygene.index.rdf.RdfIndexingEngineService;
import org.apache.polygene.index.rdf.query.RdfQueryParserFactory;
import org.apache.polygene.library.rdf.entity.EntityStateSerializer;
import org.apache.polygene.library.rdf.entity.EntityTypeSerializer;
+import org.apache.polygene.library.rdf.repository.NativeConfiguration;
+import org.apache.polygene.library.rdf.repository.RdbmsRepositoryConfiguration;
import org.apache.polygene.library.rdf.repository.RdbmsRepositoryService;
import org.apache.polygene.valueserialization.orgjson.OrgJsonValueSerializationService;
-public class RdfRdbmsSesameStoreAssembler
- implements Assembler
+public class RdfRdbmsSesameStoreAssembler extends AbstractRdfIndexingAssembler<RdfNativeSesameStoreAssembler>
{
- private Visibility indexingVisibility;
private Visibility repositoryVisibility;
public RdfRdbmsSesameStoreAssembler()
@@ -44,7 +44,7 @@ public class RdfRdbmsSesameStoreAssembler
public RdfRdbmsSesameStoreAssembler( Visibility indexingVisibility, Visibility repositoryVisibility )
{
- this.indexingVisibility = indexingVisibility;
+ visibleIn( indexingVisibility );
this.repositoryVisibility = repositoryVisibility;
}
@@ -54,14 +54,18 @@ public class RdfRdbmsSesameStoreAssembler
{
module.services( RdbmsRepositoryService.class )
.visibleIn( repositoryVisibility )
- .instantiateOnStartup()
- .identifiedBy( "rdf-indexing" );
+ .instantiateOnStartup();
module.services( RdfIndexingEngineService.class )
.taggedWith( "rdf", "query", "indexing" )
- .visibleIn( indexingVisibility )
+ .visibleIn( visibility() )
.instantiateOnStartup();
- module.services( RdfQueryParserFactory.class ).visibleIn( indexingVisibility );
- module.services( OrgJsonValueSerializationService.class ).taggedWith( ValueSerialization.Formats.JSON );
+ module.services( RdfQueryParserFactory.class ).visibleIn( visibility() );
module.objects( EntityStateSerializer.class, EntityTypeSerializer.class );
+
+ if( hasConfig() )
+ {
+ configModule().entities( RdbmsRepositoryConfiguration.class ).
+ visibleIn( configVisibility() );
+ }
}
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/14298086/tools/generator-polygene/app/index.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/index.js b/tools/generator-polygene/app/index.js
index 7f76c10..583edbf 100644
--- a/tools/generator-polygene/app/index.js
+++ b/tools/generator-polygene/app/index.js
@@ -31,10 +31,32 @@ module.exports = generators.Base.extend(
// Calling the super constructor is important so our generator is correctly set up
generators.Base.apply(this, arguments);
- this.option('import-model'); // --import-model reads model.json in current directory and creates the domain model for it.
+ this.option('import-model', {
+ name: "import",
+ desc: 'Reads a model file and creates the domain model for it.',
+ type: String,
+ default: "./model.json",
+ hide: false
+ });
+
+ this.option('export-model', {
+ name: "export",
+ desc: 'Writes the model of the application into a json file.',
+ type: String,
+ default: "exported-model",
+ hide: false
+ });
+
+ this.option('noPrompt', {
+ name: "noPrompt",
+ desc: 'If specified, the interactive prompts will be disabled.',
+ type: Boolean,
+ default: false,
+ hide: false
+ });
- if (this.options.import != null) {
- polygene = importModel(this, './imported-model.json');
+ if (this.options.import) {
+ polygene = importModel(this.options.import);
polygene.name = polygene.name ? polygene.name : firstUpper(this.appname);
polygene.packageName = polygene.packageName ? polygene.packageName : ("com.acme." + this.appname);
polygene.singletonApp = false; // not supported yet
@@ -44,13 +66,12 @@ module.exports = generators.Base.extend(
polygene.entitystore = polygene.entitystore ? polygene.entitystore : null;
polygene.caching = polygene.caching ? polygene.caching : null;
polygene.serialization = polygene.serialization ? polygene.serialization : null;
- console.log(JSON.stringify(polygene, null, 4));
}
assignFunctions(polygene);
},
prompting: function () {
- if (this.options.noPrompt != null) {
+ if (this.options.noPrompt) {
return this.prompt([]);
}
else {
@@ -194,8 +215,8 @@ module.exports = generators.Base.extend(
});
var buildToolChain = require(__dirname + '/templates/buildtool/build.js');
buildToolChain.write(polygene);
- if (this.options.export != null) {
- exportModel(this, "exported-model.json");
+ if (this.options.export) {
+ exportModel(this.options.export);
}
}
}
@@ -226,11 +247,17 @@ function firstUpper(text) {
return text.charAt(0).toUpperCase() + text.substring(1);
}
-function importModel(ctx, filename) {
+function importModel(filename) {
+ if ( typeof filename !== 'string' ) {
+ filename = "./model.json";
+ }
return JSON.parse(fs.readFileSync(filename, 'utf8'));
}
-function exportModel(ctx, filename) {
+function exportModel(filename) {
+ if ( typeof filename !== 'string' ) {
+ filename = "exported-model.json";
+ }
delete polygene.current;
return fs.writeFileSync(filename, JSON.stringify(polygene, null, 4) + "\n", 'utf8');
}
@@ -238,7 +265,6 @@ function exportModel(ctx, filename) {
function assignFunctions(polygene) {
polygene.hasFeature = function (feature) {
- console.log(polygene.features);
return polygene.features.indexOf(feature) >= 0;
};
@@ -287,17 +313,17 @@ function assignFunctions(polygene) {
polygene.firstUpper = function (text) {
return text.charAt(0).toUpperCase() + text.substring(1);
};
- polygene.typeNameOnly = function(text) {
+ polygene.typeNameOnly = function (text) {
var lastPos = text.lastIndexOf(".");
- if( lastPos < 0 ) {
+ if (lastPos < 0) {
return text;
}
return text.substring(lastPos + 1);
};
- polygene.configurationClassName = function( clazzName ) {
- if( clazzName.endsWith( "Service" )) {
- clazzName = clazzName.substring(0, clazzName.length - 7 );
+ polygene.configurationClassName = function (clazzName) {
+ if (clazzName.endsWith("Service")) {
+ clazzName = clazzName.substring(0, clazzName.length - 7);
}
return clazzName + "Configuration";
};
@@ -306,36 +332,36 @@ function assignFunctions(polygene) {
var state = [];
var imported = {};
var props = current.clazz.properties;
- if( props ) {
- for( var idx in props ) {
+ if (props) {
+ for (var idx in props) {
var prop = props[idx];
- state.push( 'Property' + '<' + polygene.typeNameOnly(prop.type) + "> " + prop.name + "();")
+ state.push('Property' + '<' + polygene.typeNameOnly(prop.type) + "> " + prop.name + "();")
imported[prop.type] = imported[prop.type];
}
} else {
- state.push( 'Property<String> name(); // TODO: remove sample property')
+ state.push('Property<String> name(); // TODO: remove sample property')
}
var assocs = current.clazz.associations;
- if( assocs ) {
- for( var idx in assocs ) {
+ if (assocs) {
+ for (var idx in assocs) {
var assoc = assocs[idx];
- state.push("Association" + '<' + polygene.typeNameOnly(assoc.type) + '>' + assoc.name + "();")
- imported[assoc.type] = imported[assoc.type] ;
+ state.push("Association" + '<' + polygene.typeNameOnly(assoc.type) + '>' + assoc.name + "();")
+ imported[assoc.type] = imported[assoc.type];
}
}
assocs = current.clazz.manyassociations;
- if( assocs ) {
- for( var idx in assocs ) {
+ if (assocs) {
+ for (var idx in assocs) {
var assoc = assocs[idx];
- state.push("ManyAssociation<" + polygene.typeNameOnly(assoc.type) + ">" + assoc.name + "();")
- imported[assoc.type] = imported[assoc.type] ;
+ state.push("ManyAssociation<" + polygene.typeNameOnly(assoc.type) + ">" + assoc.name + "();")
+ imported[assoc.type] = imported[assoc.type];
}
}
assocs = current.clazz.namedassociations;
- if( assocs ) {
- for( var idx in assocs ) {
+ if (assocs) {
+ for (var idx in assocs) {
var assoc = assocs[idx];
- state.push("NamedAssociation<" + polygene.typeNameOnly(assoc.type) + ">" + assoc.name + "();")
+ state.push("NamedAssociation<" + polygene.typeNameOnly(assoc.type) + ">" + assoc.name + "();")
imported[assoc.type] = imported[assoc.type];
}
}
@@ -345,18 +371,44 @@ function assignFunctions(polygene) {
polygene.prepareConfigClazz = function (current) {
var state = [];
+ var yaml = [];
var imported = {};
var props = current.clazz.configuration;
- if( props ) {
- for( var idx in props ) {
+ if (props) {
+ for (var idx in props) {
var prop = props[idx];
- state.push( 'Property' + '<' + polygene.typeNameOnly(prop.type) + "> " + prop.name + "();")
+ state.push('Property' + '<' + polygene.typeNameOnly(prop.type) + "> " + prop.name + "();")
imported[prop.type] = imported[prop.type];
+ var yamlDefault;
+ if( prop.type === "java.lang.String" ) {
+ yamlDefault = '""';
+ }
+ else if( prop.type === "java.lang.Boolean" ) {
+ yamlDefault = 'false';
+ }
+ else if( prop.type === "java.lang.Long" ) {
+ yamlDefault = '0';
+ }
+ else if( prop.type === "java.lang.Integer" ) {
+ yamlDefault = '0';
+ }
+ else if( prop.type === "java.lang.Double" ) {
+ yamlDefault = '0.0';
+ }
+ else if( prop.type === "java.lang.Float" ) {
+ yamlDefault = '0.0';
+ }
+ else {
+ yamlDefault = '\n # TODO: complex configuration type. ';
+ }
+ yaml.push( prop.name + " : " + yamlDefault);
}
} else {
- state.push( 'Property<String> name(); // TODO: remove sample property')
+ state.push('Property<String> name(); // TODO: remove sample property')
+ yaml.push( 'name : "sample config value"' );
}
current.state = state;
+ current.yaml = yaml;
current.imported = imported;
};
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/14298086/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Configuration.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Configuration.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Configuration.tmpl
index 14c9735..071ee7b 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Configuration.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Configuration.tmpl
@@ -19,19 +19,18 @@
-%>
package <%= packageName %>.model.<%= polygene.current.name %>;
-import org.apache.polygene.api.injection.scope.This;
-import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.property.Property;
<%
for( var prop in polygene.current.imported ) {
if( !prop.startsWith( "java.lang" )) {
- %><%- "import " + prop + ";"; %><%
+ %><%- "import " + prop + ";"; %>
+<%
}
} %>
public interface <%= polygene.current.clazz.name %>
{
-<% for( var idx in polygene.current.state ) { %>
- <%- polygene.current.state[idx]; %>
+<% for( var idx in polygene.current.state ) {
+%> <%- polygene.current.state[idx]; %>
<% } %>
}
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/14298086/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl
index ecec763..df53506 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Crud.tmpl
@@ -34,10 +34,10 @@ public interface <%= polygene.current.clazz.name %>
{
interface State
{
-<% for( var idx in polygene.current.state ) { %>
- <%- polygene.current.state[idx]; %>
-<% } %>
- }
+<% for( var idx in polygene.current.state ) {
+%> <%- polygene.current.state[idx]; %>
+<% }
+%> }
class Mixin
implements <%= polygene.current.clazz.name %>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/14298086/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl
index ecec763..df53506 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Entity.tmpl
@@ -34,10 +34,10 @@ public interface <%= polygene.current.clazz.name %>
{
interface State
{
-<% for( var idx in polygene.current.state ) { %>
- <%- polygene.current.state[idx]; %>
-<% } %>
- }
+<% for( var idx in polygene.current.state ) {
+%> <%- polygene.current.state[idx]; %>
+<% }
+%> }
class Mixin
implements <%= polygene.current.clazz.name %>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/14298086/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
index c4194e7..34a95b0 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/Value.tmpl
@@ -34,10 +34,10 @@ public interface <%= polygene.current.clazz.name %>
{
interface State
{
-<% for( var idx in polygene.current.state ) { %>
- <%- polygene.current.state[idx]; %>
-<% } %>
- }
+<% for( var idx in polygene.current.state ) {
+%> <%- polygene.current.state[idx]; %>
+<% }
+%> }
class Mixin
implements <%= polygene.current.clazz.name %>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/14298086/tools/generator-polygene/app/templates/DomainLayer/DomainModule/config.yaml.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/config.yaml.tmpl b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/config.yaml.tmpl
new file mode 100644
index 0000000..e2629d5
--- /dev/null
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/config.yaml.tmpl
@@ -0,0 +1,23 @@
+<%#
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *
+-%>
+-
+<% for( var idx in polygene.current.yaml ) {
+%> <%- polygene.current.yaml[idx]; %>
+<% } %>
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/14298086/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js
index 0c6f1eb..27b0a4f 100644
--- a/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js
+++ b/tools/generator-polygene/app/templates/DomainLayer/DomainModule/module.js
@@ -29,6 +29,8 @@ function copyPolygeneDomainModule(p, moduleName, moduleDef) {
copyComposites(p, moduleDef.objects, "Object");
copyComposites(p, moduleDef.services, "Service");
copyComposites(p, moduleDef.services, "Configuration");
+
+ copyConfigurationYaml(p, moduleDef.services )
}
function copyComposites(p, composites, type) {
@@ -46,4 +48,17 @@ function copyComposites(p, composites, type) {
'model/src/main/java/' + p.javaPackageDir + '/model/' + p.current.name + '/' + p.current.clazz.name + '.java');
}
}
-}
\ No newline at end of file
+}
+
+function copyConfigurationYaml(p, composites) {
+ for (var idx in composites) {
+ if (composites.hasOwnProperty(idx)) {
+ p.current.clazz = composites[idx];
+ p.prepareClazz(p.current);
+ p.copyTemplate(p.ctx,
+ 'DomainLayer/DomainModule/config.yaml.tmpl',
+ 'model/src/main/resources/' + p.javaPackageDir + '/model/' + p.current.name + '/' + p.current.clazz.name + '.yaml');
+ }
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/14298086/tools/generator-polygene/app/templates/InfrastructureLayer/IndexingModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/IndexingModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/IndexingModule/bootstrap.tmpl
index a1f9479..c7e1975 100644
--- a/tools/generator-polygene/app/templates/InfrastructureLayer/IndexingModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/IndexingModule/bootstrap.tmpl
@@ -43,7 +43,7 @@ public class <%- polygene.indexing %>IndexingModule
{
new <%- polygene.indexing %>IndexingAssembler()
.visibleIn( Visibility.application )
- .identifiedBy( "indexing-<%- polygene.indexing %>" )
+ .identifiedBy( "indexing-<%- polygene.indexing.toLowerCase() %>" )
.withConfig( configModule, Visibility.application )
.assemble( module );
return module;
http://git-wip-us.apache.org/repos/asf/polygene-java/blob/14298086/tools/generator-polygene/app/templates/InfrastructureLayer/StorageModule/bootstrap.tmpl
----------------------------------------------------------------------
diff --git a/tools/generator-polygene/app/templates/InfrastructureLayer/StorageModule/bootstrap.tmpl b/tools/generator-polygene/app/templates/InfrastructureLayer/StorageModule/bootstrap.tmpl
index 8e68e2f..997fe3b 100644
--- a/tools/generator-polygene/app/templates/InfrastructureLayer/StorageModule/bootstrap.tmpl
+++ b/tools/generator-polygene/app/templates/InfrastructureLayer/StorageModule/bootstrap.tmpl
@@ -44,7 +44,7 @@ public class <%- polygene.entitystore %>StorageModule
new <%- polygene.entitystore %>EntityStoreAssembler()
.visibleIn( Visibility.application )
.withConfig( configModule, Visibility.application )
- .identifiedBy( "entitystore-<%- polygene.entitystore %>" )
+ .identifiedBy( "entitystore-<%- polygene.entitystore.toLowerCase() %>" )
.assemble( module );
return module;
}