You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@isis.apache.org by da...@apache.org on 2016/03/06 19:00:51 UTC

[1/4] isis git commit: ISIS-993: split LayoutService back out into LayoutService (API) vs GridService (SPI); rationalizing APIs; adding documentation.

Repository: isis
Updated Branches:
  refs/heads/ISIS-993 [created] 5306b0112


http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/layout/LayoutServiceDefault.java
----------------------------------------------------------------------
diff --git a/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/layout/LayoutServiceDefault.java b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/layout/LayoutServiceDefault.java
new file mode 100644
index 0000000..5135f62
--- /dev/null
+++ b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/layout/LayoutServiceDefault.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.isis.core.metamodel.services.layout;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.util.Collection;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import javax.inject.Inject;
+import javax.xml.bind.Marshaller;
+
+import com.google.common.base.Predicate;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.ImmutableMap;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.isis.applib.FatalException;
+import org.apache.isis.applib.annotation.DomainService;
+import org.apache.isis.applib.annotation.NatureOfService;
+import org.apache.isis.applib.annotation.Programmatic;
+import org.apache.isis.applib.layout.component.Grid;
+import org.apache.isis.applib.services.grid.GridService;
+import org.apache.isis.applib.services.jaxb.JaxbService;
+import org.apache.isis.applib.services.layout.LayoutService;
+import org.apache.isis.core.metamodel.facets.object.grid.GridFacet;
+import org.apache.isis.core.metamodel.facets.object.viewmodel.ViewModelFacet;
+import org.apache.isis.core.metamodel.spec.ObjectSpecification;
+import org.apache.isis.core.metamodel.spec.SpecificationLoader;
+import org.apache.isis.core.metamodel.spec.SpecificationLoaderAware;
+import org.apache.isis.objectstore.jdo.metamodel.facets.object.persistencecapable.JdoPersistenceCapableFacet;
+
+@DomainService(
+        nature = NatureOfService.DOMAIN
+)
+public class LayoutServiceDefault implements LayoutService, SpecificationLoaderAware {
+
+    private static final Logger LOG = LoggerFactory.getLogger(LayoutServiceDefault.class);
+
+    @Override
+    public String toXml(final Class<?> domainClass, final Style style) {
+        final Grid grid = toGrid(domainClass, style);
+        return jaxbService.toXml(grid,
+                ImmutableMap.<String,Object>of(
+                        Marshaller.JAXB_SCHEMA_LOCATION,
+                        grid.getTnsAndSchemaLocation()
+                ));
+    }
+
+    protected Grid toGrid(final Class<?> domainClass, final Style style) {
+
+        if (style == Style.CURRENT) {
+            final ObjectSpecification objectSpec = specificationLookup.loadSpecification(domainClass);
+            final GridFacet facet = objectSpec.getFacet(GridFacet.class);
+            return facet != null? facet.getGrid(): null;
+        }
+
+        // don't use the grid from the facet, because it will be modified subsequently.
+        Grid grid = gridService.load(domainClass);
+        if(grid == null) {
+            grid = gridService.defaultGridFor(domainClass);
+        }
+        gridService.normalize(grid);
+        if (style == Style.NORMALIZED) {
+            return grid;
+        }
+        if (style == Style.COMPLETE) {
+            return gridService.complete(grid);
+        }
+        if (style == Style.MINIMAL) {
+            return gridService.minimal(grid);
+        }
+        throw new IllegalArgumentException("unsupported style");
+    }
+
+
+    @Programmatic
+    public byte[] toZip(final Style style) {
+        final Collection<ObjectSpecification> allSpecs = specificationLookup.allSpecifications();
+        final Collection<ObjectSpecification> domainObjectSpecs = Collections2
+                .filter(allSpecs, new Predicate<ObjectSpecification>(){
+                    @Override
+                    public boolean apply(final ObjectSpecification input) {
+                        return  !input.isAbstract() &&
+                                (input.containsDoOpFacet(JdoPersistenceCapableFacet.class) ||
+                                        input.containsDoOpFacet(ViewModelFacet.class));
+                    }});
+        final byte[] bytes;
+        try {
+            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+            final ZipOutputStream zos = new ZipOutputStream(baos);
+            final OutputStreamWriter writer = new OutputStreamWriter(zos);
+            for (final ObjectSpecification objectSpec : domainObjectSpecs) {
+                final Class<?> domainClass = objectSpec.getCorrespondingClass();
+                final Grid grid = toGrid(domainClass, style);
+                if(grid != null) {
+                    zos.putNextEntry(new ZipEntry(zipEntryNameFor(objectSpec)));
+                    final String xml = jaxbService.toXml(grid,
+                            ImmutableMap.<String,Object>of(
+                                    Marshaller.JAXB_SCHEMA_LOCATION,
+                                    grid.getTnsAndSchemaLocation()
+                            ));
+                    writer.write(xml);
+                    writer.flush();
+                    zos.closeEntry();
+                }
+            }
+            writer.close();
+            bytes = baos.toByteArray();
+        } catch (final IOException ex) {
+            throw new FatalException("Unable to create zip of layouts", ex);
+        }
+        return bytes;
+    }
+
+    private static String zipEntryNameFor(final ObjectSpecification objectSpec) {
+        final String fqn = objectSpec.getFullIdentifier();
+        return fqn.replace(".", File.separator)+".layout.xml";
+    }
+
+
+    ////////////////////////////////////////////////////////
+
+
+    //region > injected dependencies
+
+    private SpecificationLoader specificationLookup;
+
+    @Override
+    public void setSpecificationLoader(final SpecificationLoader specificationLookup) {
+        this.specificationLookup = specificationLookup;
+    }
+
+
+    @Inject
+    JaxbService jaxbService;
+
+    @Inject
+    GridService gridService;
+
+
+}

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/metamodel/src/test/java/org/apache/isis/core/metamodel/services/grid/BS3GridTest.java
----------------------------------------------------------------------
diff --git a/core/metamodel/src/test/java/org/apache/isis/core/metamodel/services/grid/BS3GridTest.java b/core/metamodel/src/test/java/org/apache/isis/core/metamodel/services/grid/BS3GridTest.java
index c353055..028e357 100644
--- a/core/metamodel/src/test/java/org/apache/isis/core/metamodel/services/grid/BS3GridTest.java
+++ b/core/metamodel/src/test/java/org/apache/isis/core/metamodel/services/grid/BS3GridTest.java
@@ -30,19 +30,19 @@ import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 
-import org.apache.isis.applib.services.layout.GridImplementationService;
-import org.apache.isis.applib.layout.grid.bootstrap3.BS3Col;
-import org.apache.isis.applib.layout.grid.bootstrap3.BS3Grid;
-import org.apache.isis.applib.layout.grid.bootstrap3.BS3Row;
-import org.apache.isis.applib.layout.grid.bootstrap3.BS3Tab;
-import org.apache.isis.applib.layout.grid.bootstrap3.BS3TabGroup;
 import org.apache.isis.applib.layout.component.ActionLayoutData;
 import org.apache.isis.applib.layout.component.CollectionLayoutData;
 import org.apache.isis.applib.layout.component.DomainObjectLayoutData;
 import org.apache.isis.applib.layout.component.FieldSet;
 import org.apache.isis.applib.layout.component.PropertyLayoutData;
+import org.apache.isis.applib.layout.grid.bootstrap3.BS3Col;
+import org.apache.isis.applib.layout.grid.bootstrap3.BS3Grid;
+import org.apache.isis.applib.layout.grid.bootstrap3.BS3Row;
+import org.apache.isis.applib.layout.grid.bootstrap3.BS3Tab;
+import org.apache.isis.applib.layout.grid.bootstrap3.BS3TabGroup;
+import org.apache.isis.applib.services.grid.GridSystemService;
 import org.apache.isis.applib.services.jaxb.JaxbService;
-import org.apache.isis.core.metamodel.services.grid.bootstrap3.GridImplementationServiceBS3;
+import org.apache.isis.core.metamodel.services.grid.bootstrap3.GridSystemServiceBS3;
 
 import static org.hamcrest.CoreMatchers.equalTo;
 import static org.hamcrest.CoreMatchers.is;
@@ -51,16 +51,16 @@ import static org.junit.Assert.assertThat;
 public class BS3GridTest {
 
     private JaxbService jaxbService;
-    private LayoutServiceDefault layoutServiceDefault;
-    private GridImplementationServiceBS3 gridImplementationServiceBS3;
+    private GridServiceDefault gridServiceDefault;
+    private GridSystemServiceBS3 gridSystemServiceBS3;
 
     @Before
     public void setUp() throws Exception {
         jaxbService = new JaxbService.Simple();
-        layoutServiceDefault = new LayoutServiceDefault();
-        gridImplementationServiceBS3 = new GridImplementationServiceBS3();
-        layoutServiceDefault.gridImplementationServices = Arrays.<GridImplementationService>asList(
-                gridImplementationServiceBS3);
+        gridServiceDefault = new GridServiceDefault();
+        gridSystemServiceBS3 = new GridSystemServiceBS3();
+        gridServiceDefault.gridSystemServices = Arrays.<GridSystemService>asList(
+                gridSystemServiceBS3);
     }
 
     @After
@@ -138,7 +138,7 @@ public class BS3GridTest {
         tabRightCol.getCollections().add(similarToColl);
         similarToColl.setId("similarTo");
 
-        final String schemaLocations = layoutServiceDefault.tnsAndSchemaLocation(bs3Grid);
+        final String schemaLocations = gridServiceDefault.tnsAndSchemaLocation(bs3Grid);
         String xml = jaxbService.toXml(bs3Grid,
                 ImmutableMap.<String,Object>of(Marshaller.JAXB_SCHEMA_LOCATION, schemaLocations));
         System.out.println(xml);


[4/4] isis git commit: ISIS-993: split LayoutService back out into LayoutService (API) vs GridService (SPI); rationalizing APIs; adding documentation.

Posted by da...@apache.org.
ISIS-993: split LayoutService back out into LayoutService (API) vs GridService (SPI); rationalizing APIs; adding documentation.


Project: http://git-wip-us.apache.org/repos/asf/isis/repo
Commit: http://git-wip-us.apache.org/repos/asf/isis/commit/5306b011
Tree: http://git-wip-us.apache.org/repos/asf/isis/tree/5306b011
Diff: http://git-wip-us.apache.org/repos/asf/isis/diff/5306b011

Branch: refs/heads/ISIS-993
Commit: 5306b01129faa34e4aef03a1c115db3d801e78e5
Parents: b985845
Author: Dan Haywood <da...@haywood-associates.co.uk>
Authored: Sun Mar 6 18:00:38 2016 +0000
Committer: Dan Haywood <da...@haywood-associates.co.uk>
Committed: Sun Mar 6 18:00:38 2016 +0000

----------------------------------------------------------------------
 .../main/asciidoc/guides/_rgcms_classes.adoc    |   2 +
 .../_rgcms_classes_i18n_TranslatableString.adoc |   1 +
 .../asciidoc/guides/_rgcms_classes_layout.adoc  |  59 ++
 .../asciidoc/guides/_rgcms_classes_mixins.adoc  |  16 +
 .../guides/_rgcms_classes_mixins_Dto.adoc       |  62 ++
 .../guides/_rgcms_classes_mixins_Object.adoc    |  26 +
 .../_rgcms_classes_mixins_Persistable.adoc      |  35 +
 .../asciidoc/guides/_rgcms_classes_roles.adoc   |   2 -
 .../guides/_rgcms_classes_roles_Dto.adoc        |  61 --
 .../_rgcms_classes_roles_Persistable.adoc       |  34 -
 .../src/main/asciidoc/guides/_rgsvc_api.adoc    |  11 +
 .../asciidoc/guides/_rgsvc_api_JaxbService.adoc |   2 +-
 .../guides/_rgsvc_api_LayoutService.adoc        |  98 +++
 .../src/main/asciidoc/guides/_rgsvc_spi.adoc    |  54 +-
 .../guides/_rgsvc_spi_GridLoaderService.adoc    |  36 +
 .../asciidoc/guides/_rgsvc_spi_GridService.adoc |  31 +
 .../guides/_rgsvc_spi_GridSystemService.adoc    |  68 ++
 .../guides/_rgsvc_spi_LocaleProvider.adoc       |   2 +-
 .../guides/_rgsvc_spi_TranslationService.adoc   |   7 +
 .../applib/services/grid/GridLoaderService.java |  37 +
 .../isis/applib/services/grid/GridService.java  |  96 +++
 .../applib/services/grid/GridSystemService.java |  55 ++
 .../layout/GridImplementationService.java       |  54 --
 .../applib/services/layout/LayoutService.java   |  69 +-
 .../services/layout/LayoutServiceMenu.java      |  18 +-
 .../layout/Object_downloadLayoutXml.java        |  15 +-
 .../facets/object/grid/GridFacetDefault.java    |  24 +-
 .../facets/object/grid/GridFacetFactory.java    |   8 +-
 .../json/LayoutMetadataReaderFromJson.java      |  12 +-
 .../grid/GridImplementationServiceAbstract.java | 688 -------------------
 .../services/grid/GridLoaderServiceDefault.java | 185 +++++
 .../services/grid/GridServiceDefault.java       | 204 ++++++
 .../grid/GridSystemServiceAbstract.java         | 686 ++++++++++++++++++
 .../services/grid/LayoutServiceDefault.java     | 434 ------------
 .../GridImplementationServiceBS3.java           | 674 ------------------
 .../grid/bootstrap3/GridSystemServiceBS3.java   | 682 ++++++++++++++++++
 .../services/layout/LayoutServiceDefault.java   | 161 +++++
 .../metamodel/services/grid/BS3GridTest.java    |  28 +-
 38 files changed, 2691 insertions(+), 2046 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes.adoc
index 57cd296..e20d13c 100644
--- a/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes.adoc
+++ b/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes.adoc
@@ -19,5 +19,7 @@ include::_rgcms_classes_spec.adoc[leveloffset=+1]
 include::_rgcms_classes_i18n.adoc[leveloffset=+1]
 include::_rgcms_classes_contributee.adoc[leveloffset=+1]
 include::_rgcms_classes_roles.adoc[leveloffset=+1]
+include::_rgcms_classes_mixins.adoc[leveloffset=+1]
+include::_rgcms_classes_grid.adoc[leveloffset=+1]
 
 

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_i18n_TranslatableString.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_i18n_TranslatableString.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_i18n_TranslatableString.adoc
index 52aa7c6..f8e7be7 100644
--- a/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_i18n_TranslatableString.adoc
+++ b/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_i18n_TranslatableString.adoc
@@ -11,3 +11,4 @@ The `TranslatableString` utility class ...
 
 
 
+

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_layout.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_layout.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_layout.adoc
new file mode 100644
index 0000000..8a515b5
--- /dev/null
+++ b/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_layout.adoc
@@ -0,0 +1,59 @@
+[[_rgcms_classes_layout]]
+= Layout (`1.12.0-SNAPSHOT`)
+:Notice: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at. http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR  CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
+:_basedir: ../
+:_imagesdir: images/
+
+
+The `org.apache.isis.applib.layout` package ...
+
+NOTE: TODO
+
+
+[[_rgcms_classes_layout_component]]
+== Component
+
+NOTE: TODO
+
+Consists of:
+
+* `Grid` +
++
+Top level container for a custom layout for a domain object.  `Grid` itself is an interface; it is the xref:rgsvc.adoc#_rgsvc_spi_GridSystemService[`GridSystemService`] that defines a concrete implementation.  The framework itself provides one implementation, for bootstrap3; its concrete classes are discussed xref:rgcms.adoc#_rgcms_classes_layout_grid-bootstrap3[below].
+
+* `FieldSet` +
++
+A fieldset (previously also called a property group or member group) of a number of the domain object's properties
+(along with any associationed actions of those properties).
+
+* layout data classes, which correspond to the similarly named annotations:
+
+** `PropertyLayoutData` (corresponding to the xref:rgant.adoc#_rgant_PropertyLayout[`@PropertyLayout`] annotation)
+
+** `CollectionLayoutData` (corresponding to the xref:rgant.adoc#_rgant_CollectionLayout[`@CollectionLayout`] annotation)
+
+** `ActionLayoutData` (corresponding to the xref:rgant.adoc#_rgant_ActionLayout[`@ActionLayout`] annotation)
+
+** `DomainObjectLayoutData` (corresponding to the xref:rgant.adoc#_rgant_DomainObjectLayout[`@DomainObjectLayout`] annotation)
+
+
+
+[[_rgcms_classes_layout_grid-bootstrap3]]
+== Bootstrap3 Grid
+
+NOTE: TODO
+
+Consists of:
+
+* `Row`
+
+* `Col`
+
+* `TabGroup`
+
+* `Tab`
+
+
+There are also two close cousins of `Col`, namely `ClearFixVisible` and `ClearFixHidden`.
+
+

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_mixins.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_mixins.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_mixins.adoc
new file mode 100644
index 0000000..8199c6b
--- /dev/null
+++ b/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_mixins.adoc
@@ -0,0 +1,16 @@
+[[_rgcms_classes_mixins]]
+= Mixins
+:Notice: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at. http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR  CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
+:_basedir: ../
+:_imagesdir: images/
+
+
+The interfaces listed in this chapter are role interfaces; they define a contract for the framework
+ to interact with those domain objects that implement these interfaces.
+
+
+include::_rgcms_classes_mixins_Object.adoc[leveloffset=+1]
+include::_rgcms_classes_mixins_Dto.adoc[leveloffset=+1]
+include::_rgcms_classes_mixins_Persistable.adoc[leveloffset=+1]
+
+

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_mixins_Dto.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_mixins_Dto.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_mixins_Dto.adoc
new file mode 100644
index 0000000..978c237
--- /dev/null
+++ b/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_mixins_Dto.adoc
@@ -0,0 +1,62 @@
+[[_rgcms_classes_mixins_Dto]]
+= `Dto`
+:Notice: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at. http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR  CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
+:_basedir: ../
+:_imagesdir: images/
+
+
+The `Dto` role interface is intended to be implemented by JAXB-annotated view models, that is, annotated using
+xref:rgant.adoc#_rgant-XmlRootElement[`@XmlRootElement`].  It enables the ability to download the XML and
+XSD schema of those objects using two xref:ugbtb.adoc#_ugbtb_decoupling_mixins[mixins],
+`Dto_downloadXml` and `Dto_downloadXsd`.
+
+The interface is just a marker interface (with no members), and is defined as:
+
+[source,java]
+----
+public interface Dto { }
+----
+
+The `Dto_downloadXml` mixin defines the following action:
+
+[source,java]
+----
+@Mixin
+public class Dto_downloadXml {
+    public Dto_downloadXml(final Dto dto) { ... }     // <1>
+    public Object downloadXml(final String fileName) { ... }   // <2>
+    ...
+}
+----
+<1> provided as an action to any class that (trivially) implements the `Dto` interface
+<2> actually this method is called '$$' in the code, a "special case" that means to use the derive the action name
+from the class name.
+
+This will return the XML text wrapped up in a xref:rgcms.adoc#_rgcms_classes_value-types_Clob[`Clob`].
+
+The `Dto_downloadXsd` mixin is similar:
+
+[source,java]
+----
+@Mixin
+public class Dto_downloadXsd {
+    public Dto_downloadXsd(final Dto dto) { ... }                                             // <1>
+    public Object downloadXsd(final String fileName, final IsisSchemes isisSchemas) { ... }   // <2>
+}
+----
+<1> provided as an action to any class that (trivially) implements the `Dto` interface
+<2> actually this is '$$' in the code, a "special case" that means to use the derive the action name from the class name.
+
+If the domain object's JAXB annotations reference only a single XSD schema then this will return that XML text as
+a xref:rgcms.adoc#_rgcms_classes_value-types_Clob[`Clob`] of that XSD.  If there are multiple XSD schemas referenced
+then the action will return a zip of those schemas, wrapped up in a
+xref:rgcms.adoc#_rgcms_classes_value-types_Blob[`Blob`].  The `IsisSchemas` parameter to the action can be used to
+optionally ignore the common xref:rgcms.adoc#_rgcms_schema[Apache Isis schemas] (useful if there is only one other XSD schema
+referenced by the DTO).
+
+
+
+== Related Services
+
+The `Dto_downloadXml` and `Dto_downloadXsd` delegate to the
+xref:rgsvc.adoc#_rgsvc_api_JaxbService[`JaxbService`] to actually generate the XML/XSD.
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_mixins_Object.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_mixins_Object.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_mixins_Object.adoc
new file mode 100644
index 0000000..101804f
--- /dev/null
+++ b/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_mixins_Object.adoc
@@ -0,0 +1,26 @@
+[[_rgcms_classes_mixins_Object]]
+= `Object`
+:Notice: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at. http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR  CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
+:_basedir: ../
+:_imagesdir: images/
+
+
+The framework currently provides a single mixin that contributes to simply `java.lang.Object`.  It provides the ability
+to download the layout XML for any domain object (in practical terms: entities and view models).
+
+
+The `Object_downloadLayoutXml` mixin defines the following action:
+
+[source,java]
+----
+@Mixin
+public class Object_downloadLayoutXml {
+    public Object_downloadLayoutXml(final Object object) { ... }     // <1>
+    public String downloadLayoutXml(final String fileName) { ... }   // <2>
+    ...
+}
+----
+<1> provided as an action to all objects
+<2> actually this method is called '$$' in the code, a "special case" that means to use the derive the action name
+from the class name.
+

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_mixins_Persistable.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_mixins_Persistable.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_mixins_Persistable.adoc
new file mode 100644
index 0000000..d46f56d
--- /dev/null
+++ b/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_mixins_Persistable.adoc
@@ -0,0 +1,35 @@
+[[_rgcms_classes_mixins_Persistable]]
+= `Persistable`
+:Notice: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at. http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR  CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
+:_basedir: ../
+:_imagesdir: images/
+
+
+All domain entities automatically implement the DataNucleus `Persistable` role interface as a result of the enhancer
+process (the fully qualified class name is `org.datanucleus.enhancement.Persistable`).  So as a developer you do not
+need to write any code for this role interface.
+
+Nevertheless, the `Persistable_downloadJdoMetadata` mixin provides the ability to download the
+JDO link:http://www.datanucleus.org/products/datanucleus/jdo/metadata_xml.html[class metadata in XML] form.  The mixin
+defines the following action:
+
+[source,java]
+----
+@Mixin
+public class Persistable_downloadJdoMetadata {
+    public Persistable_downloadJdoMetadata(final Persistable persistable) { ... }   // <1>
+    public Object downloadJdoMetadata(final String fileName) { ... }                // <2>
+    ...
+}
+----
+<1> provided as an action to any domain entity
+<2> actually this is method is called '$$' in the code, a "special case" that means to use the derive the action name
+from the class name.
+
+This will return the XML text wrapped up in a xref:rgcms.adoc#_rgcms_classes_value-types_Clob[`Clob`].
+
+
+== Related Services
+
+The mixin delegates to the xref:rgsvc.adoc#_rgsvc_api_IsisJdoSupport[`IsisJdoSupport`] service to obtain
+a reference to the JDO `PersistenceManagerFactory`.

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_roles.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_roles.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_roles.adoc
index 7a7bfcf..e100f47 100644
--- a/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_roles.adoc
+++ b/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_roles.adoc
@@ -12,7 +12,5 @@ The interfaces listed in this chapter are role interfaces; they define a contrac
 include::_rgcms_classes_roles_HoldsUpdatedAt.adoc[leveloffset=+1]
 include::_rgcms_classes_roles_HoldsUpdatedBy.adoc[leveloffset=+1]
 include::_rgcms_classes_roles_Timestampable.adoc[leveloffset=+1]
-include::_rgcms_classes_roles_Dto.adoc[leveloffset=+1]
-include::_rgcms_classes_roles_Persistable.adoc[leveloffset=+1]
 
 

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_roles_Dto.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_roles_Dto.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_roles_Dto.adoc
deleted file mode 100644
index dd94e0d..0000000
--- a/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_roles_Dto.adoc
+++ /dev/null
@@ -1,61 +0,0 @@
-[[_rgcms_classes_mixins_Dto]]
-= `Dto`
-:Notice: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at. http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR  CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
-:_basedir: ../
-:_imagesdir: images/
-
-
-The `Dto` role interface is intended to be implemented by JAXB-annotated view models, that is, annotated using
-xref:rgant.adoc#_rgant-XmlRootElement[`@XmlRootElement`].  It enables the ability to download the XML and
-XSD schema of those objects using two xref:ugbtb.adoc#_ugbtb_decoupling_mixins[mixins],
-`Dto_downloadXml` and `Dto_downloadXsd`.
-
-The interface is just a marker interface (with no members), and is defined as:
-
-[source,java]
-----
-public interface Dto { }
-----
-
-The `Dto_downloadXml` mixin defines the following action:
-
-[source,java]
-----
-@Mixin
-public class Dto_downloadXml {
-    public Dto_downloadXml(final Dto dto) { ... }     // <1>
-    public Object downloadXml(final String fileName) { ... }   // <2>
-    ...
-}
-----
-<1> provided as an action to any class that (trivially) implements the `Dto` interface
-<2> actually this is '$$' in the code, a "special case" that means to use the derive the action name from the class name.
-
-This will return the XML text wrapped up in a xref:rgcms.adoc#_rgcms_classes_value-types_Clob[`Clob`].
-
-The `Dto_downloadXsd` mixin is similar:
-
-[source,java]
-----
-@Mixin
-public class Dto_downloadXsd {
-    public Dto_downloadXsd(final Dto dto) { ... }                                             // <1>
-    public Object downloadXsd(final String fileName, final IsisSchemes isisSchemas) { ... }   // <2>
-}
-----
-<1> provided as an action to any class that (trivially) implements the `Dto` interface
-<2> actually this is '$$' in the code, a "special case" that means to use the derive the action name from the class name.
-
-If the domain object's JAXB annotations reference only a single XSD schema then this will return that XML text as
-a xref:rgcms.adoc#_rgcms_classes_value-types_Clob[`Clob`] of that XSD.  If there are multiple XSD schemas referenced
-then the action will return a zip of those schemas, wrapped up in a
-xref:rgcms.adoc#_rgcms_classes_value-types_Blob[`Blob`].  The `IsisSchemas` parameter to the action can be used to
-optionally ignore the common xref:rgcms.adoc#_rgcms_schema[Apache Isis schemas] (useful if there is only one other XSD schema
-referenced by the DTO).
-
-
-
-== Related Services
-
-The `Dto_downloadXml` and `Dto_downloadXsd` delegate to the
-xref:rgsvc.adoc#_rgsvc_api_JaxbService[`JaxbService`] to actually generate the XML/XSD.
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_roles_Persistable.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_roles_Persistable.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_roles_Persistable.adoc
deleted file mode 100644
index e51419c..0000000
--- a/adocs/documentation/src/main/asciidoc/guides/_rgcms_classes_roles_Persistable.adoc
+++ /dev/null
@@ -1,34 +0,0 @@
-[[_rgcms_classes_mixins_Persistable]]
-= `Persistable`
-:Notice: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at. http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR  CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
-:_basedir: ../
-:_imagesdir: images/
-
-
-All domain entities automatically implement the DataNucleus `Persistable` role interface as a result of the enhancer
-process (the fully qualified class name is `org.datanucleus.enhancement.Persistable`).  So as a developer you do not
-need to write any code for this role interface.
-
-Nevertheless, the `Persistable_downloadJdoMetadata` mixin provides the ability to download the
-JDO link:http://www.datanucleus.org/products/datanucleus/jdo/metadata_xml.html[class metadata in XML] form.  The mixin
-defines the following action:
-
-[source,java]
-----
-@Mixin
-public class Persistable_downloadJdoMetadata {
-    public Persistable_downloadJdoMetadata(final Persistable persistable) { ... }   // <1>
-    public Object downloadJdoMetadata(final String fileName) { ... }                // <2>
-    ...
-}
-----
-<1> provided as an action to any domain entity
-<2> actually this is '$$' in the code, a "special case" that means to use the derive the action name from the class name.
-
-This will return the XML text wrapped up in a xref:rgcms.adoc#_rgcms_classes_value-types_Clob[`Clob`].
-
-
-== Related Services
-
-The mixin delegates to the xref:rgsvc.adoc#_rgsvc_api_IsisJdoSupport[`IsisJdoSupport`] service to obtain
-a reference to the JDO `PersistenceManagerFactory`.

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgsvc_api.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgsvc_api.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgsvc_api.adoc
index 541a160..55a1d28 100644
--- a/adocs/documentation/src/main/asciidoc/guides/_rgsvc_api.adoc
+++ b/adocs/documentation/src/main/asciidoc/guides/_rgsvc_api.adoc
@@ -191,6 +191,16 @@ SpecificationProvider`].
 |
 
 
+|xref:rgsvc.adoc#_rgsvc_api_LayoutService[`o.a.i.applib.` +
+`services.layout` +
+`LayoutService`]
+|(`1.12.0-SNAPSHOT`) Provides the ability to download dynamic layout XML files, in various styles.
+|`LayoutServiceDefault` +
+``o.a.i.core`` +
+``isis-core-metamodel``
+|Functionality surfaced in the UI through related mixin and menu.
+
+
 |xref:rgsvc.adoc#_rgsvc_api_MementoService[`o.a.i.applib.` +
 `services.memento` +
 `MementoService`]
@@ -328,6 +338,7 @@ include::_rgsvc_api_GuiceBeanProvider.adoc[leveloffset=+1]
 include::_rgsvc_api_HomePageProviderService.adoc[leveloffset=+1]
 include::_rgsvc_api_IsisJdoSupport.adoc[leveloffset=+1]
 include::_rgsvc_api_JaxbService.adoc[leveloffset=+1]
+include::_rgsvc_api_LayoutService.adoc[leveloffset=+1]
 include::_rgsvc_api_MementoService.adoc[leveloffset=+1]
 include::_rgsvc_api_MetamodelService.adoc[leveloffset=+1]
 include::_rgsvc_api_QueryResultsCache.adoc[leveloffset=+1]

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgsvc_api_JaxbService.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgsvc_api_JaxbService.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgsvc_api_JaxbService.adoc
index a0503f5..0f42174 100644
--- a/adocs/documentation/src/main/asciidoc/guides/_rgsvc_api_JaxbService.adoc
+++ b/adocs/documentation/src/main/asciidoc/guides/_rgsvc_api_JaxbService.adoc
@@ -51,7 +51,7 @@ Isis provides a default implementation of the service, `o.a.i.schema.services.ja
 This service is provided as a convenience for applications, but is also used internally by the framework to
 xref:rgant.adoc#_rgant-XmlRootElement[`@XmlRootElement`]-annotated
 xref:ugbtb.adoc#_ugbtb_view-models[view models].  The functionality to download XML and XSD schemas is also
-exposed in the UI through mixins to xref:rgcms.adoc#_rgcms_classes_roles_Dto[`Dto`] interface.
+exposed in the UI through mixins to xref:rgcms.adoc#_rgcms_classes_mixins_Dto[`Dto`] interface.
 
 
 

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgsvc_api_LayoutService.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgsvc_api_LayoutService.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgsvc_api_LayoutService.adoc
new file mode 100644
index 0000000..8c41b43
--- /dev/null
+++ b/adocs/documentation/src/main/asciidoc/guides/_rgsvc_api_LayoutService.adoc
@@ -0,0 +1,98 @@
+[[_rgsvc_api_LayoutService]]
+= `LayoutService` (`1.12.0-SNAPSHOT`)
+:Notice: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at. http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR  CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
+:_basedir: ../
+:_imagesdir: images/
+
+
+
+The `LayoutService` provides the ability to obtain the XML layout for a single domain object or for all domain
+objects.  This functionality is surfaced through the user interface through a related xref:_rgsvc_api_LayoutService_related-mixins-and-menus[mixin and menu action].
+
+
+
+[[_rgsvc_api_LayoutService_api-and-implementation]]
+== API & Implementation
+
+The API defined by `LayoutService` is:
+
+[source,java]
+----
+public interface LayoutService {
+    String toXml(Class<?> domainClass, Style style);        // <1>
+    byte[] toZip(Style style);                              // <2>
+}
+----
+<1> Returns the serialized XML form of the layout (grid) for the specified domain class, in specified style (discussed below).
+<2> Returns (a byte array) of a zip of the serialized XML of the layouts (grids), for all domain entities and view models.
+
+The `Style` enum is defined as:
+
+[source,java]
+----
+enum Style {
+    CURRENT,
+    COMPLETE,
+    NORMALIZED,
+    MINIMAL
+}
+----
+
+The `CURRENT` style corresponds to the layout already loaded for the domain class, typically from an already persisted
+`layout.xml` file.  The other three styles allow the developer to choose how much metadata is to be specified in the
+XML, and how much (if any) will be obtained elsewhere, typically from annotations in the metamodel (but also from
+`.layout.json` file if present).  The table below summarises the choices:
+
+.Table caption
+[cols="1a,1a,1a,1a", options="header"]
+|===
+
+| Style
+| xref:rgant.adoc#_rgant_MemberGroupLayout[`@MemberGroupLayout`]
+| xref:rgant.adoc#_rgant_MemberOrder[`@MemberOrder`]
+| xref:rgant.adoc#_rgant_ActionLayout[`@ActionLayout`], xref:rgant.adoc#_rgant_PropertyLayout[`@PropertyLayout`], xref:rgant.adoc#_rgant_CollectionLayout[`@CollectionLayout`]
+
+
+|`COMPLETE`
+|serialized as XML
+|serialized as XML
+|serialized as XML
+
+
+|`NORMALIZED`
+|serialized as XML
+|serialized as XML
+|not in the XML
+
+
+|`MINIMIZED`
+|serialized as XML
+|not in the XML
+|not in the XML
+
+|===
+
+
+
+[[_rgsvc_api_LayoutService_related-mixins-and-menus]]
+== Related Mixins and Menus
+
+The service's functionality is exposed in the UI through a mixin (per object) and a menu action (for all objects):
+
+* the xref:rgant.adoc#_rgcms_classes_mixins_Object[`Object` mixin] provides the ability to download the XML layout for
+any domain object (entity or view model).
+
+* the `LayoutServiceMenu` provides the ability to download all XML layouts as a single ZIP file (in any of the
+three styles).
+
+The XML can then be copied into the codebase of the application, and annotations in the domain classes removed as
+desired.
+
+
+
+[[_rgsvc_api_LayoutService_related-domain-services]]
+== Related Domain Services
+
+The xref:rgsvc.adoc#_rgsvc_spi_GridService[`GridService`] is responsible for loading and normalizing layout XML for
+a domain class.  It in turn uses the xref:rgsvc.adoc#_rgsvc_spi_GridLoaderService[`GridLoaderService`] and  xref:rgsvc.adoc#_rgsvc_spi_GridSystemService[`GridSystemService`]
+services.
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi.adoc
index 3845f3a..0986658 100644
--- a/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi.adoc
+++ b/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi.adoc
@@ -123,6 +123,49 @@ a configured `EmailService`
 |Extensible using composite pattern if required
 
 
+|xref:rgsvc.adoc#_rgsvc_spi_FixtureScriptsSpecificationProvider[`o.a.i.applib.` +
+`services.fixturespec` +
+`FixtureScripts-` +
+`SpecificationProvider`]
+|Provides settings for xref:rgsvc.adoc#_rgsvc_api_FixtureScriptsDefault[`FixtureScriptsDefault`] fallback domain service for executing fixture scripts.
+|
+|
+
+
+|xref:rgsvc.adoc#_rgsvc_spi_GridSystemService[`o.a.i.applib.` +
+`services.grid` +
+`GridSystemService`]
+|(`1.12.0-SNAPSHOT`) Validates and normalizes the grid layout for a domain class (with respect to a particular grid
+system such as Bootstrap3), also providing a default grid (for those domain classes where there is no grid layout).
+|`GridSystemServiceBS3` +
+``o.a.i.core`` +
+``isis-core-metamodel``
+|
+
+
+|xref:rgsvc.adoc#_rgsvc_spi_GridLoaderService[`o.a.i.applib.` +
+`services.grid` +
+`GridLoaderService`]
+|(`1.12.0-SNAPSHOT`) Responsible for loading a grid layout for a domain class, eg from a `layout.xml` file.
+|`GridLoaderServiceDefault` +
+``o.a.i.core`` +
+``isis-core-metamodel``
+|
+
+
+|xref:rgsvc.adoc#_rgsvc_spi_GridService[`o.a.i.applib.` +
+`services.grid` +
+`GridService`]
+|(`1.12.0-SNAPSHOT`) A facade on top of both xref:rgsvc.adoc#_rgsvc_spi_GridLoaderService[`GridLoaderService`] and
+xref:rgsvc.adoc#_rgsvc_spi_GridSystemService[`GridSystemService`], thus being able to return normalized
+grids for any domain class.
+|`GridServiceDefault` +
+``o.a.i.core`` +
+``isis-core-metamodel``
+|
+
+
+
 |xref:rgsvc.adoc#_rgsvc_spi_LocaleProvider[`o.a.i.applib.` +
 `services.i18n` +
 `LocaleProvider`]
@@ -132,14 +175,6 @@ a configured `EmailService`
 ``isis-viewer-wicket-impl``
 |
 
-|xref:rgsvc.adoc#_rgsvc_spi_FixtureScriptsSpecificationProvider[`o.a.i.applib.` +
-`services.fixturespec` +
-`FixtureScripts-` +
-`SpecificationProvider`]
-|Provides settings for xref:rgsvc.adoc#_rgsvc_api_FixtureScriptsDefault[`FixtureScriptsDefault`] fallback domain service for executing fixture scripts.
-|
-|
-
 |xref:rgsvc.adoc#_rgsvc_spi_PublishingService[`o.a.i.applib.` +
 `services.publish` +
 `PublishingService`]
@@ -302,6 +337,9 @@ include::_rgsvc_spi_ErrorReportingService.adoc[leveloffset=+1]
 include::_rgsvc_spi_EventSerializer.adoc[leveloffset=+1]
 include::_rgsvc_spi_ExceptionRecognizer.adoc[leveloffset=+1]
 include::_rgsvc_spi_FixtureScriptsSpecificationProvider.adoc[leveloffset=+1]
+include::_rgsvc_spi_GridSystemService.adoc[leveloffset=+1]
+include::_rgsvc_spi_GridLoaderService.adoc[leveloffset=+1]
+include::_rgsvc_spi_GridService.adoc[leveloffset=+1]
 include::_rgsvc_spi_LocaleProvider.adoc[leveloffset=+1]
 include::_rgsvc_spi_PublishingService.adoc[leveloffset=+1]
 include::_rgsvc_spi_RepresentationService.adoc[leveloffset=+1]

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_GridLoaderService.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_GridLoaderService.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_GridLoaderService.adoc
new file mode 100644
index 0000000..c72b2bb
--- /dev/null
+++ b/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_GridLoaderService.adoc
@@ -0,0 +1,36 @@
+[[_rgsvc_spi_GridLoaderService]]
+= `GridLoaderService` (`1.12.0-SNAPSHOT`)
+:Notice: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at. http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR  CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
+:_basedir: ../
+:_imagesdir: images/
+
+
+
+The `GridLoaderService` provides the ability to load the XML layout (grid) for a domain class.
+
+== SPI
+
+The SPI defined by this service is:
+
+[source,java]
+----
+public interface GridLoaderService {
+    boolean existsFor(Class<?> domainClass);    // <1>
+    Grid load(final Class<?> domainClass);      // <2>
+}
+----
+<1> whether any persisted layout metadata (eg a `.layout.xml` file) exists for this domain class.
+<2> returns a new instance of a xref:rgcms.adoc#_rgcms_classes_layout_component[`Grid`] for the specified domain class, eg as loaded from a `layout.xml` file.  If none exists, will return null (and the calling xref:rgsvc.adoc#_rgsvc_spi_GridService[`GridService`] will use xref:rgsvc.adoc#_rgsvc_spi_GridSystemService[`GridSystemService`] to obtain a default grid for the domain class).
+
+
+NOTE: TODO
+
+
+== Implementation
+
+NOTE: TODO
+
+
+== Related Services
+
+NOTE: TODO

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_GridService.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_GridService.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_GridService.adoc
new file mode 100644
index 0000000..d0ef787
--- /dev/null
+++ b/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_GridService.adoc
@@ -0,0 +1,31 @@
+[[_rgsvc_spi_GridService]]
+= `GridService` (`1.12.0-SNAPSHOT`)
+:Notice: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at. http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR  CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
+:_basedir: ../
+:_imagesdir: images/
+
+
+
+The `GridService` provides the ability to load the XML layout (grid) for a domain class.   To do this it delegates:
+
+* to xref:rgsvc.adoc#_rgsvc_spi_GridLoaderService[`GridLoaderService`] to load a pre-existing layout for the domain class, if possible
+
+* to xref:rgsvc.adoc#_rgsvc_spi_GridSystemService[`GridSystemService`] to normalize the grid with respect to Apache
+Isis' internal metamodel, in other words to ensure that all of the domain objects' properties, collections and actions are associated with regions of the grid.
+
+Once a grid has been loaded for a domain class, this is cached internally by Apache Isis' internal meta model (in the
+`GridFacet` facet).  Note that that (if running in prototype mode, at least), any subsequent changes to the XML will be detected and the grid rebuilt.  This allows for dynamic layouts.
+
+== SPI
+
+NOTE: TODO
+
+
+== Implementation
+
+NOTE: TODO
+
+
+== Related Services
+
+NOTE: TODO

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_GridSystemService.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_GridSystemService.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_GridSystemService.adoc
new file mode 100644
index 0000000..46afbc5
--- /dev/null
+++ b/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_GridSystemService.adoc
@@ -0,0 +1,68 @@
+[[_rgsvc_spi_GridSystemService]]
+= `GridSystemService` (`1.12.0-SNAPSHOT`)
+:Notice: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at. http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR  CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
+:_basedir: ../
+:_imagesdir: images/
+
+
+
+The `GridSystemService` encapsulates a single layout grid system which can be used to customize the layout
+of domain objects.  In particular this means being able to return a "normalized" form (validating and associating
+domain object members into the various regions of the grid) and in providing a default grid if there is no other
+metadata available.
+
+In theory there can be multiple implementations of this service, one per concrete subclass of the applib `Grid` class.  Each concrete implementation requires Wicket viewer components capable of interpreting the grid layout.
+
+The framework provides a single such grid implementation, namely for Bootstrap3.
+
+
+== SPI
+
+The SPI defined by this service is:
+
+[source,java]
+----
+public interface GridSystemService<G extends Grid> {
+    Class<? extends Grid> gridImplementation();                 // <1>
+    String tns();                                               // <2>
+    String schemaLocation();                                    // <3>
+    Grid defaultGrid(Class<?> domainClass);                     // <4>
+    void normalize(G grid, Class<?> domainClass);               // <5>
+    void complete(G grid, Class<?> domainClass);                // <6>
+    void minimal(G grid, Class<?> domainClass);                 // <7>
+}
+----
+<1> The concrete subclass of `Grid` supported by this implementation. As noted in the introduction, there can be multiple implementations of this service,  but there can only be one implementation per concrete subclass.  As is normal practice,
+the service with the lowest xref:rgant.adoc#_rgant_DomainServiceLayout_menuOrder[`@DomainServiceLayout#menuOrder()`] takes precedence.
+<2> the target namespace for this grid system.  This is used when generating the XML.  The Bootstrap3 grid system provided by the framework returns the value `http://isis.apache.org/applib/layout/grid/bootstrap3`.
+<3> the schema location for the XSD.  The Bootstrap3 grid system provided by the framework returns the value `http://isis.apache.org/applib/layout/grid/bootstrap3/bootstrap3.xsd`.
+<4> a default grid, eg two columns in ratio 4:8.  Used when no existing grid layout exists for a domain class.
+<5> Validates and normalizes a grid, modifying the grid so that all of the domain object's members (properties, collections, actions) are bound to regions of the grid.  This is done using existing metadata, most notably that of the xref:rgant.adoc#_rgant_MemberOrder[`@MemberOrder`] annotation.  Such a grid, if persisted as the layout XML file for the domain class, allows the
+ `@MemberOrder` annotation to be removed from the source code of the domain class (but other annotations must be retained).
+<6> Takes a normalized grid and enriches it with additional metadata (taken from Apache Isis' internal metadata) that can be represented in the layout XML.  Such a grid, if persisted as the layout XML file for the domain class, allows all layout annotations (xref:rgant.adoc#_rgant_ActionLayout[`@ActionLayout`], xref:rgant.adoc#_rgant_PropertyLayout[`@PropertyLayout`] and xref:rgant.adoc#_rgant_CollectionLayout[`@CollectionLayout`]) to be removed from the source code of the domain class.
+<7> Takes a normalized grid and strips out removes all members, leaving only the grid structure.  Such a grid, if persisted as the layout XML file for the domain class, requires that the xref:rgant.adoc#_rgant_MemberOrder[`@MemberOrder`] annotation is retained in the source code of said class in order to bind members to the regions of the grid.
+
+
+== Implementation
+
+The framework provides `GridSystemServiceBS3`, an implementation that encodes the bootstrap3 grid system.  (The framework
+also provides xref:ugvw.adoc[Wicket viewer] components that are capable of interpreting and rendering this metadata).
+
+
+== Registering the Services
+
+Assuming that the `configuration-and-annotation` services installer is configured (implicit if using the
+`AppManifest` to xref:rgcms.adoc#_rgcms_classes_AppManifest-bootstrapping[bootstrap the app]), then the
+ Bootstrap3 implementation of `GridSystemService` is automatically registered and injected, and no further
+ configuration is required.
+
+To use an alternative implementation, use
+xref:rgant.adoc#_rgant-DomainServiceLayout_menuOrder[`@DomainServiceLayout#menuOrder()`] (as explained
+further in this xref:ugfun.adoc#_ugfun_how-tos_replacing-default-service-implementations["how to"] tip).
+
+
+
+
+== Related Services
+
+This service is used by xref:rgsvc.adoc#_rgsvc_spi_GridService[`GridService`].

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_LocaleProvider.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_LocaleProvider.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_LocaleProvider.adoc
index dd99647..a6aaebb 100644
--- a/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_LocaleProvider.adoc
+++ b/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_LocaleProvider.adoc
@@ -50,7 +50,7 @@ Currently there is no equivalent implementation for the xref:ugvro.adoc#[Restful
 == Registering the Services
 
 Assuming that the `configuration-and-annotation` services installer is configured (implicit if using the
-`AppManifest` to xref:rgcms.adoc#_rgcms_classes_AppManifest-bootstrapping[bootstrap the app]), _and_ that the
+`AppManifest` to xref:rgcms.adoc#_rgcms_classes_AppManifest-bootstrapping[bootstrap the app]), __and__ that the
 xref:ugvw.adoc#[Wicket viewer] is being used, then an implementation of `LocaleProvider` is
 automatically registered and injected (it is annotated with `@DomainService`) so no further configuration is required.
 

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_TranslationService.adoc
----------------------------------------------------------------------
diff --git a/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_TranslationService.adoc b/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_TranslationService.adoc
index 4476549..09695e0 100644
--- a/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_TranslationService.adoc
+++ b/adocs/documentation/src/main/asciidoc/guides/_rgsvc_spi_TranslationService.adoc
@@ -73,6 +73,13 @@ further in this xref:ugfun.adoc#_ugfun_how-tos_replacing-default-service-impleme
 
 
 
+[[_rgsvc_api_LayoutService_related-mixins-and-menus]]
+== Related Menus
+
+The `TranslationServicePoMenu` menu exposes the `TranslationServicePo` service's `toPot()` method so that all
+translations can be downloaded as a single file.
+
+
 
 == Related Services
 

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/applib/src/main/java/org/apache/isis/applib/services/grid/GridLoaderService.java
----------------------------------------------------------------------
diff --git a/core/applib/src/main/java/org/apache/isis/applib/services/grid/GridLoaderService.java b/core/applib/src/main/java/org/apache/isis/applib/services/grid/GridLoaderService.java
new file mode 100644
index 0000000..c6c49c2
--- /dev/null
+++ b/core/applib/src/main/java/org/apache/isis/applib/services/grid/GridLoaderService.java
@@ -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 org.apache.isis.applib.services.grid;
+
+import org.apache.isis.applib.annotation.Programmatic;
+import org.apache.isis.applib.layout.component.Grid;
+
+public interface GridLoaderService {
+
+    /**
+     * Whether any persisted layout metadata (eg a <code>.layout.xml</code> file) exists for this domain class.
+     */
+    @Programmatic
+    boolean existsFor(Class<?> domainClass);
+
+    /**
+     * Returns a new instance of a {@link Grid} for the specified domain class, eg from a
+     * <code>layout.xml</code> file, else <code>null</code>.
+     */
+    @Programmatic
+    Grid load(final Class<?> domainClass);
+
+}

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/applib/src/main/java/org/apache/isis/applib/services/grid/GridService.java
----------------------------------------------------------------------
diff --git a/core/applib/src/main/java/org/apache/isis/applib/services/grid/GridService.java b/core/applib/src/main/java/org/apache/isis/applib/services/grid/GridService.java
new file mode 100644
index 0000000..fc198eb
--- /dev/null
+++ b/core/applib/src/main/java/org/apache/isis/applib/services/grid/GridService.java
@@ -0,0 +1,96 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT 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.isis.applib.services.grid;
+
+import org.apache.isis.applib.annotation.ActionLayout;
+import org.apache.isis.applib.annotation.CollectionLayout;
+import org.apache.isis.applib.annotation.DomainObjectLayout;
+import org.apache.isis.applib.annotation.MemberGroupLayout;
+import org.apache.isis.applib.annotation.MemberOrder;
+import org.apache.isis.applib.annotation.Programmatic;
+import org.apache.isis.applib.annotation.PropertyLayout;
+import org.apache.isis.applib.layout.component.Grid;
+
+public interface GridService {
+
+    /**
+     * Whether any persisted layout metadata (eg a <code>.layout.xml</code> file) exists for this domain class.
+     */
+    @Programmatic
+    boolean existsFor(Class<?> domainClass);
+
+    /**
+     * Returns a new instance of a {@link Grid} for the specified domain class, eg from a
+     * <code>layout.xml</code> file, else <code>null</code>.
+     */
+    @Programmatic
+    Grid load(final Class<?> domainClass);
+
+    /**
+     * Returns a default grid; eg where none can be loaded using {@link #load(Class)}.
+     */
+    @Programmatic
+    Grid defaultGridFor(Class<?> domainClass);
+
+    /**
+     * Returns a normalized grid for the domain class obtained previously using {@link #load(Class)}.
+     *
+     * <p>
+     *     If a &quot;normalized&quot; grid is persisted as the <code>layout.xml/code>, then the expectation is that
+     *     the {@link MemberOrder} and {@link MemberGroupLayout} annotations can be removed from the domain class
+     *     because the binding of properties/collections/actions will be within the XML.  However, the layout
+     *     annotations ({@link DomainObjectLayout}, {@link ActionLayout}, {@link PropertyLayout} and
+     *     {@link CollectionLayout}) (if present) will continue to be used to provide additional layout metadata.  Of
+     *     course, there is nothing to prevent the developer from extending the layout XML to also include the
+     *     layout XML (in other words moving towards a {@link #complete(Grid) complete} grid.  Metadata within the
+     *     <code>layout.xml</code> file takes precedence over any annotations.
+     * </p>
+     */
+    @Programmatic
+    Grid normalize(final Grid grid);
+
+    /**
+     * Modifies the provided {@link Grid} with additional metadata, broadly speaking corresponding to the
+     * {@link DomainObjectLayout}, {@link ActionLayout}, {@link PropertyLayout} and {@link CollectionLayout}.
+     *
+     * <p>
+     *     If a &quot;completed&quot; grid is persisted as the <code>layout.xml</code>, then there should be no need
+     *     for any of the layout annotations, nor the {@link MemberOrder} or {@link MemberGroupLayout} annotations,
+     *     to be required in the domain class itself.
+     * </p>
+     */
+    @Programmatic
+    Grid complete(Grid grid);
+
+    /**
+     * Modifies the provided {@link Grid}, removing all metadata except the basic grid structure. 
+     * 
+     * <p>
+     *     If a &quot;minimal&quot; grid is persisted as the <code>layout.xml</code>, then the expectation is that
+     *     most of the layout annotations ({@link DomainObjectLayout}, {@link ActionLayout}, {@link PropertyLayout},
+     *     {@link CollectionLayout}, but also {@link MemberOrder}) will still be retained in the domain class code.
+     *     The only annotation that can be removed and is no longer used {@link MemberGroupLayout}.
+     * </p>
+     *
+     * @param grid
+     * @return
+     */
+    @Programmatic
+    Grid minimal(Grid grid);
+
+
+}

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/applib/src/main/java/org/apache/isis/applib/services/grid/GridSystemService.java
----------------------------------------------------------------------
diff --git a/core/applib/src/main/java/org/apache/isis/applib/services/grid/GridSystemService.java b/core/applib/src/main/java/org/apache/isis/applib/services/grid/GridSystemService.java
new file mode 100644
index 0000000..c19b821
--- /dev/null
+++ b/core/applib/src/main/java/org/apache/isis/applib/services/grid/GridSystemService.java
@@ -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 org.apache.isis.applib.services.grid;
+
+import org.apache.isis.applib.annotation.Programmatic;
+import org.apache.isis.applib.layout.component.Grid;
+
+/**
+ * Provides an implementation of {@link Grid}.
+ */
+public interface GridSystemService<G extends Grid> {
+
+    /**
+     * Which grid (implementation) is defined by this service.
+     */
+    @Programmatic
+    Class<? extends Grid> gridImplementation();
+
+    @Programmatic
+    String tns();
+
+    @Programmatic
+    String schemaLocation();
+
+    @Programmatic
+    Grid defaultGrid(Class<?> domainClass);
+
+    /**
+     * Validate the grid, derive any missing object members, and overwrite any facets in the metamodel based on the
+     * layout.
+     */
+    @Programmatic
+    void normalize(G grid, Class<?> domainClass);
+
+    @Programmatic
+    void complete(G grid, Class<?> domainClass);
+
+    @Programmatic
+    void minimal(G grid, Class<?> domainClass);
+
+}

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/applib/src/main/java/org/apache/isis/applib/services/layout/GridImplementationService.java
----------------------------------------------------------------------
diff --git a/core/applib/src/main/java/org/apache/isis/applib/services/layout/GridImplementationService.java b/core/applib/src/main/java/org/apache/isis/applib/services/layout/GridImplementationService.java
deleted file mode 100644
index 9ede4ca..0000000
--- a/core/applib/src/main/java/org/apache/isis/applib/services/layout/GridImplementationService.java
+++ /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 org.apache.isis.applib.services.layout;
-
-import org.apache.isis.applib.annotation.Programmatic;
-import org.apache.isis.applib.layout.component.Grid;
-
-/**
- * Provides an implementation of {@link Grid}.
- */
-public interface GridImplementationService<G extends Grid> {
-
-    /**
-     * Which grid (implementation) is defined by this service.
-     */
-    @Programmatic
-    Class<? extends Grid> gridImplementation();
-
-    @Programmatic
-    String tns();
-
-    @Programmatic
-    String schemaLocation();
-
-    /**
-     * Validate the grid, derive any missing object members, and overwrite any facets in the metamodel based on the
-     * layout.
-     */
-    @Programmatic
-    void normalize(G grid, Class<?> domainClass);
-
-    @Programmatic
-    void complete(G grid, Class<?> domainClass);
-
-    @Programmatic
-    void minimal(G grid, Class<?> domainClass);
-
-    @Programmatic
-    Grid defaultGrid(Class<?> domainClass);
-}

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/applib/src/main/java/org/apache/isis/applib/services/layout/LayoutService.java
----------------------------------------------------------------------
diff --git a/core/applib/src/main/java/org/apache/isis/applib/services/layout/LayoutService.java b/core/applib/src/main/java/org/apache/isis/applib/services/layout/LayoutService.java
index 327993d..dac45af 100644
--- a/core/applib/src/main/java/org/apache/isis/applib/services/layout/LayoutService.java
+++ b/core/applib/src/main/java/org/apache/isis/applib/services/layout/LayoutService.java
@@ -20,78 +20,61 @@ import org.apache.isis.applib.annotation.MemberGroupLayout;
 import org.apache.isis.applib.annotation.MemberOrder;
 import org.apache.isis.applib.annotation.Programmatic;
 import org.apache.isis.applib.layout.component.Grid;
-import org.apache.isis.applib.value.Blob;
 
 public interface LayoutService {
 
-    /**
-     * Whether any <code>.layout.xml</code> file exists for this domain class, and if so then whether it is
-     * valid or invalid.
-     */
-    @Programmatic
-    boolean xmlExistsFor(Class<?> domainClass);
-
-    /**
-     * Returns a normalized grid for the domain class, either loaded from a
-     * <code>.layout.xml</code> file, else using a default specific to the
-     * grid service.
-     *
-     * <p>
-     * Normalization generally means to add in any missing properties/collections/actions so that the
-     * in-memory grid can be rendered.
-     * </p>
-     */
-    @Programmatic
-    Grid normalizedFromXmlElseDefault(Class<?> domainClass);
-
-    @Programmatic
-    Grid complete(Grid grid);
-
-    @Programmatic
-    Grid minimal(Grid grid);
-
     enum Style {
 
         /**
+         * The current layout for the domain class.
+         * <p/>
+         * <p>
+         * If a <code>layout.xml</code> exists, then the grid returned will correspond to that
+         * grid, having been {@link org.apache.isis.applib.services.grid.GridService#normalize(Grid) normalized}.  If there is no <code>layout.xml</code> file, then the grid returned will be the
+         * {@link org.apache.isis.applib.services.grid.GridService#defaultGridFor(Class) default grid},
+         * also {@link org.apache.isis.applib.services.grid.GridService#normalize(Grid) normalized}.
+         * </p>
+         */
+        CURRENT,
+        /**
          * As per {@link #NORMALIZED}, but also with all (non-null) facets for all
          * properties/collections/actions also included included in the grid.
-         *
+         * <p/>
          * <p>
-         *     The intention here is that any layout metadata annotations can be removed from the code.
+         * The intention here is that any layout metadata annotations can be removed from the code.
          * </p>
          */
         COMPLETE,
         /**
          * Default, whereby missing properties/collections/actions are added to regions,
          * and unused/empty regions are removed/trimmed.
-         *
+         * <p/>
          * <p>
-         *     It should be possible to remove any {@link MemberOrder} and {@link MemberGroupLayout} annotations but
-         *     any layout annotations would need to be retained.
+         * It should be possible to remove any {@link MemberOrder} and {@link MemberGroupLayout} annotations but
+         * any layout annotations would need to be retained.
          * </p>
          */
         NORMALIZED,
         /**
          * As per {@link #NORMALIZED}, but with no properties/collections/actions.
-         *
+         * <p/>
          * <p>
-         *     The intention here is for layout annotations that &quot;bind&quot; the properties/collections/actions
-         *     to the regions to be retained.
+         * The intention here is for layout annotations that &quot;bind&quot; the properties/collections/actions
+         * to the regions to be retained.
          * </p>
          */
         MINIMAL
     }
 
-
     /**
-     * Obtains the grid for the specified domain class.
-     *
-     * @param style - how complete the information in the returned grid should be.
+     * Obtains the serialized XML form of the layout (grid) for the specified domain class.
      */
     @Programmatic
-    Grid toGrid(final Class<?> domainClass, final Style style);
+    String toXml(Class<?> domainClass, Style style);
 
+    /**
+     * Obtains a zip file of the serialized XML of the layouts (grids) of all domain entities and view models.
+     */
     @Programmatic
-    Blob downloadLayouts(final Style style);
-
-}
+    byte[] toZip(final Style style);
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/applib/src/main/java/org/apache/isis/applib/services/layout/LayoutServiceMenu.java
----------------------------------------------------------------------
diff --git a/core/applib/src/main/java/org/apache/isis/applib/services/layout/LayoutServiceMenu.java b/core/applib/src/main/java/org/apache/isis/applib/services/layout/LayoutServiceMenu.java
index dc0a1cb..8a995cd 100644
--- a/core/applib/src/main/java/org/apache/isis/applib/services/layout/LayoutServiceMenu.java
+++ b/core/applib/src/main/java/org/apache/isis/applib/services/layout/LayoutServiceMenu.java
@@ -16,6 +16,8 @@
  */
 package org.apache.isis.applib.services.layout;
 
+import javax.activation.MimeType;
+import javax.activation.MimeTypeParseException;
 import javax.inject.Inject;
 
 import org.apache.isis.applib.IsisApplibModule;
@@ -42,6 +44,16 @@ public class LayoutServiceMenu {
     public static abstract class ActionDomainEvent extends IsisApplibModule.ActionDomainEvent<LayoutServiceMenu> {
     }
 
+    private final MimeType mimeTypeApplicationZip;
+
+    public LayoutServiceMenu() {
+        try {
+            mimeTypeApplicationZip = new MimeType("application", "zip");
+        } catch (final MimeTypeParseException ex) {
+            throw new RuntimeException(ex);
+        }
+    }
+
     public static class DownloadLayoutsDomainEvent extends ActionDomainEvent {
     }
 
@@ -56,7 +68,11 @@ public class LayoutServiceMenu {
     )
     @MemberOrder(sequence="500.400.1")
     public Blob downloadLayouts(final LayoutService.Style style) {
-        return layoutService.downloadLayouts(style);
+
+        final String fileName = "layouts." + style.name().toLowerCase() + ".zip";
+
+        final byte[] zipBytes = layoutService.toZip(style);
+        return new Blob(fileName, mimeTypeApplicationZip, zipBytes);
     }
 
     public LayoutService.Style default0DownloadLayouts() {

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/applib/src/main/java/org/apache/isis/applib/services/layout/Object_downloadLayoutXml.java
----------------------------------------------------------------------
diff --git a/core/applib/src/main/java/org/apache/isis/applib/services/layout/Object_downloadLayoutXml.java b/core/applib/src/main/java/org/apache/isis/applib/services/layout/Object_downloadLayoutXml.java
index 752aecd..0bea504 100644
--- a/core/applib/src/main/java/org/apache/isis/applib/services/layout/Object_downloadLayoutXml.java
+++ b/core/applib/src/main/java/org/apache/isis/applib/services/layout/Object_downloadLayoutXml.java
@@ -17,9 +17,6 @@
 package org.apache.isis.applib.services.layout;
 
 import javax.inject.Inject;
-import javax.xml.bind.Marshaller;
-
-import com.google.common.collect.ImmutableMap;
 
 import org.apache.isis.applib.annotation.Action;
 import org.apache.isis.applib.annotation.ActionLayout;
@@ -28,7 +25,6 @@ import org.apache.isis.applib.annotation.Mixin;
 import org.apache.isis.applib.annotation.ParameterLayout;
 import org.apache.isis.applib.annotation.RestrictTo;
 import org.apache.isis.applib.annotation.SemanticsOf;
-import org.apache.isis.applib.layout.component.Grid;
 import org.apache.isis.applib.services.jaxb.JaxbService;
 import org.apache.isis.applib.value.Clob;
 
@@ -57,12 +53,7 @@ public class Object_downloadLayoutXml {
             @ParameterLayout(named = "File name")
             final String fileName,
             final LayoutService.Style style) {
-        final Grid grid = getGrid(style);
-        final String xml = jaxbService.toXml(grid,
-                ImmutableMap.<String,Object>of(
-                        Marshaller.JAXB_SCHEMA_LOCATION,
-                        grid.getTnsAndSchemaLocation()
-                ));
+        final String xml = layoutService.toXml(object.getClass(), style);
 
         return new Clob(Util.withSuffix(fileName, style.name().toLowerCase() + ".xml"), "text/xml", xml);
     }
@@ -74,10 +65,6 @@ public class Object_downloadLayoutXml {
         return LayoutService.Style.NORMALIZED;
     }
 
-    protected Grid getGrid(final LayoutService.Style style) {
-        return layoutService.toGrid(object.getClass(), style);
-    }
-
     @Inject
     LayoutService layoutService;
 

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/object/grid/GridFacetDefault.java
----------------------------------------------------------------------
diff --git a/core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/object/grid/GridFacetDefault.java b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/object/grid/GridFacetDefault.java
index fee8c4b..6a3374c 100644
--- a/core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/object/grid/GridFacetDefault.java
+++ b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/object/grid/GridFacetDefault.java
@@ -22,7 +22,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import org.apache.isis.applib.layout.component.Grid;
-import org.apache.isis.applib.services.layout.LayoutService;
+import org.apache.isis.applib.services.grid.GridService;
 import org.apache.isis.core.metamodel.deployment.DeploymentCategory;
 import org.apache.isis.core.metamodel.facetapi.Facet;
 import org.apache.isis.core.metamodel.facetapi.FacetAbstract;
@@ -43,22 +43,22 @@ public class GridFacetDefault
 
     public static GridFacet create(
             final FacetHolder facetHolder,
-            final LayoutService layoutService,
+            final GridService gridService,
             final DeploymentCategory deploymentCategory) {
-        return new GridFacetDefault(facetHolder, layoutService, deploymentCategory);
+        return new GridFacetDefault(facetHolder, gridService, deploymentCategory);
     }
 
     private final DeploymentCategory deploymentCategory;
-    private final LayoutService layoutService;
+    private final GridService gridService;
 
     private Grid grid;
 
     private GridFacetDefault(
             final FacetHolder facetHolder,
-            final LayoutService layoutService,
+            final GridService gridService,
             final DeploymentCategory deploymentCategory) {
         super(GridFacetDefault.type(), facetHolder, Derivation.NOT_DERIVED);
-        this.layoutService = layoutService;
+        this.gridService = gridService;
         this.deploymentCategory = deploymentCategory;
     }
 
@@ -67,10 +67,20 @@ public class GridFacetDefault
             return this.grid;
         }
         final Class<?> domainClass = getSpecification().getCorrespondingClass();
-        this.grid = layoutService.normalizedFromXmlElseDefault(domainClass);
+        this.grid = load(domainClass);
+
         return this.grid;
     }
 
+    private Grid load(final Class<?> domainClass) {
+        Grid grid = gridService.load(domainClass);
+        if(grid == null) {
+            grid = gridService.defaultGridFor(domainClass);
+        }
+        gridService.normalize(grid);
+        return grid;
+    }
+
     private ObjectSpecification getSpecification() {
         return (ObjectSpecification) getFacetHolder();
     }

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/object/grid/GridFacetFactory.java
----------------------------------------------------------------------
diff --git a/core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/object/grid/GridFacetFactory.java b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/object/grid/GridFacetFactory.java
index d6e935c..c39acec 100644
--- a/core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/object/grid/GridFacetFactory.java
+++ b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/object/grid/GridFacetFactory.java
@@ -19,7 +19,7 @@ package org.apache.isis.core.metamodel.facets.object.grid;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import org.apache.isis.applib.services.layout.LayoutService;
+import org.apache.isis.applib.services.grid.GridService;
 import org.apache.isis.core.metamodel.facetapi.FacetHolder;
 import org.apache.isis.core.metamodel.facetapi.FacetUtil;
 import org.apache.isis.core.metamodel.facetapi.FeatureType;
@@ -39,12 +39,12 @@ public class GridFacetFactory extends FacetFactoryAbstract implements ServicesIn
     public void process(final ProcessClassContext processClassContext) {
         final FacetHolder facetHolder = processClassContext.getFacetHolder();
 
-        final LayoutService layoutService =
-                servicesInjector.lookupService(LayoutService.class);
+        final GridService gridService =
+                servicesInjector.lookupService(GridService.class);
 
         FacetUtil.addFacet(
                 GridFacetDefault.create(facetHolder,
-                        layoutService, getDeploymentCategory()));
+                        gridService, getDeploymentCategory()));
     }
 
     private ServicesInjector servicesInjector;

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/metamodel/src/main/java/org/apache/isis/core/metamodel/layoutmetadata/json/LayoutMetadataReaderFromJson.java
----------------------------------------------------------------------
diff --git a/core/metamodel/src/main/java/org/apache/isis/core/metamodel/layoutmetadata/json/LayoutMetadataReaderFromJson.java b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/layoutmetadata/json/LayoutMetadataReaderFromJson.java
index c394aa5..75fe978 100644
--- a/core/metamodel/src/main/java/org/apache/isis/core/metamodel/layoutmetadata/json/LayoutMetadataReaderFromJson.java
+++ b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/layoutmetadata/json/LayoutMetadataReaderFromJson.java
@@ -43,7 +43,7 @@ import org.apache.isis.applib.annotation.Render.Type;
 import org.apache.isis.applib.annotation.When;
 import org.apache.isis.applib.annotation.Where;
 import org.apache.isis.applib.filter.Filter;
-import org.apache.isis.applib.services.layout.LayoutService;
+import org.apache.isis.applib.services.grid.GridService;
 import org.apache.isis.core.commons.lang.ClassExtensions;
 import org.apache.isis.core.metamodel.facets.all.describedas.DescribedAsFacet;
 import org.apache.isis.core.metamodel.facets.all.hide.HiddenFacet;
@@ -81,10 +81,10 @@ import org.apache.isis.core.metamodel.layoutmetadata.RenderFacetRepr;
 import org.apache.isis.core.metamodel.layoutmetadata.TypicalLengthFacetRepr;
 import org.apache.isis.core.metamodel.runtimecontext.ServicesInjector;
 import org.apache.isis.core.metamodel.runtimecontext.ServicesInjectorAware;
+import org.apache.isis.core.metamodel.services.grid.fixedcols.applib.Hint;
 import org.apache.isis.core.metamodel.spec.ActionType;
 import org.apache.isis.core.metamodel.spec.ObjectSpecification;
 import org.apache.isis.core.metamodel.spec.ObjectSpecifications;
-import org.apache.isis.core.metamodel.services.grid.fixedcols.applib.Hint;
 import org.apache.isis.core.metamodel.spec.feature.Contributed;
 import org.apache.isis.core.metamodel.spec.feature.ObjectAction;
 import org.apache.isis.core.metamodel.spec.feature.ObjectAssociation;
@@ -415,8 +415,8 @@ public class LayoutMetadataReaderFromJson implements LayoutMetadataReader2, Serv
         }
 
         try {
-            final LayoutService layoutService = getLayoutService();
-            if(layoutService.xmlExistsFor(domainClass)) {
+            final GridService gridService = getGridService();
+            if(gridService.existsFor(domainClass)) {
                 blacklisted.add(domainClass);
                 return null;
             }
@@ -699,8 +699,8 @@ public class LayoutMetadataReaderFromJson implements LayoutMetadataReader2, Serv
 
 
 
-    private LayoutService getLayoutService() {
-        return servicesInjector.lookupService(LayoutService.class);
+    private GridService getGridService() {
+        return servicesInjector.lookupService(GridService.class);
     }
 
 


[2/4] isis git commit: ISIS-993: split LayoutService back out into LayoutService (API) vs GridService (SPI); rationalizing APIs; adding documentation.

Posted by da...@apache.org.
http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/LayoutServiceDefault.java
----------------------------------------------------------------------
diff --git a/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/LayoutServiceDefault.java b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/LayoutServiceDefault.java
deleted file mode 100644
index c96e662..0000000
--- a/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/LayoutServiceDefault.java
+++ /dev/null
@@ -1,434 +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.isis.core.metamodel.services.grid;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.net.URL;
-import java.nio.charset.Charset;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-
-import javax.activation.MimeType;
-import javax.activation.MimeTypeParseException;
-import javax.annotation.Nullable;
-import javax.annotation.PostConstruct;
-import javax.inject.Inject;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.Marshaller;
-
-import com.google.common.base.Function;
-import com.google.common.base.Joiner;
-import com.google.common.base.Predicate;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.FluentIterable;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.io.Resources;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.isis.applib.FatalException;
-import org.apache.isis.applib.annotation.DomainService;
-import org.apache.isis.applib.annotation.NatureOfService;
-import org.apache.isis.applib.annotation.Programmatic;
-import org.apache.isis.applib.layout.component.Grid;
-import org.apache.isis.applib.services.jaxb.JaxbService;
-import org.apache.isis.applib.services.layout.GridImplementationService;
-import org.apache.isis.applib.services.layout.LayoutService;
-import org.apache.isis.applib.value.Blob;
-import org.apache.isis.core.metamodel.deployment.DeploymentCategory;
-import org.apache.isis.core.metamodel.deployment.DeploymentCategoryAware;
-import org.apache.isis.core.metamodel.facets.object.grid.GridFacet;
-import org.apache.isis.core.metamodel.facets.object.viewmodel.ViewModelFacet;
-import org.apache.isis.core.metamodel.spec.ObjectSpecification;
-import org.apache.isis.core.metamodel.spec.SpecificationLoader;
-import org.apache.isis.core.metamodel.spec.SpecificationLoaderAware;
-import org.apache.isis.core.metamodel.spec.SpecificationLoaderSpi;
-import org.apache.isis.core.metamodel.spec.SpecificationLoaderSpiAware;
-import org.apache.isis.objectstore.jdo.metamodel.facets.object.persistencecapable.JdoPersistenceCapableFacet;
-
-@DomainService(
-        nature = NatureOfService.DOMAIN
-)
-public class LayoutServiceDefault
-        implements LayoutService, SpecificationLoaderAware, SpecificationLoaderSpiAware, DeploymentCategoryAware {
-
-    private static final Logger LOG = LoggerFactory.getLogger(LayoutServiceDefault.class);
-
-    public static final String COMMON_TNS = "http://isis.apache.org/applib/layout/component";
-    public static final String COMMON_SCHEMA_LOCATION = "http://isis.apache.org/applib/layout/component/component.xsd";
-
-    // for better logging messages (used only in prototyping mode)
-    private final Map<Class<?>, String> badXmlByClass = Maps.newHashMap();
-
-    // cache (used only in prototyping mode)
-    private final Map<String, Grid> pageByXml = Maps.newHashMap();
-
-    private List<Class<? extends Grid>> pageImplementations;
-
-    private final MimeType mimeTypeApplicationZip;
-
-
-    public LayoutServiceDefault() {
-        try {
-            mimeTypeApplicationZip = new MimeType("application", "zip");
-        } catch (final MimeTypeParseException ex) {
-            throw new RuntimeException(ex);
-        }
-    }
-
-
-    @PostConstruct
-    public void init(){
-        pageImplementations = FluentIterable.from(gridImplementationServices)
-                .transform(new Function<GridImplementationService, Class<? extends Grid>>() {
-                    @Override
-                    public Class<? extends Grid> apply(final GridImplementationService gridImplementationService) {
-                        return gridImplementationService.gridImplementation();
-                    }
-                })
-                .toList();
-    }
-
-
-    @Override
-    @Programmatic
-    public boolean xmlExistsFor(final Class<?> domainClass) {
-        final URL resource = Resources.getResource(domainClass, resourceNameFor(domainClass));
-        return resource != null;
-    }
-
-    @Override
-    public Grid normalizedFromXmlElseDefault(final Class<?> domainClass) {
-        Grid grid = fromXml(domainClass);
-        if(grid == null) {
-            grid = defaultGrid(domainClass);
-        }
-        normalize(grid);
-        return grid;
-    }
-
-    protected Grid fromXml(Class<?> domainClass) {
-
-        final String resourceName = resourceNameFor(domainClass);
-        final String xml;
-        try {
-            xml = resourceContentOf(domainClass, resourceName);
-        } catch (IOException | IllegalArgumentException ex) {
-
-            final String message = String .format(
-                    "Failed to locate file %s (relative to %s.class); ex: %s)",
-                    resourceName, domainClass.getName(), ex.getMessage());
-
-            LOG.debug(message);
-            return null;
-        }
-
-        if(!deploymentCategory.isProduction()) {
-            final Grid grid = pageByXml.get(xml);
-            if(grid != null) {
-                return grid;
-            }
-
-            final String badXml = badXmlByClass.get(domainClass);
-            if(badXml != null) {
-                if(Objects.equals(xml, badXml)) {
-                    // seen this before and already logged; just quit
-                    return null;
-                } else {
-                    // this different XML might be good
-                    badXmlByClass.remove(domainClass);
-                }
-            }
-        }
-
-        try {
-            // all known implementations of Page
-            final JAXBContext context = JAXBContext.newInstance(pageImplementations.toArray(new Class[0]));
-
-            final Grid grid = (Grid) jaxbService.fromXml(context, xml);
-            grid.setDomainClass(domainClass);
-            if(!deploymentCategory.isProduction()) {
-                pageByXml.put(xml, grid);
-            }
-            return grid;
-        } catch(Exception ex) {
-
-            if(!deploymentCategory.isProduction()) {
-                // save fact that this was bad XML, so that we don't log again if called next time
-                badXmlByClass.put(domainClass, xml);
-            }
-
-            // note that we don't blacklist if the file exists but couldn't be parsed;
-            // the developer might fix so we will want to retry.
-            final String message = "Failed to parse " + resourceName + " file (" + ex.getMessage() + ")";
-            LOG.warn(message);
-
-            return null;
-        }
-    }
-
-    protected Grid defaultGrid(Class<?> domainClass) {
-
-        for (GridImplementationService gridImplementationService : gridNormalizerServices()) {
-            Grid grid = gridImplementationService.defaultGrid(domainClass);
-            if(grid != null) {
-                return grid;
-            }
-        }
-        throw new IllegalStateException("No GridNormalizerService available to create grid for '" + domainClass.getName() + "'");
-    }
-
-    protected Grid normalize(final Grid grid) {
-
-        // if have .layout.json and then add a .layout.xml without restarting, then note that the .layout.xml won't
-        // be picked up.  To do so would require normalizing repeatedly in order to trample over the .layout.json's
-        // original facets
-        if(grid.isNormalized()) {
-            return grid;
-        }
-
-        final Class<?> domainClass = grid.getDomainClass();
-
-        for (GridImplementationService gridImplementationService : gridNormalizerServices()) {
-            gridImplementationService.normalize(grid, domainClass);
-        }
-
-        final String tnsAndSchemaLocation = tnsAndSchemaLocation(grid);
-        grid.setTnsAndSchemaLocation(tnsAndSchemaLocation);
-
-        grid.setNormalized(true);
-
-        return grid;
-    }
-
-    /**
-     * Not public API, exposed only for testing.
-     */
-    @Programmatic
-    public String tnsAndSchemaLocation(final Grid grid) {
-        final List<String> parts = Lists.newArrayList();
-        parts.add(COMMON_TNS);
-        parts.add(COMMON_SCHEMA_LOCATION);
-        FluentIterable.from(gridImplementationServices)
-                .filter(new Predicate<GridImplementationService>() {
-                    @Override
-                    public boolean apply(final GridImplementationService gridImplementationService) {
-                        final Class<? extends Grid> gridImpl = gridImplementationService.gridImplementation();
-                        return gridImpl.isAssignableFrom(grid.getClass());
-                    }
-                })
-                .transform(new Function<GridImplementationService, Void>() {
-                    @Nullable @Override
-                    public Void apply(final GridImplementationService gridImplementationService) {
-                        parts.add(gridImplementationService.tns());
-                        parts.add(gridImplementationService.schemaLocation());
-                        return null;
-                    }
-                });
-        return Joiner.on(" ").join(parts);
-    }
-
-    @Override
-    @Programmatic
-    public Grid complete(final Grid grid) {
-
-        final Class<?> domainClass = grid.getDomainClass();
-        for (GridImplementationService gridImplementationService : gridNormalizerServices()) {
-            gridImplementationService.complete(grid, domainClass);
-        }
-
-        return grid;
-    }
-
-    @Override
-    @Programmatic
-    public Grid minimal(final Grid grid) {
-
-        final Class<?> domainClass = grid.getDomainClass();
-        for (GridImplementationService gridImplementationService : gridNormalizerServices()) {
-            gridImplementationService.minimal(grid, domainClass);
-        }
-
-        return grid;
-    }
-
-
-    private static String resourceContentOf(final Class<?> cls, final String resourceName) throws IOException {
-        final URL url = Resources.getResource(cls, resourceName);
-        return Resources.toString(url, Charset.defaultCharset());
-    }
-
-    private String resourceNameFor(final Class<?> domainClass) {
-        return domainClass.getSimpleName() + ".layout.xml";
-    }
-
-
-    @Override
-    public Grid toGrid(final Class<?> domainClass, final Style style) {
-        if (style == Style.NORMALIZED) {
-            final ObjectSpecification objectSpec = specificationLookup.loadSpecification(domainClass);
-            final GridFacet facet = objectSpec.getFacet(GridFacet.class);
-            return facet != null? facet.getGrid(): null;
-        }
-
-        // don't use the grid from the facet, because it will be modified subsequently.
-        final Grid grid = layoutService.normalizedFromXmlElseDefault(domainClass);
-        if (style == Style.COMPLETE) {
-            return complete(grid);
-        }
-        if (style == Style.MINIMAL) {
-            return minimal(grid);
-        }
-        throw new IllegalArgumentException("unsupported style");
-    }
-
-    ////////////////////////////////////////////////////////
-
-    private List<GridImplementationService<?>> filteredGridImplementationServices;
-
-    /**
-     * For all of the available {@link GridImplementationService}s available, return only the first one for any that
-     * are for the same grid implementation.
-     *
-     * <p>
-     *   This allows default implementations (eg for bootstrap3) to be overridden while also allowing for the more
-     *   general idea of multiple implementations.
-     * </p>
-     */
-    @Programmatic
-    protected List<GridImplementationService<?>> gridNormalizerServices() {
-
-        if (filteredGridImplementationServices == null) {
-            List<GridImplementationService<?>> services = Lists.newArrayList();
-
-            for (GridImplementationService gridImplementationService : this.gridImplementationServices) {
-                final Class gridImplementation = gridImplementationService.gridImplementation();
-                final boolean notSeenBefore = FluentIterable.from(services).filter(new Predicate<GridImplementationService<?>>() {
-                    @Override public boolean apply(@Nullable final GridImplementationService<?> gridNormalizerService) {
-                        return gridNormalizerService.gridImplementation() == gridImplementation;
-                    }
-                }).isEmpty();
-                if(notSeenBefore) {
-                    services.add(gridImplementationService);
-                }
-            }
-
-            filteredGridImplementationServices = services;
-
-        }
-        return filteredGridImplementationServices;
-    }
-
-    ////////////////////////////////////////////////////////
-
-
-    //region > injected dependencies
-
-    private SpecificationLoader specificationLookup;
-
-    @Override
-    public void setSpecificationLoader(final SpecificationLoader specificationLookup) {
-        this.specificationLookup = specificationLookup;
-    }
-
-    private DeploymentCategory deploymentCategory;
-
-    @Override
-    public void setDeploymentCategory(final DeploymentCategory deploymentCategory) {
-        this.deploymentCategory = deploymentCategory;
-    }
-
-    @Inject
-    JaxbService jaxbService;
-
-    @Inject
-    List<GridImplementationService> gridImplementationServices;
-    //endregion
-
-
-
-
-    @Programmatic
-    public Blob downloadLayouts(final LayoutService.Style style) {
-        final Collection<ObjectSpecification> allSpecs = specificationLoader.allSpecifications();
-        final Collection<ObjectSpecification> domainObjectSpecs = Collections2
-                .filter(allSpecs, new Predicate<ObjectSpecification>(){
-                    @Override
-                    public boolean apply(final ObjectSpecification input) {
-                        return  !input.isAbstract() &&
-                                (input.containsDoOpFacet(JdoPersistenceCapableFacet.class) ||
-                                        input.containsDoOpFacet(ViewModelFacet.class));
-                    }});
-        try {
-            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
-            final ZipOutputStream zos = new ZipOutputStream(baos);
-            final OutputStreamWriter writer = new OutputStreamWriter(zos);
-            for (final ObjectSpecification objectSpec : domainObjectSpecs) {
-                final Class<?> domainClass = objectSpec.getCorrespondingClass();
-                final Grid grid = layoutService.toGrid(domainClass, style);
-                if(grid != null) {
-                    zos.putNextEntry(new ZipEntry(zipEntryNameFor(objectSpec)));
-                    final String xml = jaxbService.toXml(grid,
-                            ImmutableMap.<String,Object>of(
-                                    Marshaller.JAXB_SCHEMA_LOCATION,
-                                    grid.getTnsAndSchemaLocation()
-                            ));
-                    writer.write(xml);
-                    writer.flush();
-                    zos.closeEntry();
-                }
-            }
-            writer.close();
-            final String fileName = "layouts." + style.name().toLowerCase() + ".zip";
-            return new Blob(fileName, mimeTypeApplicationZip, baos.toByteArray());
-        } catch (final IOException ex) {
-            throw new FatalException("Unable to create zip of layouts", ex);
-        }
-    }
-
-    private static String zipEntryNameFor(final ObjectSpecification objectSpec) {
-        final String fqn = objectSpec.getFullIdentifier();
-        return fqn.replace(".", File.separator)+".layout.xml";
-    }
-
-
-    // //////////////////////////////////////
-
-    @Inject
-    LayoutService layoutService;
-
-
-    private SpecificationLoaderSpi specificationLoader;
-
-    @Programmatic
-    @Override
-    public void setSpecificationLoaderSpi(final SpecificationLoaderSpi specificationLoader) {
-        this.specificationLoader = specificationLoader;
-    }
-
-
-}

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/bootstrap3/GridImplementationServiceBS3.java
----------------------------------------------------------------------
diff --git a/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/bootstrap3/GridImplementationServiceBS3.java b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/bootstrap3/GridImplementationServiceBS3.java
deleted file mode 100644
index 5cac95e..0000000
--- a/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/bootstrap3/GridImplementationServiceBS3.java
+++ /dev/null
@@ -1,674 +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.isis.core.metamodel.services.grid.bootstrap3;
-
-import java.util.Arrays;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.function.Consumer;
-
-import javax.annotation.Nullable;
-
-import com.google.common.base.Function;
-import com.google.common.base.Predicates;
-import com.google.common.base.Strings;
-import com.google.common.collect.FluentIterable;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-
-import org.apache.isis.applib.annotation.ActionLayout;
-import org.apache.isis.applib.annotation.DomainService;
-import org.apache.isis.applib.annotation.MemberGroupLayout;
-import org.apache.isis.applib.annotation.NatureOfService;
-import org.apache.isis.applib.annotation.Programmatic;
-import org.apache.isis.applib.layout.component.ActionLayoutData;
-import org.apache.isis.applib.layout.component.ActionLayoutDataOwner;
-import org.apache.isis.applib.layout.component.CollectionLayoutData;
-import org.apache.isis.applib.layout.component.DomainObjectLayoutData;
-import org.apache.isis.applib.layout.component.FieldSet;
-import org.apache.isis.applib.layout.component.Grid;
-import org.apache.isis.applib.layout.component.PropertyLayoutData;
-import org.apache.isis.applib.layout.grid.bootstrap3.BS3Col;
-import org.apache.isis.applib.layout.grid.bootstrap3.BS3Grid;
-import org.apache.isis.applib.layout.grid.bootstrap3.BS3Row;
-import org.apache.isis.applib.layout.grid.bootstrap3.BS3Tab;
-import org.apache.isis.applib.layout.grid.bootstrap3.BS3TabGroup;
-import org.apache.isis.applib.layout.grid.bootstrap3.Size;
-import org.apache.isis.core.metamodel.facets.actions.position.ActionPositionFacet;
-import org.apache.isis.core.metamodel.facets.members.order.MemberOrderFacet;
-import org.apache.isis.core.metamodel.facets.members.order.annotprop.MemberOrderFacetAnnotation;
-import org.apache.isis.core.metamodel.facets.object.membergroups.MemberGroupLayoutFacet;
-import org.apache.isis.core.metamodel.services.grid.GridImplementationServiceAbstract;
-import org.apache.isis.core.metamodel.spec.ObjectSpecification;
-import org.apache.isis.core.metamodel.spec.feature.Contributed;
-import org.apache.isis.core.metamodel.spec.feature.ObjectAction;
-import org.apache.isis.core.metamodel.spec.feature.ObjectAssociation;
-import org.apache.isis.core.metamodel.spec.feature.ObjectMember;
-import org.apache.isis.core.metamodel.spec.feature.OneToManyAssociation;
-import org.apache.isis.core.metamodel.spec.feature.OneToOneAssociation;
-
-@DomainService(
-        nature = NatureOfService.DOMAIN
-)
-public class GridImplementationServiceBS3 extends GridImplementationServiceAbstract<BS3Grid> {
-
-    public static final String TNS = "http://isis.apache.org/applib/layout/grid/bootstrap3";
-    public static final String SCHEMA_LOCATION = "http://isis.apache.org/applib/layout/grid/bootstrap3/bootstrap3.xsd";
-
-    public GridImplementationServiceBS3() {
-        super(BS3Grid.class, TNS, SCHEMA_LOCATION);
-    }
-
-
-    @Programmatic
-    @Override
-    public Grid defaultGrid(final Class<?> domainClass) {
-        final BS3Grid bs3Grid = new BS3Grid();
-
-        final ObjectSpecification objectSpec = specificationLookup.loadSpecification(domainClass);
-        bs3Grid.setDomainClass(domainClass);
-
-        final BS3Row headerRow = new BS3Row();
-        bs3Grid.getRows().add(headerRow);
-        final BS3Col headerRowCol = new BS3Col();
-        headerRowCol.setSpan(12);
-        headerRowCol.setUnreferencedActions(true);
-        headerRowCol.setDomainObject(new DomainObjectLayoutData());
-        headerRow.getCols().add(headerRowCol);
-
-        final BS3Row propsRow = new BS3Row();
-        bs3Grid.getRows().add(propsRow);
-
-        final MemberGroupLayoutFacet memberGroupLayoutFacet =
-                objectSpec.getFacet(MemberGroupLayoutFacet.class);
-        if(memberGroupLayoutFacet != null) {
-            // if have @MemberGroupLayout (or equally, a .layout.json file)
-            final MemberGroupLayout.ColumnSpans columnSpans = memberGroupLayoutFacet.getColumnSpans();
-            addFieldSetsToColumn(propsRow, columnSpans.getLeft(), memberGroupLayoutFacet.getLeft(), true);
-            addFieldSetsToColumn(propsRow, columnSpans.getMiddle(), memberGroupLayoutFacet.getMiddle(), false);
-            addFieldSetsToColumn(propsRow, columnSpans.getRight(), memberGroupLayoutFacet.getRight(), false);
-
-            final BS3Col col = new BS3Col();
-            final int collectionSpan = columnSpans.getCollections();
-            col.setUnreferencedCollections(true);
-            col.setSpan(collectionSpan > 0? collectionSpan: 12);
-            propsRow.getCols().add(col);
-
-            // will already be sorted per @MemberOrder
-            final List<OneToManyAssociation> collections = objectSpec.getCollections(Contributed.INCLUDED);
-            for (OneToManyAssociation collection : collections) {
-                col.getCollections().add(new CollectionLayoutData(collection.getId()));
-            }
-        } else {
-
-            // if no layout hints other than @MemberOrder
-            addFieldSetsToColumn(propsRow, 4, Arrays.asList("General"), true);
-
-            final BS3Col col = new BS3Col();
-            col.setUnreferencedCollections(true);
-            col.setSpan(12);
-            propsRow.getCols().add(col);
-        }
-        return bs3Grid;
-    }
-
-    static void addFieldSetsToColumn(
-            final BS3Row propsRow,
-            final int span,
-            final List<String> memberGroupNames,
-            final boolean unreferencedProperties) {
-
-        if(span > 0 || unreferencedProperties) {
-            final BS3Col col = new BS3Col();
-            col.setSpan(span); // in case we are here because of 'unreferencedProperties' needs setting
-            propsRow.getCols().add(col);
-            final List<String> leftMemberGroups = memberGroupNames;
-            for (String memberGroup : leftMemberGroups) {
-                final FieldSet fieldSet = new FieldSet();
-                fieldSet.setName(memberGroup);
-                // fieldSet's id will be derived from the name later
-                // during normalization phase.
-                if(unreferencedProperties && col.getFieldSets().isEmpty()) {
-                    fieldSet.setUnreferencedProperties(true);
-                }
-                col.getFieldSets().add(fieldSet);
-            }
-        }
-    }
-
-    // //////////////////////////////////////
-
-    /**
-     * Mandatory hook method defined in {@link GridImplementationServiceAbstract superclass}, called by {@link #normalize(Grid, Class)}.
-     */
-    @Override
-    protected boolean validateAndDerive(
-            final Grid grid,
-            final Map<String, OneToOneAssociation> oneToOneAssociationById,
-            final Map<String, OneToManyAssociation> oneToManyAssociationById,
-            final Map<String, ObjectAction> objectActionById,
-            final ObjectSpecification objectSpec) {
-
-        final BS3Grid bs3Grid = (BS3Grid) grid;
-
-        final LinkedHashMap<String, PropertyLayoutData> propertyLayoutDataById = bs3Grid.getAllPropertiesById();
-        final LinkedHashMap<String, CollectionLayoutData> collectionLayoutDataById = bs3Grid.getAllCollectionsById();
-        final LinkedHashMap<String, ActionLayoutData> actionLayoutDataById = bs3Grid.getAllActionsById();
-
-
-        // find all row and col ids
-        // ensure that all Ids are different
-
-        final List<String> gridIds = Lists.newArrayList();
-        final LinkedHashMap<String, BS3Row> rowIds = Maps.newLinkedHashMap();
-        final LinkedHashMap<String, BS3Col> colIds = Maps.newLinkedHashMap();
-        final LinkedHashMap<String, FieldSet> fieldSetIds = Maps.newLinkedHashMap();
-
-        final AtomicReference<Boolean> duplicateIdDetected = new AtomicReference<>(false);
-
-        bs3Grid.visit(new BS3Grid.VisitorAdapter(){
-            @Override
-            public void visit(final BS3Row bs3Row) {
-                final String id = bs3Row.getId();
-                if(id == null) {
-                    return;
-                }
-                if(gridIds.contains(id)) {
-                    bs3Row.setMetadataError("There is another element in the grid with this id");
-                    duplicateIdDetected.set(true);
-                    return;
-                }
-                rowIds.put(id, bs3Row);
-                gridIds.add(id);
-            }
-
-            @Override
-            public void visit(final BS3Col bs3Col) {
-                final String id = bs3Col.getId();
-                if(id == null) {
-                    return;
-                }
-                if(gridIds.contains(id)) {
-                    bs3Col.setMetadataError("There is another element in the grid with this id");
-                    duplicateIdDetected.set(true);
-                    return;
-                }
-                colIds.put(id, bs3Col);
-                gridIds.add(id);
-            }
-
-            @Override
-            public void visit(final FieldSet fieldSet) {
-                String id = fieldSet.getId();
-                if(id == null) {
-                    final String name = fieldSet.getName();
-                    fieldSet.setId(id = asId(name));
-                }
-                if(gridIds.contains(id)) {
-                    fieldSet.setMetadataError("There is another element in the grid with this id");
-                    duplicateIdDetected.set(true);
-                    return;
-                }
-                fieldSetIds.put(id, fieldSet);
-                gridIds.add(id);
-            }
-        });
-
-        if(duplicateIdDetected.get()) {
-            return false;
-        }
-
-
-        // ensure that there is exactly one col with the
-        // unreferencedActions, unreferencedProperties and unreferencedCollections attribute set.
-
-        final AtomicReference<BS3Col> colForUnreferencedActionsRef = new AtomicReference<>();
-        final AtomicReference<BS3Col> colForUnreferencedCollectionsRef = new AtomicReference<>();
-        final AtomicReference<FieldSet> fieldSetForUnreferencedActionsRef = new AtomicReference<>();
-        final AtomicReference<FieldSet> fieldSetForUnreferencedPropertiesRef = new AtomicReference<>();
-        final AtomicReference<BS3TabGroup> tabGroupForUnreferencedCollectionsRef = new AtomicReference<>();
-
-        bs3Grid.visit(new BS3Grid.VisitorAdapter(){
-
-            @Override
-            public void visit(final BS3Col bs3Col) {
-                if(isSet(bs3Col.isUnreferencedActions())) {
-                    if(colForUnreferencedActionsRef.get() != null) {
-                        bs3Col.setMetadataError("More than one col with 'unreferencedActions' attribute set");
-                    } else if(fieldSetForUnreferencedActionsRef.get() != null) {
-                        bs3Col.setMetadataError("Already found a fieldset with 'unreferencedActions' attribute set");
-                    } else {
-                        colForUnreferencedActionsRef.set(bs3Col);
-                    }
-                }
-                if(isSet(bs3Col.isUnreferencedCollections())) {
-                    if(colForUnreferencedCollectionsRef.get() != null) {
-                        bs3Col.setMetadataError("More than one col with 'unreferencedCollections' attribute set");
-                    } else if(tabGroupForUnreferencedCollectionsRef.get() != null) {
-                        bs3Col.setMetadataError("Already found a tabgroup with 'unreferencedCollections' attribute set");
-                    } else {
-                        colForUnreferencedCollectionsRef.set(bs3Col);
-                    }
-                }
-            }
-
-            @Override
-            public void visit(final FieldSet fieldSet) {
-                if(isSet(fieldSet.isUnreferencedActions())) {
-                    if(fieldSetForUnreferencedActionsRef.get() != null) {
-                        fieldSet.setMetadataError("More than one fieldset with 'unreferencedActions' attribute set");
-                    } else if(colForUnreferencedActionsRef.get() != null) {
-                        fieldSet.setMetadataError("Already found a column with 'unreferencedActions' attribute set");
-                    } else {
-                        fieldSetForUnreferencedActionsRef.set(fieldSet);
-                    }
-                }
-                if(isSet(fieldSet.isUnreferencedProperties())) {
-                    if(fieldSetForUnreferencedPropertiesRef.get() != null) {
-                        fieldSet.setMetadataError("More than one col with 'unreferencedProperties' attribute set");
-                    } else {
-                        fieldSetForUnreferencedPropertiesRef.set(fieldSet);
-                    }
-                }
-            }
-
-            @Override
-            public void visit(final BS3TabGroup bs3TabGroup) {
-                if(isSet(bs3TabGroup.isUnreferencedCollections())) {
-                    if(tabGroupForUnreferencedCollectionsRef.get() != null) {
-                        bs3TabGroup.setMetadataError("More than one tabgroup with 'unreferencedCollections' attribute set");
-                    } else if(colForUnreferencedCollectionsRef.get() != null) {
-                        bs3TabGroup.setMetadataError("Already found a column with 'unreferencedCollections' attribute set");
-                    } else {
-                        tabGroupForUnreferencedCollectionsRef.set(bs3TabGroup);
-                    }
-                }
-            }
-        });
-
-        if(colForUnreferencedActionsRef.get() == null && fieldSetForUnreferencedActionsRef.get() == null) {
-            bs3Grid.getMetadataErrors().add("No column and also no fieldset found with the 'unreferencedActions' attribute set");
-        }
-        if(fieldSetForUnreferencedPropertiesRef.get() == null) {
-            bs3Grid.getMetadataErrors().add("No fieldset found with the 'unreferencedProperties' attribute set");
-        }
-        if(colForUnreferencedCollectionsRef.get() == null && tabGroupForUnreferencedCollectionsRef.get() == null) {
-            bs3Grid.getMetadataErrors().add("No column and also no tabgroup found with the 'unreferencedCollections' attribute set");
-        }
-
-        if(     colForUnreferencedActionsRef.get() == null && fieldSetForUnreferencedActionsRef.get() == null ||
-                fieldSetForUnreferencedPropertiesRef.get() == null ||
-                colForUnreferencedCollectionsRef.get() == null && tabGroupForUnreferencedCollectionsRef.get() == null) {
-            return false;
-        }
-
-        // add missing properties will be added to the first fieldset of the specified column
-        final Tuple<List<String>> propertyIdTuple =
-                surplusAndMissing(propertyLayoutDataById.keySet(),  oneToOneAssociationById.keySet());
-        final List<String> surplusPropertyIds = propertyIdTuple.first;
-        final List<String> missingPropertyIds = propertyIdTuple.second;
-
-        for (String surplusPropertyId : surplusPropertyIds) {
-            propertyLayoutDataById.get(surplusPropertyId).setMetadataError("No such property");
-        }
-
-        // catalog which associations are bound to an existing field set
-        // so that (below) we can determine which missing property ids are not unbound vs which should be included
-        // in the fieldset that they are bound to.
-        final Map<String, Set<String>> boundAssociationIdsByFieldSetId = Maps.newHashMap();
-
-        // all those explicitly in the grid
-        for (FieldSet fieldSet : fieldSetIds.values()) {
-            final String fieldSetId = fieldSet.getId();
-            Set<String> boundAssociationIds = boundAssociationIdsByFieldSetId.get(fieldSetId);
-            if(boundAssociationIds == null) {
-                boundAssociationIds = Sets.newLinkedHashSet();
-                boundAssociationIds.addAll(
-                        FluentIterable.from(fieldSet.getProperties()).transform(
-                                new Function<PropertyLayoutData, String>() {
-                                    @Override
-                                    public String apply(@Nullable final PropertyLayoutData propertyLayoutData) {
-                                        return propertyLayoutData.getId();
-                                    }
-                                }).toList());
-                boundAssociationIdsByFieldSetId.put(fieldSetId, boundAssociationIds);
-            }
-        }
-        // along with any specified by existing metadata
-        for (OneToOneAssociation otoa : oneToOneAssociationById.values()) {
-            final MemberOrderFacet memberOrderFacet = otoa.getFacet(MemberOrderFacet.class);
-            if(memberOrderFacet != null) {
-                final String id = asId(memberOrderFacet.name());
-                if(fieldSetIds.containsKey(id)) {
-                    Set<String> boundAssociationIds = boundAssociationIdsByFieldSetId.get(id);
-                    if(boundAssociationIds == null) {
-                        boundAssociationIds = Sets.newLinkedHashSet();
-                        boundAssociationIdsByFieldSetId.put(id, boundAssociationIds);
-                    }
-                    boundAssociationIds.add(otoa.getId());
-                }
-            }
-        }
-
-        if(!missingPropertyIds.isEmpty()) {
-
-            final List<String> unboundPropertyIds = Lists.newArrayList(missingPropertyIds);
-
-            for (final String fieldSetId : boundAssociationIdsByFieldSetId.keySet()) {
-                final Set<String> boundPropertyIds = boundAssociationIdsByFieldSetId.get(fieldSetId);
-                unboundPropertyIds.removeAll(boundPropertyIds);
-            }
-
-            for (final String fieldSetId : boundAssociationIdsByFieldSetId.keySet()) {
-                final FieldSet fieldSet = fieldSetIds.get(fieldSetId);
-                final Set<String> associationIds =
-                        boundAssociationIdsByFieldSetId.get(fieldSetId);
-
-                final List<OneToOneAssociation> associations = Lists.newArrayList(
-                        FluentIterable.from(associationIds)
-                        .transform(new Function<String, OneToOneAssociation>() {
-                            @Nullable @Override public OneToOneAssociation apply(final String propertyId) {
-                                return oneToOneAssociationById.get(propertyId);
-                            }
-                        })
-                        .filter(Predicates.<OneToOneAssociation>notNull())
-                );
-
-                associations.sort(ObjectAssociation.Comparators.byMemberOrderSequence());
-                addPropertiesTo(fieldSet,
-                        FluentIterable.from(associations)
-                                      .transform(ObjectAssociation.Functions.toId())
-                                      .toList(),
-                        propertyLayoutDataById);
-            }
-
-            if(!unboundPropertyIds.isEmpty()) {
-                final FieldSet fieldSet = fieldSetForUnreferencedPropertiesRef.get();
-                if(fieldSet != null) {
-                    addPropertiesTo(fieldSet, unboundPropertyIds, propertyLayoutDataById);
-                }
-            }
-        }
-
-        // any missing collections will be added as tabs to a new TabGroup in the specified column
-        final Tuple<List<String>> collectionIdTuple =
-                surplusAndMissing(collectionLayoutDataById.keySet(), oneToManyAssociationById.keySet());
-        final List<String> surplusCollectionIds = collectionIdTuple.first;
-        final List<String> missingCollectionIds = collectionIdTuple.second;
-
-        for (String surplusCollectionId : surplusCollectionIds) {
-            collectionLayoutDataById.get(surplusCollectionId).setMetadataError("No such collection");
-        }
-
-        if(!missingCollectionIds.isEmpty()) {
-            List<OneToManyAssociation> sortedCollections = Lists.newArrayList(
-                    FluentIterable.from(missingCollectionIds)
-                    .transform(new Function<String, OneToManyAssociation>() {
-                        @Nullable @Override public OneToManyAssociation apply(@Nullable final String collectionId) {
-                            return oneToManyAssociationById.get(collectionId);
-                        }
-                    })
-                    .toSortedList(ObjectMember.Comparators.byMemberOrderSequence())
-
-            );
-            final ImmutableList<String> sortedMissingCollectionIds = FluentIterable.from(sortedCollections)
-                    .transform(ObjectAssociation.Functions.toId()).toList();
-            final BS3TabGroup bs3TabGroup = tabGroupForUnreferencedCollectionsRef.get();
-            if(bs3TabGroup != null) {
-                addCollectionsTo(bs3TabGroup, sortedMissingCollectionIds, objectSpec);
-            } else {
-                final BS3Col bs3Col = colForUnreferencedCollectionsRef.get();
-                if(bs3Col != null) {
-                    addCollectionsTo(bs3Col, sortedMissingCollectionIds, collectionLayoutDataById);
-                }
-            }
-        }
-
-        // any missing actions will be added as actions in the specified column
-        final Tuple<List<String>> actionIdTuple =
-                surplusAndMissing(actionLayoutDataById.keySet(), objectActionById.keySet());
-        final List<String> surplusActionIds = actionIdTuple.first;
-        final List<String> possiblyMissingActionIds = actionIdTuple.second;
-
-        final List<String> associatedActionIds = Lists.newArrayList();
-
-        List<ObjectAction> sortedPossiblyMissingActions = Lists.newArrayList(
-                FluentIterable.from(possiblyMissingActionIds)
-                        .transform(new Function<String, ObjectAction>() {
-                            @Nullable @Override public ObjectAction apply(@Nullable final String actionId) {
-                                return objectActionById.get(actionId);
-                            }
-                        })
-                        .toSortedList(ObjectMember.Comparators.byMemberOrderSequence()));
-
-        List<String> sortedPossiblyMissingActionIds =
-                FluentIterable.from(sortedPossiblyMissingActions)
-                .transform(ObjectMember.Functions.getId())
-                .toList();
-
-            FluentIterable.from(sortedPossiblyMissingActionIds)
-                .forEach(
-                        new Consumer<String>() {
-                            @Override
-                            public void accept(final String actionId) {
-                                final ObjectAction oa = objectActionById.get(actionId);
-                                final MemberOrderFacet memberOrderFacet = oa.getFacet(MemberOrderFacet.class);
-                                if(memberOrderFacet == null) {
-                                    return;
-                                }
-                                final String memberOrderName = memberOrderFacet.name();
-                                if (memberOrderName == null) {
-                                    return;
-                                }
-                                final String id = asId(memberOrderName);
-
-                                if (oneToOneAssociationById.containsKey(id)) {
-                                    associatedActionIds.add(actionId);
-
-                                    if(!(memberOrderFacet instanceof MemberOrderFacetAnnotation)) {
-                                        // if binding not via annotation, then explicitly bind this
-                                        // action to the property
-                                        final PropertyLayoutData propertyLayoutData = propertyLayoutDataById.get(id);
-                                        final ActionLayoutData actionLayoutData = new ActionLayoutData(actionId);
-
-                                        final ActionPositionFacet actionPositionFacet = oa.getFacet(ActionPositionFacet.class);
-                                        final ActionLayoutDataOwner owner;
-                                        final ActionLayout.Position position;
-                                        if(actionPositionFacet != null) {
-                                            position = actionPositionFacet.position();
-                                            owner = position == ActionLayout.Position.PANEL ||
-                                                    position == ActionLayout.Position.PANEL_DROPDOWN
-                                                        ? propertyLayoutData.getOwner()
-                                                        : propertyLayoutData;
-                                        } else {
-                                            position = ActionLayout.Position.BELOW;
-                                            owner = propertyLayoutData;
-                                        }
-                                        actionLayoutData.setPosition(position);
-                                        addActionTo(owner, actionLayoutData);
-                                    }
-
-                                    return;
-                                }
-                                if (oneToManyAssociationById.containsKey(id)) {
-                                    associatedActionIds.add(actionId);
-
-                                    if(!(memberOrderFacet instanceof MemberOrderFacetAnnotation)) {
-                                        // if binding not via annotation, then explicitly bind this
-                                        // action to the property
-                                        final CollectionLayoutData collectionLayoutData = collectionLayoutDataById.get(id);
-                                        final ActionLayoutData actionLayoutData = new ActionLayoutData(actionId);
-                                        addActionTo(collectionLayoutData, actionLayoutData);
-                                    }
-                                    return;
-                                }
-                                // if the @MemberOrder for the action references a field set (that has bound
-                                // associations), then don't mark it as missing, butinstead explicitly add it to the
-                                // list of actions of that fieldset.
-                                final Set<String> boundAssociationIds = boundAssociationIdsByFieldSetId.get(id);
-                                if(boundAssociationIds != null && !boundAssociationIds.isEmpty()) {
-
-                                    associatedActionIds.add(actionId);
-
-                                    final ActionLayoutData actionLayoutData = new ActionLayoutData(actionId);
-
-                                    actionLayoutData.setPosition(ActionLayout.Position.PANEL_DROPDOWN);
-                                    final FieldSet fieldSet = fieldSetIds.get(id);
-                                    addActionTo(fieldSet, actionLayoutData);
-                                    return;
-                                }
-                            }
-                        });
-
-        // ... the missing actions are those in the second tuple, excluding those associated (via @MemberOrder#name)
-        // to a property or collection.
-        final List<String> missingActionIds = Lists.newArrayList(sortedPossiblyMissingActionIds);
-        missingActionIds.removeAll(associatedActionIds);
-
-        for (String surplusActionId : surplusActionIds) {
-            actionLayoutDataById.get(surplusActionId).setMetadataError("No such action");
-        }
-
-        if(!missingActionIds.isEmpty()) {
-            final BS3Col bs3Col = colForUnreferencedActionsRef.get();
-            if(bs3Col != null) {
-                addActionsTo(bs3Col, missingActionIds, actionLayoutDataById);
-            } else {
-                final FieldSet fieldSet = fieldSetForUnreferencedActionsRef.get();
-                if(fieldSet != null) {
-                    addActionsTo(fieldSet, missingActionIds, actionLayoutDataById);
-                }
-            }
-        }
-
-        return true;
-    }
-
-    protected void addPropertiesTo(
-            final FieldSet fieldSet,
-            final List<String> propertyIds,
-            final LinkedHashMap<String, PropertyLayoutData> propertyLayoutDataById) {
-        final ImmutableList<String> existingIds = FluentIterable
-                .from(fieldSet.getProperties())
-                .transform(new Function<PropertyLayoutData, String>() {
-                    @Nullable
-                    @Override
-                    public String apply(@Nullable final PropertyLayoutData propertyLayoutData) {
-                        return propertyLayoutData.getId();
-                    }
-                })
-                .toList();
-        for (final String propertyId : propertyIds) {
-            if(!existingIds.contains(propertyId)) {
-                final PropertyLayoutData propertyLayoutData = new PropertyLayoutData(propertyId);
-                fieldSet.getProperties().add(propertyLayoutData);
-                propertyLayoutData.setOwner(fieldSet);
-                propertyLayoutDataById.put(propertyId, propertyLayoutData);
-            }
-        }
-    }
-
-    protected void addCollectionsTo(
-            final BS3Col tabRowCol,
-            final List<String> collectionIds,
-            final LinkedHashMap<String, CollectionLayoutData> collectionLayoutDataById) {
-        for (final String collectionId : collectionIds) {
-            final CollectionLayoutData collectionLayoutData = new CollectionLayoutData(collectionId);
-            collectionLayoutData.setDefaultView("table");
-            tabRowCol.getCollections().add(collectionLayoutData);
-            collectionLayoutDataById.put(collectionId, collectionLayoutData);
-        }
-    }
-
-    protected void addCollectionsTo(
-            final BS3TabGroup tabGroup,
-            final List<String> collectionIds,
-            final ObjectSpecification objectSpec) {
-        for (final String collectionId : collectionIds) {
-            final BS3Tab bs3Tab = new BS3Tab();
-            bs3Tab.setName(objectSpec.getAssociation(collectionId).getName());
-            tabGroup.getTabs().add(bs3Tab);
-            bs3Tab.setOwner(tabGroup);
-
-            final BS3Row tabRow = new BS3Row();
-            tabRow.setOwner(bs3Tab);
-            bs3Tab.getRows().add(tabRow);
-
-            final BS3Col tabRowCol = new BS3Col();
-            tabRowCol.setSpan(12);
-            tabRowCol.setSize(Size.MD);
-            tabRowCol.setOwner(tabRow);
-            tabRow.getCols().add(tabRowCol);
-
-            final CollectionLayoutData layoutMetadata = new CollectionLayoutData(collectionId);
-            layoutMetadata.setDefaultView("table");
-            tabRowCol.getCollections().add(layoutMetadata);
-        }
-    }
-
-    protected void addActionsTo(
-            final BS3Col bs3Col,
-            final List<String> actionIds,
-            final LinkedHashMap<String, ActionLayoutData> actionLayoutDataById) {
-        for (String actionId : actionIds) {
-            final ActionLayoutData actionLayoutData = new ActionLayoutData(actionId);
-            addActionTo(bs3Col, actionLayoutData);
-            actionLayoutDataById.put(actionId, actionLayoutData);
-        }
-    }
-
-    protected void addActionsTo(
-            final FieldSet fieldSet,
-            final List<String> actionIds,
-            final LinkedHashMap<String, ActionLayoutData> actionLayoutDataById) {
-        for (String actionId : actionIds) {
-            final ActionLayoutData actionLayoutData = new ActionLayoutData(actionId);
-            addActionTo(fieldSet, actionLayoutData);
-            actionLayoutDataById.put(actionId, actionLayoutData);
-        }
-    }
-
-    protected void addActionTo(
-            final ActionLayoutDataOwner owner,
-            final ActionLayoutData actionLayoutData) {
-        List<ActionLayoutData> actions = owner.getActions();
-        if(actions == null) {
-            owner.setActions(actions = Lists.newArrayList());
-        }
-        actions.add(actionLayoutData);
-        actionLayoutData.setOwner(owner);
-    }
-
-    private static Boolean isSet(final Boolean flag) {
-        return flag != null && flag;
-    }
-
-    private static String asId(final String str) {
-        if(Strings.isNullOrEmpty(str)) {
-            return str;
-        }
-        final char c = str.charAt(0);
-        return Character.toLowerCase(c) + str.substring(1).replaceAll("\\s+", "");
-    }
-
-
-}

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/bootstrap3/GridSystemServiceBS3.java
----------------------------------------------------------------------
diff --git a/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/bootstrap3/GridSystemServiceBS3.java b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/bootstrap3/GridSystemServiceBS3.java
new file mode 100644
index 0000000..8130066
--- /dev/null
+++ b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/bootstrap3/GridSystemServiceBS3.java
@@ -0,0 +1,682 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT 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.isis.core.metamodel.services.grid.bootstrap3;
+
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
+
+import javax.annotation.Nullable;
+
+import com.google.common.base.Function;
+import com.google.common.base.Predicates;
+import com.google.common.base.Strings;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+
+import org.apache.isis.applib.annotation.ActionLayout;
+import org.apache.isis.applib.annotation.DomainService;
+import org.apache.isis.applib.annotation.MemberGroupLayout;
+import org.apache.isis.applib.annotation.NatureOfService;
+import org.apache.isis.applib.annotation.Programmatic;
+import org.apache.isis.applib.layout.component.ActionLayoutData;
+import org.apache.isis.applib.layout.component.ActionLayoutDataOwner;
+import org.apache.isis.applib.layout.component.CollectionLayoutData;
+import org.apache.isis.applib.layout.component.DomainObjectLayoutData;
+import org.apache.isis.applib.layout.component.FieldSet;
+import org.apache.isis.applib.layout.component.Grid;
+import org.apache.isis.applib.layout.component.PropertyLayoutData;
+import org.apache.isis.applib.layout.grid.bootstrap3.BS3Col;
+import org.apache.isis.applib.layout.grid.bootstrap3.BS3Grid;
+import org.apache.isis.applib.layout.grid.bootstrap3.BS3Row;
+import org.apache.isis.applib.layout.grid.bootstrap3.BS3Tab;
+import org.apache.isis.applib.layout.grid.bootstrap3.BS3TabGroup;
+import org.apache.isis.applib.layout.grid.bootstrap3.Size;
+import org.apache.isis.core.metamodel.facets.actions.position.ActionPositionFacet;
+import org.apache.isis.core.metamodel.facets.members.order.MemberOrderFacet;
+import org.apache.isis.core.metamodel.facets.members.order.annotprop.MemberOrderFacetAnnotation;
+import org.apache.isis.core.metamodel.facets.object.membergroups.MemberGroupLayoutFacet;
+import org.apache.isis.core.metamodel.services.grid.GridSystemServiceAbstract;
+import org.apache.isis.core.metamodel.spec.ObjectSpecification;
+import org.apache.isis.core.metamodel.spec.feature.Contributed;
+import org.apache.isis.core.metamodel.spec.feature.ObjectAction;
+import org.apache.isis.core.metamodel.spec.feature.ObjectAssociation;
+import org.apache.isis.core.metamodel.spec.feature.ObjectMember;
+import org.apache.isis.core.metamodel.spec.feature.OneToManyAssociation;
+import org.apache.isis.core.metamodel.spec.feature.OneToOneAssociation;
+
+@DomainService(
+        nature = NatureOfService.DOMAIN
+)
+public class GridSystemServiceBS3 extends GridSystemServiceAbstract<BS3Grid> {
+
+    public static final String TNS = "http://isis.apache.org/applib/layout/grid/bootstrap3";
+    public static final String SCHEMA_LOCATION = "http://isis.apache.org/applib/layout/grid/bootstrap3/bootstrap3.xsd";
+
+    public GridSystemServiceBS3() {
+        super(BS3Grid.class, TNS, SCHEMA_LOCATION);
+    }
+
+
+    @Programmatic
+    @Override
+    public Grid defaultGrid(final Class<?> domainClass) {
+        final BS3Grid bs3Grid = new BS3Grid();
+
+        final ObjectSpecification objectSpec = specificationLookup.loadSpecification(domainClass);
+        bs3Grid.setDomainClass(domainClass);
+
+        final BS3Row headerRow = new BS3Row();
+        bs3Grid.getRows().add(headerRow);
+        final BS3Col headerRowCol = new BS3Col();
+        headerRowCol.setSpan(12);
+        headerRowCol.setUnreferencedActions(true);
+        headerRowCol.setDomainObject(new DomainObjectLayoutData());
+        headerRow.getCols().add(headerRowCol);
+
+        final BS3Row propsRow = new BS3Row();
+        bs3Grid.getRows().add(propsRow);
+
+        final MemberGroupLayoutFacet memberGroupLayoutFacet =
+                objectSpec.getFacet(MemberGroupLayoutFacet.class);
+        if(memberGroupLayoutFacet != null) {
+            // if have @MemberGroupLayout (or equally, a .layout.json file)
+            final MemberGroupLayout.ColumnSpans columnSpans = memberGroupLayoutFacet.getColumnSpans();
+            addFieldSetsToColumn(propsRow, columnSpans.getLeft(), memberGroupLayoutFacet.getLeft(), true);
+            addFieldSetsToColumn(propsRow, columnSpans.getMiddle(), memberGroupLayoutFacet.getMiddle(), false);
+            addFieldSetsToColumn(propsRow, columnSpans.getRight(), memberGroupLayoutFacet.getRight(), false);
+
+            final BS3Col col = new BS3Col();
+            final int collectionSpan = columnSpans.getCollections();
+            col.setUnreferencedCollections(true);
+            col.setSpan(collectionSpan > 0? collectionSpan: 12);
+            propsRow.getCols().add(col);
+
+            // will already be sorted per @MemberOrder
+            final List<OneToManyAssociation> collections = objectSpec.getCollections(Contributed.INCLUDED);
+            for (OneToManyAssociation collection : collections) {
+                col.getCollections().add(new CollectionLayoutData(collection.getId()));
+            }
+        } else {
+
+            // if no layout hints other than @MemberOrder
+            addFieldSetsToColumn(propsRow, 4, Arrays.asList("General"), true);
+
+            final BS3Col col = new BS3Col();
+            col.setUnreferencedCollections(true);
+            col.setSpan(12);
+            propsRow.getCols().add(col);
+        }
+        return bs3Grid;
+    }
+
+    static void addFieldSetsToColumn(
+            final BS3Row propsRow,
+            final int span,
+            final List<String> memberGroupNames,
+            final boolean unreferencedProperties) {
+
+        if(span > 0 || unreferencedProperties) {
+            final BS3Col col = new BS3Col();
+            col.setSpan(span); // in case we are here because of 'unreferencedProperties' needs setting
+            propsRow.getCols().add(col);
+            final List<String> leftMemberGroups = memberGroupNames;
+            for (String memberGroup : leftMemberGroups) {
+                final FieldSet fieldSet = new FieldSet();
+                fieldSet.setName(memberGroup);
+                // fieldSet's id will be derived from the name later
+                // during normalization phase.
+                if(unreferencedProperties && col.getFieldSets().isEmpty()) {
+                    fieldSet.setUnreferencedProperties(true);
+                }
+                col.getFieldSets().add(fieldSet);
+            }
+        }
+    }
+
+    // //////////////////////////////////////
+
+    /**
+     * Mandatory hook method defined in {@link GridSystemServiceAbstract superclass}, called by {@link #normalize(Grid, Class)}.
+     */
+    @Override
+    protected boolean validateAndNormalize(
+            final Grid grid,
+            final Class<?> domainClass) {
+
+
+        final ObjectSpecification objectSpec = specificationLookup.loadSpecification(domainClass);
+
+        final Map<String, OneToOneAssociation> oneToOneAssociationById =
+                ObjectMember.Util.mapById(getOneToOneAssociations(objectSpec));
+        final Map<String, OneToManyAssociation> oneToManyAssociationById =
+                ObjectMember.Util.mapById(getOneToManyAssociations(objectSpec));
+        final Map<String, ObjectAction> objectActionById =
+                ObjectMember.Util.mapById(objectSpec.getObjectActions(Contributed.INCLUDED));
+
+
+        final BS3Grid bs3Grid = (BS3Grid) grid;
+
+        final LinkedHashMap<String, PropertyLayoutData> propertyLayoutDataById = bs3Grid.getAllPropertiesById();
+        final LinkedHashMap<String, CollectionLayoutData> collectionLayoutDataById = bs3Grid.getAllCollectionsById();
+        final LinkedHashMap<String, ActionLayoutData> actionLayoutDataById = bs3Grid.getAllActionsById();
+
+
+        // find all row and col ids
+        // ensure that all Ids are different
+
+        final List<String> gridIds = Lists.newArrayList();
+        final LinkedHashMap<String, BS3Row> rowIds = Maps.newLinkedHashMap();
+        final LinkedHashMap<String, BS3Col> colIds = Maps.newLinkedHashMap();
+        final LinkedHashMap<String, FieldSet> fieldSetIds = Maps.newLinkedHashMap();
+
+        final AtomicReference<Boolean> duplicateIdDetected = new AtomicReference<>(false);
+
+        bs3Grid.visit(new BS3Grid.VisitorAdapter(){
+            @Override
+            public void visit(final BS3Row bs3Row) {
+                final String id = bs3Row.getId();
+                if(id == null) {
+                    return;
+                }
+                if(gridIds.contains(id)) {
+                    bs3Row.setMetadataError("There is another element in the grid with this id");
+                    duplicateIdDetected.set(true);
+                    return;
+                }
+                rowIds.put(id, bs3Row);
+                gridIds.add(id);
+            }
+
+            @Override
+            public void visit(final BS3Col bs3Col) {
+                final String id = bs3Col.getId();
+                if(id == null) {
+                    return;
+                }
+                if(gridIds.contains(id)) {
+                    bs3Col.setMetadataError("There is another element in the grid with this id");
+                    duplicateIdDetected.set(true);
+                    return;
+                }
+                colIds.put(id, bs3Col);
+                gridIds.add(id);
+            }
+
+            @Override
+            public void visit(final FieldSet fieldSet) {
+                String id = fieldSet.getId();
+                if(id == null) {
+                    final String name = fieldSet.getName();
+                    fieldSet.setId(id = asId(name));
+                }
+                if(gridIds.contains(id)) {
+                    fieldSet.setMetadataError("There is another element in the grid with this id");
+                    duplicateIdDetected.set(true);
+                    return;
+                }
+                fieldSetIds.put(id, fieldSet);
+                gridIds.add(id);
+            }
+        });
+
+        if(duplicateIdDetected.get()) {
+            return false;
+        }
+
+
+        // ensure that there is exactly one col with the
+        // unreferencedActions, unreferencedProperties and unreferencedCollections attribute set.
+
+        final AtomicReference<BS3Col> colForUnreferencedActionsRef = new AtomicReference<>();
+        final AtomicReference<BS3Col> colForUnreferencedCollectionsRef = new AtomicReference<>();
+        final AtomicReference<FieldSet> fieldSetForUnreferencedActionsRef = new AtomicReference<>();
+        final AtomicReference<FieldSet> fieldSetForUnreferencedPropertiesRef = new AtomicReference<>();
+        final AtomicReference<BS3TabGroup> tabGroupForUnreferencedCollectionsRef = new AtomicReference<>();
+
+        bs3Grid.visit(new BS3Grid.VisitorAdapter(){
+
+            @Override
+            public void visit(final BS3Col bs3Col) {
+                if(isSet(bs3Col.isUnreferencedActions())) {
+                    if(colForUnreferencedActionsRef.get() != null) {
+                        bs3Col.setMetadataError("More than one col with 'unreferencedActions' attribute set");
+                    } else if(fieldSetForUnreferencedActionsRef.get() != null) {
+                        bs3Col.setMetadataError("Already found a fieldset with 'unreferencedActions' attribute set");
+                    } else {
+                        colForUnreferencedActionsRef.set(bs3Col);
+                    }
+                }
+                if(isSet(bs3Col.isUnreferencedCollections())) {
+                    if(colForUnreferencedCollectionsRef.get() != null) {
+                        bs3Col.setMetadataError("More than one col with 'unreferencedCollections' attribute set");
+                    } else if(tabGroupForUnreferencedCollectionsRef.get() != null) {
+                        bs3Col.setMetadataError("Already found a tabgroup with 'unreferencedCollections' attribute set");
+                    } else {
+                        colForUnreferencedCollectionsRef.set(bs3Col);
+                    }
+                }
+            }
+
+            @Override
+            public void visit(final FieldSet fieldSet) {
+                if(isSet(fieldSet.isUnreferencedActions())) {
+                    if(fieldSetForUnreferencedActionsRef.get() != null) {
+                        fieldSet.setMetadataError("More than one fieldset with 'unreferencedActions' attribute set");
+                    } else if(colForUnreferencedActionsRef.get() != null) {
+                        fieldSet.setMetadataError("Already found a column with 'unreferencedActions' attribute set");
+                    } else {
+                        fieldSetForUnreferencedActionsRef.set(fieldSet);
+                    }
+                }
+                if(isSet(fieldSet.isUnreferencedProperties())) {
+                    if(fieldSetForUnreferencedPropertiesRef.get() != null) {
+                        fieldSet.setMetadataError("More than one col with 'unreferencedProperties' attribute set");
+                    } else {
+                        fieldSetForUnreferencedPropertiesRef.set(fieldSet);
+                    }
+                }
+            }
+
+            @Override
+            public void visit(final BS3TabGroup bs3TabGroup) {
+                if(isSet(bs3TabGroup.isUnreferencedCollections())) {
+                    if(tabGroupForUnreferencedCollectionsRef.get() != null) {
+                        bs3TabGroup.setMetadataError("More than one tabgroup with 'unreferencedCollections' attribute set");
+                    } else if(colForUnreferencedCollectionsRef.get() != null) {
+                        bs3TabGroup.setMetadataError("Already found a column with 'unreferencedCollections' attribute set");
+                    } else {
+                        tabGroupForUnreferencedCollectionsRef.set(bs3TabGroup);
+                    }
+                }
+            }
+        });
+
+        if(colForUnreferencedActionsRef.get() == null && fieldSetForUnreferencedActionsRef.get() == null) {
+            bs3Grid.getMetadataErrors().add("No column and also no fieldset found with the 'unreferencedActions' attribute set");
+        }
+        if(fieldSetForUnreferencedPropertiesRef.get() == null) {
+            bs3Grid.getMetadataErrors().add("No fieldset found with the 'unreferencedProperties' attribute set");
+        }
+        if(colForUnreferencedCollectionsRef.get() == null && tabGroupForUnreferencedCollectionsRef.get() == null) {
+            bs3Grid.getMetadataErrors().add("No column and also no tabgroup found with the 'unreferencedCollections' attribute set");
+        }
+
+        if(     colForUnreferencedActionsRef.get() == null && fieldSetForUnreferencedActionsRef.get() == null ||
+                fieldSetForUnreferencedPropertiesRef.get() == null ||
+                colForUnreferencedCollectionsRef.get() == null && tabGroupForUnreferencedCollectionsRef.get() == null) {
+            return false;
+        }
+
+        // add missing properties will be added to the first fieldset of the specified column
+        final Tuple<List<String>> propertyIdTuple =
+                surplusAndMissing(propertyLayoutDataById.keySet(),  oneToOneAssociationById.keySet());
+        final List<String> surplusPropertyIds = propertyIdTuple.first;
+        final List<String> missingPropertyIds = propertyIdTuple.second;
+
+        for (String surplusPropertyId : surplusPropertyIds) {
+            propertyLayoutDataById.get(surplusPropertyId).setMetadataError("No such property");
+        }
+
+        // catalog which associations are bound to an existing field set
+        // so that (below) we can determine which missing property ids are not unbound vs which should be included
+        // in the fieldset that they are bound to.
+        final Map<String, Set<String>> boundAssociationIdsByFieldSetId = Maps.newHashMap();
+
+        // all those explicitly in the grid
+        for (FieldSet fieldSet : fieldSetIds.values()) {
+            final String fieldSetId = fieldSet.getId();
+            Set<String> boundAssociationIds = boundAssociationIdsByFieldSetId.get(fieldSetId);
+            if(boundAssociationIds == null) {
+                boundAssociationIds = Sets.newLinkedHashSet();
+                boundAssociationIds.addAll(
+                        FluentIterable.from(fieldSet.getProperties()).transform(
+                                new Function<PropertyLayoutData, String>() {
+                                    @Override
+                                    public String apply(@Nullable final PropertyLayoutData propertyLayoutData) {
+                                        return propertyLayoutData.getId();
+                                    }
+                                }).toList());
+                boundAssociationIdsByFieldSetId.put(fieldSetId, boundAssociationIds);
+            }
+        }
+        // along with any specified by existing metadata
+        for (OneToOneAssociation otoa : oneToOneAssociationById.values()) {
+            final MemberOrderFacet memberOrderFacet = otoa.getFacet(MemberOrderFacet.class);
+            if(memberOrderFacet != null) {
+                final String id = asId(memberOrderFacet.name());
+                if(fieldSetIds.containsKey(id)) {
+                    Set<String> boundAssociationIds = boundAssociationIdsByFieldSetId.get(id);
+                    if(boundAssociationIds == null) {
+                        boundAssociationIds = Sets.newLinkedHashSet();
+                        boundAssociationIdsByFieldSetId.put(id, boundAssociationIds);
+                    }
+                    boundAssociationIds.add(otoa.getId());
+                }
+            }
+        }
+
+        if(!missingPropertyIds.isEmpty()) {
+
+            final List<String> unboundPropertyIds = Lists.newArrayList(missingPropertyIds);
+
+            for (final String fieldSetId : boundAssociationIdsByFieldSetId.keySet()) {
+                final Set<String> boundPropertyIds = boundAssociationIdsByFieldSetId.get(fieldSetId);
+                unboundPropertyIds.removeAll(boundPropertyIds);
+            }
+
+            for (final String fieldSetId : boundAssociationIdsByFieldSetId.keySet()) {
+                final FieldSet fieldSet = fieldSetIds.get(fieldSetId);
+                final Set<String> associationIds =
+                        boundAssociationIdsByFieldSetId.get(fieldSetId);
+
+                final List<OneToOneAssociation> associations = Lists.newArrayList(
+                        FluentIterable.from(associationIds)
+                        .transform(new Function<String, OneToOneAssociation>() {
+                            @Nullable @Override public OneToOneAssociation apply(final String propertyId) {
+                                return oneToOneAssociationById.get(propertyId);
+                            }
+                        })
+                        .filter(Predicates.<OneToOneAssociation>notNull())
+                );
+
+                associations.sort(ObjectAssociation.Comparators.byMemberOrderSequence());
+                addPropertiesTo(fieldSet,
+                        FluentIterable.from(associations)
+                                      .transform(ObjectAssociation.Functions.toId())
+                                      .toList(),
+                        propertyLayoutDataById);
+            }
+
+            if(!unboundPropertyIds.isEmpty()) {
+                final FieldSet fieldSet = fieldSetForUnreferencedPropertiesRef.get();
+                if(fieldSet != null) {
+                    addPropertiesTo(fieldSet, unboundPropertyIds, propertyLayoutDataById);
+                }
+            }
+        }
+
+        // any missing collections will be added as tabs to a new TabGroup in the specified column
+        final Tuple<List<String>> collectionIdTuple =
+                surplusAndMissing(collectionLayoutDataById.keySet(), oneToManyAssociationById.keySet());
+        final List<String> surplusCollectionIds = collectionIdTuple.first;
+        final List<String> missingCollectionIds = collectionIdTuple.second;
+
+        for (String surplusCollectionId : surplusCollectionIds) {
+            collectionLayoutDataById.get(surplusCollectionId).setMetadataError("No such collection");
+        }
+
+        if(!missingCollectionIds.isEmpty()) {
+            List<OneToManyAssociation> sortedCollections = Lists.newArrayList(
+                    FluentIterable.from(missingCollectionIds)
+                    .transform(new Function<String, OneToManyAssociation>() {
+                        @Nullable @Override public OneToManyAssociation apply(@Nullable final String collectionId) {
+                            return oneToManyAssociationById.get(collectionId);
+                        }
+                    })
+                    .toSortedList(ObjectMember.Comparators.byMemberOrderSequence())
+
+            );
+            final ImmutableList<String> sortedMissingCollectionIds = FluentIterable.from(sortedCollections)
+                    .transform(ObjectAssociation.Functions.toId()).toList();
+            final BS3TabGroup bs3TabGroup = tabGroupForUnreferencedCollectionsRef.get();
+            if(bs3TabGroup != null) {
+                addCollectionsTo(bs3TabGroup, sortedMissingCollectionIds, objectSpec);
+            } else {
+                final BS3Col bs3Col = colForUnreferencedCollectionsRef.get();
+                if(bs3Col != null) {
+                    addCollectionsTo(bs3Col, sortedMissingCollectionIds, collectionLayoutDataById);
+                }
+            }
+        }
+
+        // any missing actions will be added as actions in the specified column
+        final Tuple<List<String>> actionIdTuple =
+                surplusAndMissing(actionLayoutDataById.keySet(), objectActionById.keySet());
+        final List<String> surplusActionIds = actionIdTuple.first;
+        final List<String> possiblyMissingActionIds = actionIdTuple.second;
+
+        final List<String> associatedActionIds = Lists.newArrayList();
+
+        List<ObjectAction> sortedPossiblyMissingActions = Lists.newArrayList(
+                FluentIterable.from(possiblyMissingActionIds)
+                        .transform(new Function<String, ObjectAction>() {
+                            @Nullable @Override public ObjectAction apply(@Nullable final String actionId) {
+                                return objectActionById.get(actionId);
+                            }
+                        })
+                        .toSortedList(ObjectMember.Comparators.byMemberOrderSequence()));
+
+        List<String> sortedPossiblyMissingActionIds =
+                FluentIterable.from(sortedPossiblyMissingActions)
+                .transform(ObjectMember.Functions.getId())
+                .toList();
+
+            FluentIterable.from(sortedPossiblyMissingActionIds)
+                .forEach(
+                        new Consumer<String>() {
+                            @Override
+                            public void accept(final String actionId) {
+                                final ObjectAction oa = objectActionById.get(actionId);
+                                final MemberOrderFacet memberOrderFacet = oa.getFacet(MemberOrderFacet.class);
+                                if(memberOrderFacet == null) {
+                                    return;
+                                }
+                                final String memberOrderName = memberOrderFacet.name();
+                                if (memberOrderName == null) {
+                                    return;
+                                }
+                                final String id = asId(memberOrderName);
+
+                                if (oneToOneAssociationById.containsKey(id)) {
+                                    associatedActionIds.add(actionId);
+
+                                    if(!(memberOrderFacet instanceof MemberOrderFacetAnnotation)) {
+                                        // if binding not via annotation, then explicitly bind this
+                                        // action to the property
+                                        final PropertyLayoutData propertyLayoutData = propertyLayoutDataById.get(id);
+                                        final ActionLayoutData actionLayoutData = new ActionLayoutData(actionId);
+
+                                        final ActionPositionFacet actionPositionFacet = oa.getFacet(ActionPositionFacet.class);
+                                        final ActionLayoutDataOwner owner;
+                                        final ActionLayout.Position position;
+                                        if(actionPositionFacet != null) {
+                                            position = actionPositionFacet.position();
+                                            owner = position == ActionLayout.Position.PANEL ||
+                                                    position == ActionLayout.Position.PANEL_DROPDOWN
+                                                        ? propertyLayoutData.getOwner()
+                                                        : propertyLayoutData;
+                                        } else {
+                                            position = ActionLayout.Position.BELOW;
+                                            owner = propertyLayoutData;
+                                        }
+                                        actionLayoutData.setPosition(position);
+                                        addActionTo(owner, actionLayoutData);
+                                    }
+
+                                    return;
+                                }
+                                if (oneToManyAssociationById.containsKey(id)) {
+                                    associatedActionIds.add(actionId);
+
+                                    if(!(memberOrderFacet instanceof MemberOrderFacetAnnotation)) {
+                                        // if binding not via annotation, then explicitly bind this
+                                        // action to the property
+                                        final CollectionLayoutData collectionLayoutData = collectionLayoutDataById.get(id);
+                                        final ActionLayoutData actionLayoutData = new ActionLayoutData(actionId);
+                                        addActionTo(collectionLayoutData, actionLayoutData);
+                                    }
+                                    return;
+                                }
+                                // if the @MemberOrder for the action references a field set (that has bound
+                                // associations), then don't mark it as missing, butinstead explicitly add it to the
+                                // list of actions of that fieldset.
+                                final Set<String> boundAssociationIds = boundAssociationIdsByFieldSetId.get(id);
+                                if(boundAssociationIds != null && !boundAssociationIds.isEmpty()) {
+
+                                    associatedActionIds.add(actionId);
+
+                                    final ActionLayoutData actionLayoutData = new ActionLayoutData(actionId);
+
+                                    actionLayoutData.setPosition(ActionLayout.Position.PANEL_DROPDOWN);
+                                    final FieldSet fieldSet = fieldSetIds.get(id);
+                                    addActionTo(fieldSet, actionLayoutData);
+                                    return;
+                                }
+                            }
+                        });
+
+        // ... the missing actions are those in the second tuple, excluding those associated (via @MemberOrder#name)
+        // to a property or collection.
+        final List<String> missingActionIds = Lists.newArrayList(sortedPossiblyMissingActionIds);
+        missingActionIds.removeAll(associatedActionIds);
+
+        for (String surplusActionId : surplusActionIds) {
+            actionLayoutDataById.get(surplusActionId).setMetadataError("No such action");
+        }
+
+        if(!missingActionIds.isEmpty()) {
+            final BS3Col bs3Col = colForUnreferencedActionsRef.get();
+            if(bs3Col != null) {
+                addActionsTo(bs3Col, missingActionIds, actionLayoutDataById);
+            } else {
+                final FieldSet fieldSet = fieldSetForUnreferencedActionsRef.get();
+                if(fieldSet != null) {
+                    addActionsTo(fieldSet, missingActionIds, actionLayoutDataById);
+                }
+            }
+        }
+
+        return true;
+    }
+
+    protected void addPropertiesTo(
+            final FieldSet fieldSet,
+            final List<String> propertyIds,
+            final LinkedHashMap<String, PropertyLayoutData> propertyLayoutDataById) {
+        final ImmutableList<String> existingIds = FluentIterable
+                .from(fieldSet.getProperties())
+                .transform(new Function<PropertyLayoutData, String>() {
+                    @Nullable
+                    @Override
+                    public String apply(@Nullable final PropertyLayoutData propertyLayoutData) {
+                        return propertyLayoutData.getId();
+                    }
+                })
+                .toList();
+        for (final String propertyId : propertyIds) {
+            if(!existingIds.contains(propertyId)) {
+                final PropertyLayoutData propertyLayoutData = new PropertyLayoutData(propertyId);
+                fieldSet.getProperties().add(propertyLayoutData);
+                propertyLayoutData.setOwner(fieldSet);
+                propertyLayoutDataById.put(propertyId, propertyLayoutData);
+            }
+        }
+    }
+
+    protected void addCollectionsTo(
+            final BS3Col tabRowCol,
+            final List<String> collectionIds,
+            final LinkedHashMap<String, CollectionLayoutData> collectionLayoutDataById) {
+        for (final String collectionId : collectionIds) {
+            final CollectionLayoutData collectionLayoutData = new CollectionLayoutData(collectionId);
+            collectionLayoutData.setDefaultView("table");
+            tabRowCol.getCollections().add(collectionLayoutData);
+            collectionLayoutDataById.put(collectionId, collectionLayoutData);
+        }
+    }
+
+    protected void addCollectionsTo(
+            final BS3TabGroup tabGroup,
+            final List<String> collectionIds,
+            final ObjectSpecification objectSpec) {
+        for (final String collectionId : collectionIds) {
+            final BS3Tab bs3Tab = new BS3Tab();
+            bs3Tab.setName(objectSpec.getAssociation(collectionId).getName());
+            tabGroup.getTabs().add(bs3Tab);
+            bs3Tab.setOwner(tabGroup);
+
+            final BS3Row tabRow = new BS3Row();
+            tabRow.setOwner(bs3Tab);
+            bs3Tab.getRows().add(tabRow);
+
+            final BS3Col tabRowCol = new BS3Col();
+            tabRowCol.setSpan(12);
+            tabRowCol.setSize(Size.MD);
+            tabRowCol.setOwner(tabRow);
+            tabRow.getCols().add(tabRowCol);
+
+            final CollectionLayoutData layoutMetadata = new CollectionLayoutData(collectionId);
+            layoutMetadata.setDefaultView("table");
+            tabRowCol.getCollections().add(layoutMetadata);
+        }
+    }
+
+    protected void addActionsTo(
+            final BS3Col bs3Col,
+            final List<String> actionIds,
+            final LinkedHashMap<String, ActionLayoutData> actionLayoutDataById) {
+        for (String actionId : actionIds) {
+            final ActionLayoutData actionLayoutData = new ActionLayoutData(actionId);
+            addActionTo(bs3Col, actionLayoutData);
+            actionLayoutDataById.put(actionId, actionLayoutData);
+        }
+    }
+
+    protected void addActionsTo(
+            final FieldSet fieldSet,
+            final List<String> actionIds,
+            final LinkedHashMap<String, ActionLayoutData> actionLayoutDataById) {
+        for (String actionId : actionIds) {
+            final ActionLayoutData actionLayoutData = new ActionLayoutData(actionId);
+            addActionTo(fieldSet, actionLayoutData);
+            actionLayoutDataById.put(actionId, actionLayoutData);
+        }
+    }
+
+    protected void addActionTo(
+            final ActionLayoutDataOwner owner,
+            final ActionLayoutData actionLayoutData) {
+        List<ActionLayoutData> actions = owner.getActions();
+        if(actions == null) {
+            owner.setActions(actions = Lists.newArrayList());
+        }
+        actions.add(actionLayoutData);
+        actionLayoutData.setOwner(owner);
+    }
+
+    private static Boolean isSet(final Boolean flag) {
+        return flag != null && flag;
+    }
+
+    private static String asId(final String str) {
+        if(Strings.isNullOrEmpty(str)) {
+            return str;
+        }
+        final char c = str.charAt(0);
+        return Character.toLowerCase(c) + str.substring(1).replaceAll("\\s+", "");
+    }
+
+
+}


[3/4] isis git commit: ISIS-993: split LayoutService back out into LayoutService (API) vs GridService (SPI); rationalizing APIs; adding documentation.

Posted by da...@apache.org.
http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/GridImplementationServiceAbstract.java
----------------------------------------------------------------------
diff --git a/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/GridImplementationServiceAbstract.java b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/GridImplementationServiceAbstract.java
deleted file mode 100644
index c2bd8e9..0000000
--- a/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/GridImplementationServiceAbstract.java
+++ /dev/null
@@ -1,688 +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.isis.core.metamodel.services.grid;
-
-import java.util.Collection;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import javax.inject.Inject;
-
-import com.google.common.base.Strings;
-import com.google.common.collect.Lists;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.isis.applib.DomainObjectContainer;
-import org.apache.isis.applib.annotation.ActionLayout;
-import org.apache.isis.applib.annotation.BookmarkPolicy;
-import org.apache.isis.applib.annotation.LabelPosition;
-import org.apache.isis.applib.annotation.Programmatic;
-import org.apache.isis.applib.annotation.Where;
-import org.apache.isis.applib.layout.component.ActionLayoutData;
-import org.apache.isis.applib.layout.component.ActionLayoutDataOwner;
-import org.apache.isis.applib.layout.component.CollectionLayoutData;
-import org.apache.isis.applib.layout.component.DomainObjectLayoutData;
-import org.apache.isis.applib.layout.component.DomainObjectLayoutDataOwner;
-import org.apache.isis.applib.layout.component.FieldSet;
-import org.apache.isis.applib.layout.component.Grid;
-import org.apache.isis.applib.layout.component.HasBookmarking;
-import org.apache.isis.applib.layout.component.HasCssClass;
-import org.apache.isis.applib.layout.component.HasCssClassFa;
-import org.apache.isis.applib.layout.component.HasDescribedAs;
-import org.apache.isis.applib.layout.component.HasHidden;
-import org.apache.isis.applib.layout.component.HasNamed;
-import org.apache.isis.applib.layout.component.PropertyLayoutData;
-import org.apache.isis.applib.services.i18n.TranslationService;
-import org.apache.isis.applib.services.jaxb.JaxbService;
-import org.apache.isis.applib.services.layout.GridImplementationService;
-import org.apache.isis.core.metamodel.deployment.DeploymentCategory;
-import org.apache.isis.core.metamodel.deployment.DeploymentCategoryAware;
-import org.apache.isis.core.metamodel.facetapi.Facet;
-import org.apache.isis.core.metamodel.facetapi.FacetHolder;
-import org.apache.isis.core.metamodel.facetapi.FacetUtil;
-import org.apache.isis.core.metamodel.facets.actions.layout.ActionPositionFacetForActionXml;
-import org.apache.isis.core.metamodel.facets.actions.layout.BookmarkPolicyFacetForActionXml;
-import org.apache.isis.core.metamodel.facets.actions.layout.CssClassFaFacetForActionXml;
-import org.apache.isis.core.metamodel.facets.actions.layout.CssClassFacetForActionXml;
-import org.apache.isis.core.metamodel.facets.actions.layout.DescribedAsFacetForActionXml;
-import org.apache.isis.core.metamodel.facets.actions.layout.HiddenFacetForActionLayoutXml;
-import org.apache.isis.core.metamodel.facets.actions.layout.NamedFacetForActionXml;
-import org.apache.isis.core.metamodel.facets.actions.position.ActionPositionFacet;
-import org.apache.isis.core.metamodel.facets.all.describedas.DescribedAsFacet;
-import org.apache.isis.core.metamodel.facets.all.hide.HiddenFacet;
-import org.apache.isis.core.metamodel.facets.all.named.NamedFacet;
-import org.apache.isis.core.metamodel.facets.collections.collection.defaultview.DefaultViewFacet;
-import org.apache.isis.core.metamodel.facets.collections.layout.CssClassFacetForCollectionXml;
-import org.apache.isis.core.metamodel.facets.collections.layout.DefaultViewFacetForCollectionXml;
-import org.apache.isis.core.metamodel.facets.collections.layout.DescribedAsFacetForCollectionXml;
-import org.apache.isis.core.metamodel.facets.collections.layout.HiddenFacetForCollectionXml;
-import org.apache.isis.core.metamodel.facets.collections.layout.NamedFacetForCollectionXml;
-import org.apache.isis.core.metamodel.facets.collections.layout.PagedFacetForCollectionXml;
-import org.apache.isis.core.metamodel.facets.collections.layout.SortedByFacetForCollectionXml;
-import org.apache.isis.core.metamodel.facets.collections.sortedby.SortedByFacet;
-import org.apache.isis.core.metamodel.facets.members.cssclass.CssClassFacet;
-import org.apache.isis.core.metamodel.facets.members.cssclassfa.CssClassFaFacet;
-import org.apache.isis.core.metamodel.facets.members.cssclassfa.CssClassFaPosition;
-import org.apache.isis.core.metamodel.facets.members.order.annotprop.MemberOrderFacetXml;
-import org.apache.isis.core.metamodel.facets.object.bookmarkpolicy.BookmarkPolicyFacet;
-import org.apache.isis.core.metamodel.facets.object.paged.PagedFacet;
-import org.apache.isis.core.metamodel.facets.object.plural.PluralFacet;
-import org.apache.isis.core.metamodel.facets.objectvalue.labelat.LabelAtFacet;
-import org.apache.isis.core.metamodel.facets.objectvalue.multiline.MultiLineFacet;
-import org.apache.isis.core.metamodel.facets.objectvalue.renderedadjusted.RenderedAdjustedFacet;
-import org.apache.isis.core.metamodel.facets.objectvalue.typicallen.TypicalLengthFacet;
-import org.apache.isis.core.metamodel.facets.properties.propertylayout.CssClassFacetForPropertyXml;
-import org.apache.isis.core.metamodel.facets.properties.propertylayout.DescribedAsFacetForPropertyXml;
-import org.apache.isis.core.metamodel.facets.properties.propertylayout.HiddenFacetForPropertyXml;
-import org.apache.isis.core.metamodel.facets.properties.propertylayout.LabelAtFacetForPropertyXml;
-import org.apache.isis.core.metamodel.facets.properties.propertylayout.MultiLineFacetForPropertyXml;
-import org.apache.isis.core.metamodel.facets.properties.propertylayout.NamedFacetForPropertyXml;
-import org.apache.isis.core.metamodel.facets.properties.propertylayout.RenderedAdjustedFacetForPropertyXml;
-import org.apache.isis.core.metamodel.facets.properties.propertylayout.TypicalLengthFacetForPropertyXml;
-import org.apache.isis.core.metamodel.spec.ObjectSpecification;
-import org.apache.isis.core.metamodel.spec.SpecificationLoader;
-import org.apache.isis.core.metamodel.spec.SpecificationLoaderAware;
-import org.apache.isis.core.metamodel.spec.feature.Contributed;
-import org.apache.isis.core.metamodel.spec.feature.ObjectAction;
-import org.apache.isis.core.metamodel.spec.feature.ObjectAssociation;
-import org.apache.isis.core.metamodel.spec.feature.ObjectMember;
-import org.apache.isis.core.metamodel.spec.feature.OneToManyAssociation;
-import org.apache.isis.core.metamodel.spec.feature.OneToOneAssociation;
-
-public abstract class GridImplementationServiceAbstract<G extends Grid>
-        implements GridImplementationService<G>, SpecificationLoaderAware, DeploymentCategoryAware {
-
-    private static final Logger LOG = LoggerFactory.getLogger(GridImplementationServiceAbstract.class);
-
-    private final Class<G> gridImplementation;
-    private final String tns;
-    private final String schemaLocation;
-
-    public GridImplementationServiceAbstract(
-            final Class<G> gridImplementation,
-            final String tns,
-            final String schemaLocation) {
-        this.gridImplementation = gridImplementation;
-        this.tns = tns;
-        this.schemaLocation = schemaLocation;
-    }
-
-    // //////////////////////////////////////
-
-    @Programmatic
-    @Override
-    public Class<G> gridImplementation() {
-        return gridImplementation;
-    }
-
-    @Programmatic
-    @Override
-    public String tns() {
-        return tns;
-    }
-
-    @Programmatic
-    @Override
-    public String schemaLocation() {
-        return schemaLocation;
-    }
-
-
-    // //////////////////////////////////////
-
-    @Programmatic
-    @Override
-    public void normalize(final G grid, final Class<?> domainClass) {
-
-        if(!gridImplementation.isAssignableFrom(grid.getClass())) {
-            // ignore any other grid implementations
-            return;
-        }
-        final ObjectSpecification objectSpec = specificationLookup.loadSpecification(domainClass);
-
-        final Map<String, OneToOneAssociation> oneToOneAssociationById =
-                ObjectMember.Util.mapById(getOneToOneAssociations(objectSpec));
-        final Map<String, OneToManyAssociation> oneToManyAssociationById =
-                ObjectMember.Util.mapById(getOneToManyAssociations(objectSpec));
-        final Map<String, ObjectAction> objectActionById =
-                ObjectMember.Util.mapById(objectSpec.getObjectActions(Contributed.INCLUDED));
-
-        final boolean valid =
-                validateAndDerive(
-                    grid, oneToOneAssociationById, oneToManyAssociationById, objectActionById, objectSpec);
-        if (valid) {
-            overwrite(grid, oneToOneAssociationById, oneToManyAssociationById, objectActionById);
-            if(LOG.isDebugEnabled()) {
-                LOG.debug("Grid:\n\n" + jaxbService.toXml(grid) + "\n\n");
-            }
-        } else {
-
-            if(!deploymentCategory.isProduction()) {
-                container.warnUser("Grid metadata errors for " + grid.getDomainClass().getName() + "; check the error log");
-            }
-            LOG.error("Grid metadata errors:\n\n" + jaxbService.toXml(grid) + "\n\n");
-        }
-    }
-
-
-    /**
-     * Mandatory hook method for subclasses, where they must ensure that all object members (properties, collections
-     * and actions) are in the grid metadata, typically by deriving this information from other existing metadata
-     * (eg facets from annotations) or just by applying default rules.
-     */
-    protected abstract boolean validateAndDerive(
-            final Grid grid,
-            final Map<String, OneToOneAssociation> oneToOneAssociationById,
-            final Map<String, OneToManyAssociation> oneToManyAssociationById,
-            final Map<String, ObjectAction> objectActionById,
-            final ObjectSpecification objectSpec);
-
-
-    /**
-     * Overwrites (replaces) any existing facets in the metamodel with info taken from the grid.
-     *
-     * <p>
-     *     This code uses {@link FacetUtil#addOrReplaceFacet(Facet)} because the layout might be changed multiple times.
-     * </p>
-     */
-    protected void overwrite(
-            final G fcGrid,
-            final Map<String, OneToOneAssociation> oneToOneAssociationById,
-            final Map<String, OneToManyAssociation> oneToManyAssociationById,
-            final Map<String, ObjectAction> objectActionById) {
-
-        final AtomicInteger propertySequence = new AtomicInteger(0);
-        fcGrid.visit(new Grid.VisitorAdapter() {
-            private int collectionSequence = 1;
-
-            private int actionDomainObjectSequence = 1;
-            private int actionPropertyGroupSequence = 1;
-            private int actionPropertySequence = 1;
-            private int actionCollectionSequence = 1;
-
-            @Override
-            public void visit(final ActionLayoutData actionLayoutData) {
-                final ActionLayoutDataOwner actionLayoutDataOwner = actionLayoutData.getOwner();
-                final ObjectAction objectAction = objectActionById.get(actionLayoutData.getId());
-                if(objectAction == null) {
-                    return;
-                }
-
-                final String memberOrderName;
-                final int memberOrderSequence;
-                if(actionLayoutDataOwner instanceof FieldSet) {
-                    final FieldSet fieldSet = (FieldSet) actionLayoutDataOwner;
-                    final List<PropertyLayoutData> properties = fieldSet.getProperties();
-                    final PropertyLayoutData propertyLayoutData = properties.get(0); // any will do
-                    memberOrderName = propertyLayoutData.getId();
-                    memberOrderSequence = actionPropertyGroupSequence++;
-                } else if(actionLayoutDataOwner instanceof PropertyLayoutData) {
-                    final PropertyLayoutData propertyLayoutData = (PropertyLayoutData) actionLayoutDataOwner;
-                    memberOrderName = propertyLayoutData.getId();
-                    memberOrderSequence = actionPropertySequence++;
-                } else if(actionLayoutDataOwner instanceof CollectionLayoutData) {
-                    final CollectionLayoutData collectionLayoutData = (CollectionLayoutData) actionLayoutDataOwner;
-                    memberOrderName = collectionLayoutData.getId();
-                    memberOrderSequence = actionCollectionSequence++;
-                } else {
-                    // means' don't add: any existing metadata should be preserved
-                    memberOrderName = null;
-                    memberOrderSequence = actionDomainObjectSequence++;
-                }
-                if(memberOrderName != null) {
-                    FacetUtil.addOrReplaceFacet(
-                            new MemberOrderFacetXml(memberOrderName, "" + memberOrderSequence, translationService,
-                                    objectAction));
-                }
-
-                // fix up the action position if required
-                if(actionLayoutDataOwner instanceof FieldSet) {
-                    if(actionLayoutData.getPosition() == null ||
-                            actionLayoutData.getPosition() == org.apache.isis.applib.annotation.ActionLayout.Position.BELOW ||
-                            actionLayoutData.getPosition() == org.apache.isis.applib.annotation.ActionLayout.Position.RIGHT) {
-                        actionLayoutData.setPosition(org.apache.isis.applib.annotation.ActionLayout.Position.PANEL);
-                    }
-                } else if(actionLayoutDataOwner instanceof PropertyLayoutData) {
-                    if(actionLayoutData.getPosition() == null ||
-                            actionLayoutData.getPosition() == org.apache.isis.applib.annotation.ActionLayout.Position.PANEL_DROPDOWN ||
-                            actionLayoutData.getPosition() == org.apache.isis.applib.annotation.ActionLayout.Position.PANEL) {
-                        actionLayoutData.setPosition(org.apache.isis.applib.annotation.ActionLayout.Position.BELOW);
-                    }
-                } else {
-                    // doesn't do anything for DomainObject or Collection
-                    actionLayoutData.setPosition(null);
-                }
-
-                FacetUtil.addOrReplaceFacet(ActionPositionFacetForActionXml.create(actionLayoutData, objectAction));
-                FacetUtil.addOrReplaceFacet(BookmarkPolicyFacetForActionXml.create(actionLayoutData, objectAction));
-                FacetUtil.addOrReplaceFacet(CssClassFacetForActionXml.create(actionLayoutData, objectAction));
-                FacetUtil.addOrReplaceFacet(CssClassFaFacetForActionXml.create(actionLayoutData, objectAction));
-                FacetUtil.addOrReplaceFacet(DescribedAsFacetForActionXml.create(actionLayoutData, objectAction));
-                FacetUtil.addOrReplaceFacet(HiddenFacetForActionLayoutXml.create(actionLayoutData, objectAction));
-                FacetUtil.addOrReplaceFacet(NamedFacetForActionXml.create(actionLayoutData, objectAction));
-            }
-
-            @Override
-            public void visit(final PropertyLayoutData propertyLayoutData) {
-                final OneToOneAssociation oneToOneAssociation = oneToOneAssociationById.get(propertyLayoutData.getId());
-                if(oneToOneAssociation == null) {
-                    return;
-                }
-
-                FacetUtil.addOrReplaceFacet(CssClassFacetForPropertyXml.create(propertyLayoutData, oneToOneAssociation));
-                FacetUtil.addOrReplaceFacet(DescribedAsFacetForPropertyXml.create(propertyLayoutData, oneToOneAssociation));
-                FacetUtil.addOrReplaceFacet(HiddenFacetForPropertyXml.create(propertyLayoutData, oneToOneAssociation));
-                FacetUtil.addOrReplaceFacet(LabelAtFacetForPropertyXml.create(propertyLayoutData, oneToOneAssociation));
-                FacetUtil.addOrReplaceFacet(MultiLineFacetForPropertyXml.create(propertyLayoutData, oneToOneAssociation));
-                FacetUtil.addOrReplaceFacet(NamedFacetForPropertyXml.create(propertyLayoutData, oneToOneAssociation));
-                FacetUtil.addOrReplaceFacet(
-                        RenderedAdjustedFacetForPropertyXml.create(propertyLayoutData, oneToOneAssociation));
-                FacetUtil.addOrReplaceFacet(TypicalLengthFacetForPropertyXml.create(propertyLayoutData, oneToOneAssociation));
-
-                // @MemberOrder#name based on owning property group, @MemberOrder#sequence monotonically increasing
-                // nb for any given field set the sequence won't reset to zero; however this is what we want so that
-                // table columns are shown correctly (by fieldset, then property order within that fieldset).
-                final FieldSet fieldSet = propertyLayoutData.getOwner();
-                final String groupName = fieldSet.getName();
-                final String sequence = "" + (propertySequence.incrementAndGet());
-                FacetUtil.addOrReplaceFacet(
-                        new MemberOrderFacetXml(groupName, sequence, translationService, oneToOneAssociation));
-            }
-
-            @Override
-            public void visit(final CollectionLayoutData collectionLayoutData) {
-                final OneToManyAssociation oneToManyAssociation = oneToManyAssociationById.get(collectionLayoutData.getId());
-                if(oneToManyAssociation == null) {
-                    return;
-                }
-
-                FacetUtil.addOrReplaceFacet(CssClassFacetForCollectionXml.create(collectionLayoutData, oneToManyAssociation));
-                FacetUtil.addOrReplaceFacet(
-                        DefaultViewFacetForCollectionXml.create(collectionLayoutData, oneToManyAssociation));
-                FacetUtil.addOrReplaceFacet(
-                        DescribedAsFacetForCollectionXml.create(collectionLayoutData, oneToManyAssociation));
-                FacetUtil.addOrReplaceFacet(HiddenFacetForCollectionXml.create(collectionLayoutData, oneToManyAssociation));
-                FacetUtil.addOrReplaceFacet(NamedFacetForCollectionXml.create(collectionLayoutData, oneToManyAssociation));
-                FacetUtil.addOrReplaceFacet(PagedFacetForCollectionXml.create(collectionLayoutData, oneToManyAssociation));
-                FacetUtil.addOrReplaceFacet(SortedByFacetForCollectionXml.create(collectionLayoutData, oneToManyAssociation));
-
-                // @MemberOrder#name based on the collection's id (so that each has a single "member group")
-                final String groupName = collectionLayoutData.getId();
-                final String sequence = "" + collectionSequence++;
-                FacetUtil.addOrReplaceFacet(
-                        new MemberOrderFacetXml(groupName, sequence, translationService, oneToManyAssociation));
-            }
-        });
-    }
-
-
-    protected static List<OneToOneAssociation> getOneToOneAssociations(final ObjectSpecification objectSpec) {
-        List associations = objectSpec.getAssociations(Contributed.INCLUDED, ObjectAssociation.Filters.PROPERTIES);
-        return associations;
-    }
-    protected  static List<OneToManyAssociation> getOneToManyAssociations(final ObjectSpecification objectSpec) {
-        List associations = objectSpec.getAssociations(Contributed.INCLUDED, ObjectAssociation.Filters.COLLECTIONS);
-        return associations;
-    }
-
-
-
-    protected static class Tuple<T> {
-        public final T first;
-        public final T second;
-        private Tuple(final T first, final T second) {
-            this.first = first;
-            this.second = second;
-        }
-        public static <T> Tuple<T> of(final T first, final T second) {
-            return new Tuple<>(first, second);
-        }
-    }
-
-
-    /**
-     * Returns a 2-element tuple of [first-second, second-first]
-     */
-    protected static <T> Tuple<List<T>> surplusAndMissing(final Collection<T> first, final Collection<T> second){
-        final List<T> firstNotSecond = Lists.newArrayList(first);
-        firstNotSecond.removeAll(second);
-        final List<T> secondNotFirst = Lists.newArrayList(second);
-        secondNotFirst.removeAll(first);
-        return Tuple.of(firstNotSecond, secondNotFirst);
-    }
-
-
-
-    // //////////////////////////////////////
-
-    @Programmatic
-    @Override
-    public void complete(final G grid, final Class<?> domainClass) {
-        normalize(grid, domainClass);
-
-        final ObjectSpecification objectSpec = specificationLookup.loadSpecification(domainClass);
-
-        grid.visit(new Grid.VisitorAdapter() {
-
-            @Override
-            public void visit(final ActionLayoutData actionLayoutData) {
-                final ObjectAction objectAction = objectSpec.getObjectAction(actionLayoutData.getId());
-
-                setBookmarkingIfAny(actionLayoutData, objectAction);
-                setCssClassIfAny(actionLayoutData, objectAction);
-                setCssClassFaIfAny(actionLayoutData, objectAction);
-                setDescribedAsIfAny(actionLayoutData, objectAction);
-                setHiddenIfAny(actionLayoutData, objectAction);
-                setNamedIfAny(actionLayoutData, objectAction);
-                setActionPositionIfAny(actionLayoutData, objectAction);
-            }
-
-            @Override
-            public void visit(final CollectionLayoutData collectionLayoutData) {
-                final ObjectAssociation collection = objectSpec.getAssociation(collectionLayoutData.getId());
-
-                setCssClassIfAny(collectionLayoutData, collection);
-                setDefaultViewIfAny(collectionLayoutData, collection);
-                setDescribedAsIfAny(collectionLayoutData, collection);
-                setHiddenIfAny(collectionLayoutData, collection);
-                setNamedIfAny(collectionLayoutData, collection);
-                setPagedIfAny(collectionLayoutData, collection);
-                setSortedByIfAny(collectionLayoutData, collection);
-            }
-
-            @Override
-            public void visit(final PropertyLayoutData propertyLayoutData) {
-                final ObjectAssociation property = objectSpec.getAssociation(propertyLayoutData.getId());
-
-                setCssClassIfAny(propertyLayoutData, property);
-                setDescribedAsIfAny(propertyLayoutData, property);
-                setHiddenIfAny(propertyLayoutData, property);
-                setNamedIfAny(propertyLayoutData, property);
-                setLabelPositionIfAny(propertyLayoutData, property);
-                setMultiLineIfAny(propertyLayoutData, property);
-                setRenderedAsDayBeforeIfAny(propertyLayoutData, property);
-                setTypicalLengthIfAny(propertyLayoutData, property);
-            }
-
-            @Override
-            public void visit(final DomainObjectLayoutData domainObjectLayoutData) {
-                setBookmarkingIfAny(domainObjectLayoutData, objectSpec);
-                setCssClassIfAny(domainObjectLayoutData, objectSpec);
-                setCssClassFaIfAny(domainObjectLayoutData, objectSpec);
-                setDescribedAsIfAny(domainObjectLayoutData, objectSpec);
-                setNamedIfAny(domainObjectLayoutData, objectSpec);
-                setPluralIfAny(domainObjectLayoutData, objectSpec);
-            }
-        });
-    }
-
-    private static boolean isDoOp(final Facet facet) {
-        return facet != null && !facet.isNoop();
-    }
-
-    protected void setBookmarkingIfAny(
-            final HasBookmarking hasBookmarking,
-            final FacetHolder facetHolder) {
-        final BookmarkPolicyFacet bookmarkPolicyFacet = facetHolder.getFacet(BookmarkPolicyFacet.class);
-        if(isDoOp(bookmarkPolicyFacet)) {
-            final BookmarkPolicy bookmarking = bookmarkPolicyFacet.value();
-            if(bookmarking != null) {
-                hasBookmarking.setBookmarking(bookmarking);
-            }
-        }
-    }
-
-    protected void setCssClassIfAny(
-            final HasCssClass hasCssClass,
-            final FacetHolder facetHolder) {
-        final CssClassFacet cssClassFacet = facetHolder.getFacet(CssClassFacet.class);
-        if(isDoOp(cssClassFacet)) {
-            try {
-                // try...finally because CSS class may vary by object, and we pass in only null
-                final String cssClass = cssClassFacet.cssClass(null);
-                if(!Strings.isNullOrEmpty(cssClass)) {
-                    hasCssClass.setCssClass(cssClass);
-                }
-            } catch(Exception ignore) {
-                // ignore
-            }
-        }
-    }
-
-    protected void setCssClassFaIfAny(
-            final HasCssClassFa hasCssClassFa,
-            final FacetHolder facetHolder) {
-        final CssClassFaFacet cssClassFaFacet = facetHolder.getFacet(CssClassFaFacet.class);
-        if (isDoOp(cssClassFaFacet)) {
-            final String cssClassFa = cssClassFaFacet.value();
-            final CssClassFaPosition position = cssClassFaFacet.getPosition();
-            if(!Strings.isNullOrEmpty(cssClassFa)) {
-                hasCssClassFa.setCssClassFa(cssClassFa);
-                hasCssClassFa.setCssClassFaPosition(position.toActionLayoutPosition());
-            }
-        }
-    }
-
-    protected void setDefaultViewIfAny(
-            final CollectionLayoutData collectionLayoutData,
-            final FacetHolder facetHolder) {
-        final DefaultViewFacet defaultViewFacet = facetHolder.getFacet(DefaultViewFacet.class);
-        if(isDoOp(defaultViewFacet)) {
-            final String defaultView = defaultViewFacet.value();
-            if(!Strings.isNullOrEmpty(defaultView)) {
-                collectionLayoutData.setDefaultView(defaultView);
-            }
-        }
-    }
-
-    protected void setDescribedAsIfAny(
-            final HasDescribedAs hasDescribedAs,
-            final FacetHolder facetHolder) {
-        final DescribedAsFacet describedAsFacet = facetHolder.getFacet(DescribedAsFacet.class);
-        if(isDoOp(describedAsFacet)) {
-            final String describedAs = describedAsFacet.value();
-            if(!Strings.isNullOrEmpty(describedAs)) {
-                hasDescribedAs.setDescribedAs(describedAs);
-            }
-        }
-    }
-
-    protected void setHiddenIfAny(
-            final HasHidden hasHidden,
-            final FacetHolder facetHolder) {
-        final HiddenFacet hiddenFacet = facetHolder.getFacet(HiddenFacet.class);
-        if (isDoOp(hiddenFacet)) {
-            final Where where = hiddenFacet.where();
-            if(where != null) {
-                hasHidden.setHidden(where);
-            }
-        }
-    }
-
-    protected void setLabelPositionIfAny(
-            final PropertyLayoutData propertyLayoutData,
-            final FacetHolder facetHolder) {
-        final LabelAtFacet labelAtFacet = facetHolder.getFacet(LabelAtFacet.class);
-        if(isDoOp(labelAtFacet)) {
-            final LabelPosition labelPosition = labelAtFacet.label();
-            if(labelPosition != null) {
-                propertyLayoutData.setLabelPosition(labelPosition);
-            }
-        }
-    }
-
-    protected void setMultiLineIfAny(
-            final PropertyLayoutData propertyLayoutData,
-            final FacetHolder facetHolder) {
-        final MultiLineFacet multiLineFacet = facetHolder.getFacet(MultiLineFacet.class);
-        if(isDoOp(multiLineFacet)) {
-            final int numberOfLines = multiLineFacet.numberOfLines();
-            if(numberOfLines > 0) {
-                propertyLayoutData.setMultiLine(numberOfLines);
-            }
-        }
-    }
-
-    protected void setNamedIfAny(
-            final HasNamed hasNamed,
-            final FacetHolder facetHolder) {
-        final NamedFacet namedFacet = facetHolder.getFacet(NamedFacet.class);
-        if(isDoOp(namedFacet)) {
-            final String named = namedFacet.value();
-            if(!Strings.isNullOrEmpty(named)){
-                hasNamed.setNamed(named);
-            }
-            final boolean escaped = namedFacet.escaped();
-            if(!escaped) {
-                hasNamed.setNamedEscaped(escaped);
-            }
-        }
-    }
-
-    protected void setPagedIfAny(
-            final CollectionLayoutData collectionLayoutData,
-            final FacetHolder facetHolder) {
-        final PagedFacet pagedFacet = facetHolder.getFacet(PagedFacet.class);
-        if(isDoOp(pagedFacet)) {
-            final int value = pagedFacet.value();
-            if(value > 0) {
-                collectionLayoutData.setPaged(value);
-            }
-        }
-    }
-
-    protected void setPluralIfAny(
-            final DomainObjectLayoutData domainObjectLayoutData,
-            final FacetHolder facetHolder) {
-        final PluralFacet pluralFacet = facetHolder.getFacet(PluralFacet.class);
-        if(isDoOp(pluralFacet)) {
-            final String plural = pluralFacet.value();
-            if(!Strings.isNullOrEmpty(plural)) {
-                domainObjectLayoutData.setPlural(plural);
-            }
-        }
-    }
-
-
-    protected void setActionPositionIfAny(
-            final ActionLayoutData actionLayoutData,
-            final FacetHolder facetHolder) {
-        final ActionPositionFacet actionPositionFacet = facetHolder.getFacet(ActionPositionFacet.class);
-        if(isDoOp(actionPositionFacet)) {
-            final ActionLayout.Position position = actionPositionFacet.position();
-            if(position != null) {
-                actionLayoutData.setPosition(position);
-            }
-        }
-    }
-
-    protected void setRenderedAsDayBeforeIfAny(
-            final PropertyLayoutData propertyLayoutData,
-            final FacetHolder facetHolder) {
-        final RenderedAdjustedFacet renderedAdjustedFacet = facetHolder.getFacet(RenderedAdjustedFacet.class);
-        if(isDoOp(renderedAdjustedFacet)) {
-            final int adjusted = renderedAdjustedFacet.value();
-            propertyLayoutData.setRenderedAsDayBefore(adjusted != 0);
-        }
-    }
-
-    protected void setSortedByIfAny(
-            final CollectionLayoutData collectionLayoutData,
-            final FacetHolder facetHolder) {
-        final SortedByFacet sortedByFacet = facetHolder.getFacet(SortedByFacet.class);
-        if(isDoOp(sortedByFacet)) {
-            final Class<? extends Comparator<?>> className = sortedByFacet.value();
-            if(className != null) {
-                collectionLayoutData.setSortedBy(className.getCanonicalName());
-            }
-        }
-    }
-
-    protected void setTypicalLengthIfAny(
-            final PropertyLayoutData propertyLayoutData,
-            final FacetHolder facetHolder) {
-        final TypicalLengthFacet typicalLengthFacet = facetHolder.getFacet(TypicalLengthFacet.class);
-        if(isDoOp(typicalLengthFacet)) {
-            final int typicalLength = typicalLengthFacet.value();
-            if(typicalLength > 0) {
-                propertyLayoutData.setTypicalLength(typicalLength);
-            }
-        }
-    }
-
-
-    @Programmatic
-    @Override
-    public void minimal(final G grid, final Class<?> domainClass) {
-        normalize(grid, domainClass);
-        grid.visit(new Grid.VisitorAdapter() {
-            @Override
-            public void visit(final ActionLayoutData actionLayoutData) {
-                actionLayoutData.getOwner().getActions().remove(actionLayoutData);
-            }
-
-            @Override
-            public void visit(final CollectionLayoutData collectionLayoutData) {
-                collectionLayoutData.getOwner().getCollections().remove(collectionLayoutData);
-            }
-
-            @Override
-            public void visit(final PropertyLayoutData propertyLayoutData) {
-                propertyLayoutData.getOwner().getProperties().remove(propertyLayoutData);
-            }
-
-            @Override
-            public void visit(final DomainObjectLayoutData domainObjectLayoutData) {
-                final DomainObjectLayoutDataOwner owner = domainObjectLayoutData.getOwner();
-                owner.setDomainObject(new DomainObjectLayoutData());
-            }
-        });
-    }
-
-
-    // //////////////////////////////////////
-
-    protected SpecificationLoader specificationLookup;
-
-    public void setSpecificationLoader(final SpecificationLoader specificationLookup) {
-        this.specificationLookup = specificationLookup;
-    }
-
-    @Inject
-    protected TranslationService translationService;
-
-    @Inject
-    protected JaxbService jaxbService;
-
-    @Inject
-    protected DomainObjectContainer container;
-
-
-    protected DeploymentCategory deploymentCategory;
-
-    @Programmatic
-    @Override
-    public void setDeploymentCategory(final DeploymentCategory deploymentCategory) {
-        this.deploymentCategory = deploymentCategory;
-    }
-
-
-}

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/GridLoaderServiceDefault.java
----------------------------------------------------------------------
diff --git a/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/GridLoaderServiceDefault.java b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/GridLoaderServiceDefault.java
new file mode 100644
index 0000000..a62cd54
--- /dev/null
+++ b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/GridLoaderServiceDefault.java
@@ -0,0 +1,185 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT 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.isis.core.metamodel.services.grid;
+
+import java.io.IOException;
+import java.net.URL;
+import java.nio.charset.Charset;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+import javax.annotation.PostConstruct;
+import javax.inject.Inject;
+import javax.xml.bind.JAXBContext;
+
+import com.google.common.base.Function;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.Maps;
+import com.google.common.io.Resources;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.isis.applib.DomainObjectContainer;
+import org.apache.isis.applib.annotation.DomainService;
+import org.apache.isis.applib.annotation.NatureOfService;
+import org.apache.isis.applib.annotation.Programmatic;
+import org.apache.isis.applib.layout.component.Grid;
+import org.apache.isis.applib.services.grid.GridSystemService;
+import org.apache.isis.applib.services.grid.GridLoaderService;
+import org.apache.isis.applib.services.jaxb.JaxbService;
+import org.apache.isis.core.metamodel.deployment.DeploymentCategory;
+import org.apache.isis.core.metamodel.deployment.DeploymentCategoryAware;
+
+@DomainService(
+        nature = NatureOfService.DOMAIN
+)
+public class GridLoaderServiceDefault implements GridLoaderService, DeploymentCategoryAware {
+
+    private static final Logger LOG = LoggerFactory.getLogger(GridLoaderServiceDefault.class);
+
+
+    // for better logging messages (used only in prototyping mode)
+    private final Map<Class<?>, String> badXmlByClass = Maps.newHashMap();
+
+    // cache (used only in prototyping mode)
+    private final Map<String, Grid> pageByXml = Maps.newHashMap();
+
+    private List<Class<? extends Grid>> pageImplementations;
+
+
+
+    @PostConstruct
+    public void init(){
+        pageImplementations = FluentIterable.from(gridSystemServices)
+                .transform(new Function<GridSystemService, Class<? extends Grid>>() {
+                    @Override
+                    public Class<? extends Grid> apply(final GridSystemService gridSystemService) {
+                        return gridSystemService.gridImplementation();
+                    }
+                })
+                .toList();
+    }
+
+
+    @Override
+    @Programmatic
+    public boolean existsFor(final Class<?> domainClass) {
+        final URL resource = Resources.getResource(domainClass, resourceNameFor(domainClass));
+        return resource != null;
+    }
+
+    @Override
+    @Programmatic
+    public Grid load(final Class<?> domainClass) {
+        final String resourceName = resourceNameFor(domainClass);
+        final String xml;
+        try {
+            xml = resourceContentOf(domainClass, resourceName);
+        } catch (IOException | IllegalArgumentException ex) {
+
+            if(LOG.isDebugEnabled()) {
+                final String message = String .format(
+                        "Failed to locate file %s (relative to %s.class); ex: %s)",
+                        resourceName, domainClass.getName(), ex.getMessage());
+
+                LOG.debug(message);
+            }
+            return null;
+        }
+
+        if(!deploymentCategory.isProduction()) {
+            final Grid grid = pageByXml.get(xml);
+            if(grid != null) {
+                return grid;
+            }
+
+            final String badXml = badXmlByClass.get(domainClass);
+            if(badXml != null) {
+                if(Objects.equals(xml, badXml)) {
+                    // seen this before and already logged; just quit
+                    return null;
+                } else {
+                    // this different XML might be good
+                    badXmlByClass.remove(domainClass);
+                }
+            }
+        }
+
+        try {
+            // all known implementations of Page
+            final JAXBContext context = JAXBContext.newInstance(pageImplementations.toArray(new Class[0]));
+
+            final Grid grid = (Grid) jaxbService.fromXml(context, xml);
+            grid.setDomainClass(domainClass);
+            if(!deploymentCategory.isProduction()) {
+                pageByXml.put(xml, grid);
+            }
+            return grid;
+        } catch(Exception ex) {
+
+            if(!deploymentCategory.isProduction()) {
+                // save fact that this was bad XML, so that we don't log again if called next time
+                badXmlByClass.put(domainClass, xml);
+            }
+
+            // note that we don't blacklist if the file exists but couldn't be parsed;
+            // the developer might fix so we will want to retry.
+            final String message = "Failed to parse " + resourceName + " file (" + ex.getMessage() + ")";
+            if(deploymentCategory.isPrototyping()) {
+                container.warnUser(message);
+            }
+            LOG.warn(message);
+
+            return null;
+        }
+    }
+
+    private static String resourceContentOf(final Class<?> cls, final String resourceName) throws IOException {
+        final URL url = Resources.getResource(cls, resourceName);
+        return Resources.toString(url, Charset.defaultCharset());
+    }
+
+    private String resourceNameFor(final Class<?> domainClass) {
+        return domainClass.getSimpleName() + ".layout.xml";
+    }
+
+
+
+    //region > injected dependencies
+
+
+    private DeploymentCategory deploymentCategory;
+
+    @Override
+    public void setDeploymentCategory(final DeploymentCategory deploymentCategory) {
+        this.deploymentCategory = deploymentCategory;
+    }
+
+    @Inject
+    DomainObjectContainer container;
+
+    @Inject
+    JaxbService jaxbService;
+
+    @Inject
+    List<GridSystemService> gridSystemServices;
+    //endregion
+
+
+}

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/GridServiceDefault.java
----------------------------------------------------------------------
diff --git a/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/GridServiceDefault.java b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/GridServiceDefault.java
new file mode 100644
index 0000000..9c116f7
--- /dev/null
+++ b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/GridServiceDefault.java
@@ -0,0 +1,204 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT 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.isis.core.metamodel.services.grid;
+
+import java.util.List;
+
+import javax.annotation.Nullable;
+import javax.inject.Inject;
+
+import com.google.common.base.Function;
+import com.google.common.base.Joiner;
+import com.google.common.base.Predicate;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.Lists;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.isis.applib.annotation.DomainService;
+import org.apache.isis.applib.annotation.NatureOfService;
+import org.apache.isis.applib.annotation.Programmatic;
+import org.apache.isis.applib.layout.component.Grid;
+import org.apache.isis.applib.services.grid.GridSystemService;
+import org.apache.isis.applib.services.grid.GridLoaderService;
+import org.apache.isis.applib.services.grid.GridService;
+
+@DomainService(
+        nature = NatureOfService.DOMAIN
+)
+public class GridServiceDefault implements GridService {
+
+    private static final Logger LOG = LoggerFactory.getLogger(GridServiceDefault.class);
+
+    public static final String COMMON_TNS = "http://isis.apache.org/applib/layout/component";
+    public static final String COMMON_SCHEMA_LOCATION = "http://isis.apache.org/applib/layout/component/component.xsd";
+
+
+    // //////////////////////////////////////
+
+    @Override
+    @Programmatic
+    public boolean existsFor(final Class<?> domainClass) {
+        return gridLoaderService.existsFor(domainClass);
+    }
+
+    @Override
+    @Programmatic
+    public Grid load(final Class<?> domainClass) {
+        return gridLoaderService.load(domainClass);
+    }
+
+    // //////////////////////////////////////
+
+    @Override
+    @Programmatic
+    public Grid defaultGridFor(Class<?> domainClass) {
+
+        for (GridSystemService gridSystemService : gridNormalizerServices()) {
+            Grid grid = gridSystemService.defaultGrid(domainClass);
+            if(grid != null) {
+                return grid;
+            }
+        }
+        throw new IllegalStateException("No GridNormalizerService available to create grid for '" + domainClass.getName() + "'");
+    }
+
+    @Override
+    public Grid normalize(final Grid grid) {
+
+        // if have .layout.json and then add a .layout.xml without restarting, then note that the .layout.xml won't
+        // be picked up.  To do so would require normalizing repeatedly in order to trample over the .layout.json's
+        // original facets
+        if(grid.isNormalized()) {
+            return grid;
+        }
+
+        final Class<?> domainClass = grid.getDomainClass();
+
+        for (GridSystemService gridSystemService : gridNormalizerServices()) {
+            gridSystemService.normalize(grid, domainClass);
+        }
+
+        final String tnsAndSchemaLocation = tnsAndSchemaLocation(grid);
+        grid.setTnsAndSchemaLocation(tnsAndSchemaLocation);
+
+        grid.setNormalized(true);
+
+        return grid;
+    }
+
+    @Override
+    @Programmatic
+    public Grid complete(final Grid grid) {
+
+        final Class<?> domainClass = grid.getDomainClass();
+        for (GridSystemService gridSystemService : gridNormalizerServices()) {
+            gridSystemService.complete(grid, domainClass);
+        }
+
+        return grid;
+    }
+
+    @Override
+    @Programmatic
+    public Grid minimal(final Grid grid) {
+
+        final Class<?> domainClass = grid.getDomainClass();
+        for (GridSystemService gridSystemService : gridNormalizerServices()) {
+            gridSystemService.minimal(grid, domainClass);
+        }
+
+        return grid;
+    }
+
+
+    /**
+     * Not public API, exposed only for testing.
+     */
+    @Programmatic
+    public String tnsAndSchemaLocation(final Grid grid) {
+        final List<String> parts = Lists.newArrayList();
+        parts.add(COMMON_TNS);
+        parts.add(COMMON_SCHEMA_LOCATION);
+        FluentIterable.from(gridSystemServices)
+                .filter(new Predicate<GridSystemService>() {
+                    @Override
+                    public boolean apply(final GridSystemService gridSystemService) {
+                        final Class<? extends Grid> gridImpl = gridSystemService.gridImplementation();
+                        return gridImpl.isAssignableFrom(grid.getClass());
+                    }
+                })
+                .transform(new Function<GridSystemService, Void>() {
+                    @Nullable @Override
+                    public Void apply(final GridSystemService gridSystemService) {
+                        parts.add(gridSystemService.tns());
+                        parts.add(gridSystemService.schemaLocation());
+                        return null;
+                    }
+                });
+        return Joiner.on(" ").join(parts);
+    }
+
+    ////////////////////////////////////////////////////////
+
+    private List<GridSystemService<?>> filteredGridSystemServices;
+
+    /**
+     * For all of the available {@link GridSystemService}s available, return only the first one for any that
+     * are for the same grid implementation.
+     *
+     * <p>
+     *   This allows default implementations (eg for bootstrap3) to be overridden while also allowing for the more
+     *   general idea of multiple implementations.
+     * </p>
+     */
+    @Programmatic
+    protected List<GridSystemService<?>> gridNormalizerServices() {
+
+        if (filteredGridSystemServices == null) {
+            List<GridSystemService<?>> services = Lists.newArrayList();
+
+            for (GridSystemService gridSystemService : this.gridSystemServices) {
+                final Class gridImplementation = gridSystemService.gridImplementation();
+                final boolean notSeenBefore = FluentIterable.from(services).filter(new Predicate<GridSystemService<?>>() {
+                    @Override public boolean apply(@Nullable final GridSystemService<?> gridNormalizerService) {
+                        return gridNormalizerService.gridImplementation() == gridImplementation;
+                    }
+                }).isEmpty();
+                if(notSeenBefore) {
+                    services.add(gridSystemService);
+                }
+            }
+
+            filteredGridSystemServices = services;
+
+        }
+        return filteredGridSystemServices;
+    }
+
+    ////////////////////////////////////////////////////////
+
+
+
+    @Inject
+    GridLoaderService gridLoaderService;
+
+    @Inject
+    List<GridSystemService> gridSystemServices;
+
+}

http://git-wip-us.apache.org/repos/asf/isis/blob/5306b011/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/GridSystemServiceAbstract.java
----------------------------------------------------------------------
diff --git a/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/GridSystemServiceAbstract.java b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/GridSystemServiceAbstract.java
new file mode 100644
index 0000000..f0deaa6
--- /dev/null
+++ b/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/grid/GridSystemServiceAbstract.java
@@ -0,0 +1,686 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT 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.isis.core.metamodel.services.grid;
+
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import javax.inject.Inject;
+
+import com.google.common.base.Strings;
+import com.google.common.collect.Lists;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.isis.applib.DomainObjectContainer;
+import org.apache.isis.applib.annotation.ActionLayout;
+import org.apache.isis.applib.annotation.BookmarkPolicy;
+import org.apache.isis.applib.annotation.LabelPosition;
+import org.apache.isis.applib.annotation.Programmatic;
+import org.apache.isis.applib.annotation.Where;
+import org.apache.isis.applib.layout.component.ActionLayoutData;
+import org.apache.isis.applib.layout.component.ActionLayoutDataOwner;
+import org.apache.isis.applib.layout.component.CollectionLayoutData;
+import org.apache.isis.applib.layout.component.DomainObjectLayoutData;
+import org.apache.isis.applib.layout.component.DomainObjectLayoutDataOwner;
+import org.apache.isis.applib.layout.component.FieldSet;
+import org.apache.isis.applib.layout.component.Grid;
+import org.apache.isis.applib.layout.component.HasBookmarking;
+import org.apache.isis.applib.layout.component.HasCssClass;
+import org.apache.isis.applib.layout.component.HasCssClassFa;
+import org.apache.isis.applib.layout.component.HasDescribedAs;
+import org.apache.isis.applib.layout.component.HasHidden;
+import org.apache.isis.applib.layout.component.HasNamed;
+import org.apache.isis.applib.layout.component.PropertyLayoutData;
+import org.apache.isis.applib.services.grid.GridSystemService;
+import org.apache.isis.applib.services.i18n.TranslationService;
+import org.apache.isis.applib.services.jaxb.JaxbService;
+import org.apache.isis.core.metamodel.deployment.DeploymentCategory;
+import org.apache.isis.core.metamodel.deployment.DeploymentCategoryAware;
+import org.apache.isis.core.metamodel.facetapi.Facet;
+import org.apache.isis.core.metamodel.facetapi.FacetHolder;
+import org.apache.isis.core.metamodel.facetapi.FacetUtil;
+import org.apache.isis.core.metamodel.facets.actions.layout.ActionPositionFacetForActionXml;
+import org.apache.isis.core.metamodel.facets.actions.layout.BookmarkPolicyFacetForActionXml;
+import org.apache.isis.core.metamodel.facets.actions.layout.CssClassFaFacetForActionXml;
+import org.apache.isis.core.metamodel.facets.actions.layout.CssClassFacetForActionXml;
+import org.apache.isis.core.metamodel.facets.actions.layout.DescribedAsFacetForActionXml;
+import org.apache.isis.core.metamodel.facets.actions.layout.HiddenFacetForActionLayoutXml;
+import org.apache.isis.core.metamodel.facets.actions.layout.NamedFacetForActionXml;
+import org.apache.isis.core.metamodel.facets.actions.position.ActionPositionFacet;
+import org.apache.isis.core.metamodel.facets.all.describedas.DescribedAsFacet;
+import org.apache.isis.core.metamodel.facets.all.hide.HiddenFacet;
+import org.apache.isis.core.metamodel.facets.all.named.NamedFacet;
+import org.apache.isis.core.metamodel.facets.collections.collection.defaultview.DefaultViewFacet;
+import org.apache.isis.core.metamodel.facets.collections.layout.CssClassFacetForCollectionXml;
+import org.apache.isis.core.metamodel.facets.collections.layout.DefaultViewFacetForCollectionXml;
+import org.apache.isis.core.metamodel.facets.collections.layout.DescribedAsFacetForCollectionXml;
+import org.apache.isis.core.metamodel.facets.collections.layout.HiddenFacetForCollectionXml;
+import org.apache.isis.core.metamodel.facets.collections.layout.NamedFacetForCollectionXml;
+import org.apache.isis.core.metamodel.facets.collections.layout.PagedFacetForCollectionXml;
+import org.apache.isis.core.metamodel.facets.collections.layout.SortedByFacetForCollectionXml;
+import org.apache.isis.core.metamodel.facets.collections.sortedby.SortedByFacet;
+import org.apache.isis.core.metamodel.facets.members.cssclass.CssClassFacet;
+import org.apache.isis.core.metamodel.facets.members.cssclassfa.CssClassFaFacet;
+import org.apache.isis.core.metamodel.facets.members.cssclassfa.CssClassFaPosition;
+import org.apache.isis.core.metamodel.facets.members.order.annotprop.MemberOrderFacetXml;
+import org.apache.isis.core.metamodel.facets.object.bookmarkpolicy.BookmarkPolicyFacet;
+import org.apache.isis.core.metamodel.facets.object.paged.PagedFacet;
+import org.apache.isis.core.metamodel.facets.object.plural.PluralFacet;
+import org.apache.isis.core.metamodel.facets.objectvalue.labelat.LabelAtFacet;
+import org.apache.isis.core.metamodel.facets.objectvalue.multiline.MultiLineFacet;
+import org.apache.isis.core.metamodel.facets.objectvalue.renderedadjusted.RenderedAdjustedFacet;
+import org.apache.isis.core.metamodel.facets.objectvalue.typicallen.TypicalLengthFacet;
+import org.apache.isis.core.metamodel.facets.properties.propertylayout.CssClassFacetForPropertyXml;
+import org.apache.isis.core.metamodel.facets.properties.propertylayout.DescribedAsFacetForPropertyXml;
+import org.apache.isis.core.metamodel.facets.properties.propertylayout.HiddenFacetForPropertyXml;
+import org.apache.isis.core.metamodel.facets.properties.propertylayout.LabelAtFacetForPropertyXml;
+import org.apache.isis.core.metamodel.facets.properties.propertylayout.MultiLineFacetForPropertyXml;
+import org.apache.isis.core.metamodel.facets.properties.propertylayout.NamedFacetForPropertyXml;
+import org.apache.isis.core.metamodel.facets.properties.propertylayout.RenderedAdjustedFacetForPropertyXml;
+import org.apache.isis.core.metamodel.facets.properties.propertylayout.TypicalLengthFacetForPropertyXml;
+import org.apache.isis.core.metamodel.spec.ObjectSpecification;
+import org.apache.isis.core.metamodel.spec.SpecificationLoader;
+import org.apache.isis.core.metamodel.spec.SpecificationLoaderAware;
+import org.apache.isis.core.metamodel.spec.feature.Contributed;
+import org.apache.isis.core.metamodel.spec.feature.ObjectAction;
+import org.apache.isis.core.metamodel.spec.feature.ObjectAssociation;
+import org.apache.isis.core.metamodel.spec.feature.ObjectMember;
+import org.apache.isis.core.metamodel.spec.feature.OneToManyAssociation;
+import org.apache.isis.core.metamodel.spec.feature.OneToOneAssociation;
+
+public abstract class GridSystemServiceAbstract<G extends Grid>
+        implements GridSystemService<G>, SpecificationLoaderAware, DeploymentCategoryAware {
+
+    private static final Logger LOG = LoggerFactory.getLogger(GridSystemServiceAbstract.class);
+
+    private final Class<G> gridImplementation;
+    private final String tns;
+    private final String schemaLocation;
+
+    public GridSystemServiceAbstract(
+            final Class<G> gridImplementation,
+            final String tns,
+            final String schemaLocation) {
+        this.gridImplementation = gridImplementation;
+        this.tns = tns;
+        this.schemaLocation = schemaLocation;
+    }
+
+    // //////////////////////////////////////
+
+    @Programmatic
+    @Override
+    public Class<G> gridImplementation() {
+        return gridImplementation;
+    }
+
+    @Programmatic
+    @Override
+    public String tns() {
+        return tns;
+    }
+
+    @Programmatic
+    @Override
+    public String schemaLocation() {
+        return schemaLocation;
+    }
+
+
+    // //////////////////////////////////////
+
+    @Programmatic
+    @Override
+    public void normalize(final G grid, final Class<?> domainClass) {
+
+        if(!gridImplementation.isAssignableFrom(grid.getClass())) {
+            // ignore any other grid implementations
+            return;
+        }
+
+        final boolean valid =
+                validateAndNormalize(
+                    grid, domainClass);
+        if (valid) {
+            overwriteFacets(grid, domainClass);
+            if(LOG.isDebugEnabled()) {
+                LOG.debug("Grid:\n\n" + jaxbService.toXml(grid) + "\n\n");
+            }
+        } else {
+
+            if(!deploymentCategory.isProduction()) {
+                container.warnUser("Grid metadata errors for " + grid.getDomainClass().getName() + "; check the error log");
+            }
+            LOG.error("Grid metadata errors:\n\n" + jaxbService.toXml(grid) + "\n\n");
+        }
+    }
+
+
+    /**
+     * Mandatory hook method for subclasses, where they must ensure that all object members (properties, collections
+     * and actions) are in the grid metadata, typically by deriving this information from other existing metadata
+     * (eg facets from annotations) or just by applying default rules.
+     */
+    protected abstract boolean validateAndNormalize(
+            final Grid grid,
+            final Class<?> domainClass);
+
+
+    /**
+     * Overwrites (replaces) any existing facets in the metamodel with info taken from the grid.
+     *
+     * <p>
+     *     This code uses {@link FacetUtil#addOrReplaceFacet(Facet)} because the layout might be changed multiple times.
+     * </p>
+     */
+    protected void overwriteFacets(
+            final G fcGrid,
+            final Class<?> domainClass) {
+
+
+        final ObjectSpecification objectSpec = specificationLookup.loadSpecification(domainClass);
+
+        final Map<String, OneToOneAssociation> oneToOneAssociationById =
+                ObjectMember.Util.mapById(getOneToOneAssociations(objectSpec));
+        final Map<String, OneToManyAssociation> oneToManyAssociationById =
+                ObjectMember.Util.mapById(getOneToManyAssociations(objectSpec));
+        final Map<String, ObjectAction> objectActionById =
+                ObjectMember.Util.mapById(objectSpec.getObjectActions(Contributed.INCLUDED));
+
+
+        final AtomicInteger propertySequence = new AtomicInteger(0);
+        fcGrid.visit(new Grid.VisitorAdapter() {
+            private int collectionSequence = 1;
+
+            private int actionDomainObjectSequence = 1;
+            private int actionPropertyGroupSequence = 1;
+            private int actionPropertySequence = 1;
+            private int actionCollectionSequence = 1;
+
+            @Override
+            public void visit(final ActionLayoutData actionLayoutData) {
+                final ActionLayoutDataOwner actionLayoutDataOwner = actionLayoutData.getOwner();
+                final ObjectAction objectAction = objectActionById.get(actionLayoutData.getId());
+                if(objectAction == null) {
+                    return;
+                }
+
+                final String memberOrderName;
+                final int memberOrderSequence;
+                if(actionLayoutDataOwner instanceof FieldSet) {
+                    final FieldSet fieldSet = (FieldSet) actionLayoutDataOwner;
+                    final List<PropertyLayoutData> properties = fieldSet.getProperties();
+                    final PropertyLayoutData propertyLayoutData = properties.get(0); // any will do
+                    memberOrderName = propertyLayoutData.getId();
+                    memberOrderSequence = actionPropertyGroupSequence++;
+                } else if(actionLayoutDataOwner instanceof PropertyLayoutData) {
+                    final PropertyLayoutData propertyLayoutData = (PropertyLayoutData) actionLayoutDataOwner;
+                    memberOrderName = propertyLayoutData.getId();
+                    memberOrderSequence = actionPropertySequence++;
+                } else if(actionLayoutDataOwner instanceof CollectionLayoutData) {
+                    final CollectionLayoutData collectionLayoutData = (CollectionLayoutData) actionLayoutDataOwner;
+                    memberOrderName = collectionLayoutData.getId();
+                    memberOrderSequence = actionCollectionSequence++;
+                } else {
+                    // means' don't add: any existing metadata should be preserved
+                    memberOrderName = null;
+                    memberOrderSequence = actionDomainObjectSequence++;
+                }
+                if(memberOrderName != null) {
+                    FacetUtil.addOrReplaceFacet(
+                            new MemberOrderFacetXml(memberOrderName, "" + memberOrderSequence, translationService,
+                                    objectAction));
+                }
+
+                // fix up the action position if required
+                if(actionLayoutDataOwner instanceof FieldSet) {
+                    if(actionLayoutData.getPosition() == null ||
+                            actionLayoutData.getPosition() == org.apache.isis.applib.annotation.ActionLayout.Position.BELOW ||
+                            actionLayoutData.getPosition() == org.apache.isis.applib.annotation.ActionLayout.Position.RIGHT) {
+                        actionLayoutData.setPosition(org.apache.isis.applib.annotation.ActionLayout.Position.PANEL);
+                    }
+                } else if(actionLayoutDataOwner instanceof PropertyLayoutData) {
+                    if(actionLayoutData.getPosition() == null ||
+                            actionLayoutData.getPosition() == org.apache.isis.applib.annotation.ActionLayout.Position.PANEL_DROPDOWN ||
+                            actionLayoutData.getPosition() == org.apache.isis.applib.annotation.ActionLayout.Position.PANEL) {
+                        actionLayoutData.setPosition(org.apache.isis.applib.annotation.ActionLayout.Position.BELOW);
+                    }
+                } else {
+                    // doesn't do anything for DomainObject or Collection
+                    actionLayoutData.setPosition(null);
+                }
+
+                FacetUtil.addOrReplaceFacet(ActionPositionFacetForActionXml.create(actionLayoutData, objectAction));
+                FacetUtil.addOrReplaceFacet(BookmarkPolicyFacetForActionXml.create(actionLayoutData, objectAction));
+                FacetUtil.addOrReplaceFacet(CssClassFacetForActionXml.create(actionLayoutData, objectAction));
+                FacetUtil.addOrReplaceFacet(CssClassFaFacetForActionXml.create(actionLayoutData, objectAction));
+                FacetUtil.addOrReplaceFacet(DescribedAsFacetForActionXml.create(actionLayoutData, objectAction));
+                FacetUtil.addOrReplaceFacet(HiddenFacetForActionLayoutXml.create(actionLayoutData, objectAction));
+                FacetUtil.addOrReplaceFacet(NamedFacetForActionXml.create(actionLayoutData, objectAction));
+            }
+
+            @Override
+            public void visit(final PropertyLayoutData propertyLayoutData) {
+                final OneToOneAssociation oneToOneAssociation = oneToOneAssociationById.get(propertyLayoutData.getId());
+                if(oneToOneAssociation == null) {
+                    return;
+                }
+
+                FacetUtil.addOrReplaceFacet(CssClassFacetForPropertyXml.create(propertyLayoutData, oneToOneAssociation));
+                FacetUtil.addOrReplaceFacet(DescribedAsFacetForPropertyXml.create(propertyLayoutData, oneToOneAssociation));
+                FacetUtil.addOrReplaceFacet(HiddenFacetForPropertyXml.create(propertyLayoutData, oneToOneAssociation));
+                FacetUtil.addOrReplaceFacet(LabelAtFacetForPropertyXml.create(propertyLayoutData, oneToOneAssociation));
+                FacetUtil.addOrReplaceFacet(MultiLineFacetForPropertyXml.create(propertyLayoutData, oneToOneAssociation));
+                FacetUtil.addOrReplaceFacet(NamedFacetForPropertyXml.create(propertyLayoutData, oneToOneAssociation));
+                FacetUtil.addOrReplaceFacet(
+                        RenderedAdjustedFacetForPropertyXml.create(propertyLayoutData, oneToOneAssociation));
+                FacetUtil.addOrReplaceFacet(TypicalLengthFacetForPropertyXml.create(propertyLayoutData, oneToOneAssociation));
+
+                // @MemberOrder#name based on owning property group, @MemberOrder#sequence monotonically increasing
+                // nb for any given field set the sequence won't reset to zero; however this is what we want so that
+                // table columns are shown correctly (by fieldset, then property order within that fieldset).
+                final FieldSet fieldSet = propertyLayoutData.getOwner();
+                final String groupName = fieldSet.getName();
+                final String sequence = "" + (propertySequence.incrementAndGet());
+                FacetUtil.addOrReplaceFacet(
+                        new MemberOrderFacetXml(groupName, sequence, translationService, oneToOneAssociation));
+            }
+
+            @Override
+            public void visit(final CollectionLayoutData collectionLayoutData) {
+                final OneToManyAssociation oneToManyAssociation = oneToManyAssociationById.get(collectionLayoutData.getId());
+                if(oneToManyAssociation == null) {
+                    return;
+                }
+
+                FacetUtil.addOrReplaceFacet(CssClassFacetForCollectionXml.create(collectionLayoutData, oneToManyAssociation));
+                FacetUtil.addOrReplaceFacet(
+                        DefaultViewFacetForCollectionXml.create(collectionLayoutData, oneToManyAssociation));
+                FacetUtil.addOrReplaceFacet(
+                        DescribedAsFacetForCollectionXml.create(collectionLayoutData, oneToManyAssociation));
+                FacetUtil.addOrReplaceFacet(HiddenFacetForCollectionXml.create(collectionLayoutData, oneToManyAssociation));
+                FacetUtil.addOrReplaceFacet(NamedFacetForCollectionXml.create(collectionLayoutData, oneToManyAssociation));
+                FacetUtil.addOrReplaceFacet(PagedFacetForCollectionXml.create(collectionLayoutData, oneToManyAssociation));
+                FacetUtil.addOrReplaceFacet(SortedByFacetForCollectionXml.create(collectionLayoutData, oneToManyAssociation));
+
+                // @MemberOrder#name based on the collection's id (so that each has a single "member group")
+                final String groupName = collectionLayoutData.getId();
+                final String sequence = "" + collectionSequence++;
+                FacetUtil.addOrReplaceFacet(
+                        new MemberOrderFacetXml(groupName, sequence, translationService, oneToManyAssociation));
+            }
+        });
+    }
+
+
+    protected static List<OneToOneAssociation> getOneToOneAssociations(final ObjectSpecification objectSpec) {
+        List associations = objectSpec.getAssociations(Contributed.INCLUDED, ObjectAssociation.Filters.PROPERTIES);
+        return associations;
+    }
+    protected  static List<OneToManyAssociation> getOneToManyAssociations(final ObjectSpecification objectSpec) {
+        List associations = objectSpec.getAssociations(Contributed.INCLUDED, ObjectAssociation.Filters.COLLECTIONS);
+        return associations;
+    }
+
+
+
+    protected static class Tuple<T> {
+        public final T first;
+        public final T second;
+        private Tuple(final T first, final T second) {
+            this.first = first;
+            this.second = second;
+        }
+        public static <T> Tuple<T> of(final T first, final T second) {
+            return new Tuple<>(first, second);
+        }
+    }
+
+
+    /**
+     * Returns a 2-element tuple of [first-second, second-first]
+     */
+    protected static <T> Tuple<List<T>> surplusAndMissing(final Collection<T> first, final Collection<T> second){
+        final List<T> firstNotSecond = Lists.newArrayList(first);
+        firstNotSecond.removeAll(second);
+        final List<T> secondNotFirst = Lists.newArrayList(second);
+        secondNotFirst.removeAll(first);
+        return Tuple.of(firstNotSecond, secondNotFirst);
+    }
+
+
+
+    // //////////////////////////////////////
+
+    @Programmatic
+    @Override
+    public void complete(final G grid, final Class<?> domainClass) {
+        normalize(grid, domainClass);
+
+        final ObjectSpecification objectSpec = specificationLookup.loadSpecification(domainClass);
+
+        grid.visit(new Grid.VisitorAdapter() {
+
+            @Override
+            public void visit(final ActionLayoutData actionLayoutData) {
+                final ObjectAction objectAction = objectSpec.getObjectAction(actionLayoutData.getId());
+
+                setBookmarkingIfAny(actionLayoutData, objectAction);
+                setCssClassIfAny(actionLayoutData, objectAction);
+                setCssClassFaIfAny(actionLayoutData, objectAction);
+                setDescribedAsIfAny(actionLayoutData, objectAction);
+                setHiddenIfAny(actionLayoutData, objectAction);
+                setNamedIfAny(actionLayoutData, objectAction);
+                setActionPositionIfAny(actionLayoutData, objectAction);
+            }
+
+            @Override
+            public void visit(final CollectionLayoutData collectionLayoutData) {
+                final ObjectAssociation collection = objectSpec.getAssociation(collectionLayoutData.getId());
+
+                setCssClassIfAny(collectionLayoutData, collection);
+                setDefaultViewIfAny(collectionLayoutData, collection);
+                setDescribedAsIfAny(collectionLayoutData, collection);
+                setHiddenIfAny(collectionLayoutData, collection);
+                setNamedIfAny(collectionLayoutData, collection);
+                setPagedIfAny(collectionLayoutData, collection);
+                setSortedByIfAny(collectionLayoutData, collection);
+            }
+
+            @Override
+            public void visit(final PropertyLayoutData propertyLayoutData) {
+                final ObjectAssociation property = objectSpec.getAssociation(propertyLayoutData.getId());
+
+                setCssClassIfAny(propertyLayoutData, property);
+                setDescribedAsIfAny(propertyLayoutData, property);
+                setHiddenIfAny(propertyLayoutData, property);
+                setNamedIfAny(propertyLayoutData, property);
+                setLabelPositionIfAny(propertyLayoutData, property);
+                setMultiLineIfAny(propertyLayoutData, property);
+                setRenderedAsDayBeforeIfAny(propertyLayoutData, property);
+                setTypicalLengthIfAny(propertyLayoutData, property);
+            }
+
+            @Override
+            public void visit(final DomainObjectLayoutData domainObjectLayoutData) {
+                setBookmarkingIfAny(domainObjectLayoutData, objectSpec);
+                setCssClassIfAny(domainObjectLayoutData, objectSpec);
+                setCssClassFaIfAny(domainObjectLayoutData, objectSpec);
+                setDescribedAsIfAny(domainObjectLayoutData, objectSpec);
+                setNamedIfAny(domainObjectLayoutData, objectSpec);
+                setPluralIfAny(domainObjectLayoutData, objectSpec);
+            }
+        });
+    }
+
+    private static boolean isDoOp(final Facet facet) {
+        return facet != null && !facet.isNoop();
+    }
+
+    protected void setBookmarkingIfAny(
+            final HasBookmarking hasBookmarking,
+            final FacetHolder facetHolder) {
+        final BookmarkPolicyFacet bookmarkPolicyFacet = facetHolder.getFacet(BookmarkPolicyFacet.class);
+        if(isDoOp(bookmarkPolicyFacet)) {
+            final BookmarkPolicy bookmarking = bookmarkPolicyFacet.value();
+            if(bookmarking != null) {
+                hasBookmarking.setBookmarking(bookmarking);
+            }
+        }
+    }
+
+    protected void setCssClassIfAny(
+            final HasCssClass hasCssClass,
+            final FacetHolder facetHolder) {
+        final CssClassFacet cssClassFacet = facetHolder.getFacet(CssClassFacet.class);
+        if(isDoOp(cssClassFacet)) {
+            try {
+                // try...finally because CSS class may vary by object, and we pass in only null
+                final String cssClass = cssClassFacet.cssClass(null);
+                if(!Strings.isNullOrEmpty(cssClass)) {
+                    hasCssClass.setCssClass(cssClass);
+                }
+            } catch(Exception ignore) {
+                // ignore
+            }
+        }
+    }
+
+    protected void setCssClassFaIfAny(
+            final HasCssClassFa hasCssClassFa,
+            final FacetHolder facetHolder) {
+        final CssClassFaFacet cssClassFaFacet = facetHolder.getFacet(CssClassFaFacet.class);
+        if (isDoOp(cssClassFaFacet)) {
+            final String cssClassFa = cssClassFaFacet.value();
+            final CssClassFaPosition position = cssClassFaFacet.getPosition();
+            if(!Strings.isNullOrEmpty(cssClassFa)) {
+                hasCssClassFa.setCssClassFa(cssClassFa);
+                hasCssClassFa.setCssClassFaPosition(position.toActionLayoutPosition());
+            }
+        }
+    }
+
+    protected void setDefaultViewIfAny(
+            final CollectionLayoutData collectionLayoutData,
+            final FacetHolder facetHolder) {
+        final DefaultViewFacet defaultViewFacet = facetHolder.getFacet(DefaultViewFacet.class);
+        if(isDoOp(defaultViewFacet)) {
+            final String defaultView = defaultViewFacet.value();
+            if(!Strings.isNullOrEmpty(defaultView)) {
+                collectionLayoutData.setDefaultView(defaultView);
+            }
+        }
+    }
+
+    protected void setDescribedAsIfAny(
+            final HasDescribedAs hasDescribedAs,
+            final FacetHolder facetHolder) {
+        final DescribedAsFacet describedAsFacet = facetHolder.getFacet(DescribedAsFacet.class);
+        if(isDoOp(describedAsFacet)) {
+            final String describedAs = describedAsFacet.value();
+            if(!Strings.isNullOrEmpty(describedAs)) {
+                hasDescribedAs.setDescribedAs(describedAs);
+            }
+        }
+    }
+
+    protected void setHiddenIfAny(
+            final HasHidden hasHidden,
+            final FacetHolder facetHolder) {
+        final HiddenFacet hiddenFacet = facetHolder.getFacet(HiddenFacet.class);
+        if (isDoOp(hiddenFacet)) {
+            final Where where = hiddenFacet.where();
+            if(where != null) {
+                hasHidden.setHidden(where);
+            }
+        }
+    }
+
+    protected void setLabelPositionIfAny(
+            final PropertyLayoutData propertyLayoutData,
+            final FacetHolder facetHolder) {
+        final LabelAtFacet labelAtFacet = facetHolder.getFacet(LabelAtFacet.class);
+        if(isDoOp(labelAtFacet)) {
+            final LabelPosition labelPosition = labelAtFacet.label();
+            if(labelPosition != null) {
+                propertyLayoutData.setLabelPosition(labelPosition);
+            }
+        }
+    }
+
+    protected void setMultiLineIfAny(
+            final PropertyLayoutData propertyLayoutData,
+            final FacetHolder facetHolder) {
+        final MultiLineFacet multiLineFacet = facetHolder.getFacet(MultiLineFacet.class);
+        if(isDoOp(multiLineFacet)) {
+            final int numberOfLines = multiLineFacet.numberOfLines();
+            if(numberOfLines > 0) {
+                propertyLayoutData.setMultiLine(numberOfLines);
+            }
+        }
+    }
+
+    protected void setNamedIfAny(
+            final HasNamed hasNamed,
+            final FacetHolder facetHolder) {
+        final NamedFacet namedFacet = facetHolder.getFacet(NamedFacet.class);
+        if(isDoOp(namedFacet)) {
+            final String named = namedFacet.value();
+            if(!Strings.isNullOrEmpty(named)){
+                hasNamed.setNamed(named);
+            }
+            final boolean escaped = namedFacet.escaped();
+            if(!escaped) {
+                hasNamed.setNamedEscaped(escaped);
+            }
+        }
+    }
+
+    protected void setPagedIfAny(
+            final CollectionLayoutData collectionLayoutData,
+            final FacetHolder facetHolder) {
+        final PagedFacet pagedFacet = facetHolder.getFacet(PagedFacet.class);
+        if(isDoOp(pagedFacet)) {
+            final int value = pagedFacet.value();
+            if(value > 0) {
+                collectionLayoutData.setPaged(value);
+            }
+        }
+    }
+
+    protected void setPluralIfAny(
+            final DomainObjectLayoutData domainObjectLayoutData,
+            final FacetHolder facetHolder) {
+        final PluralFacet pluralFacet = facetHolder.getFacet(PluralFacet.class);
+        if(isDoOp(pluralFacet)) {
+            final String plural = pluralFacet.value();
+            if(!Strings.isNullOrEmpty(plural)) {
+                domainObjectLayoutData.setPlural(plural);
+            }
+        }
+    }
+
+
+    protected void setActionPositionIfAny(
+            final ActionLayoutData actionLayoutData,
+            final FacetHolder facetHolder) {
+        final ActionPositionFacet actionPositionFacet = facetHolder.getFacet(ActionPositionFacet.class);
+        if(isDoOp(actionPositionFacet)) {
+            final ActionLayout.Position position = actionPositionFacet.position();
+            if(position != null) {
+                actionLayoutData.setPosition(position);
+            }
+        }
+    }
+
+    protected void setRenderedAsDayBeforeIfAny(
+            final PropertyLayoutData propertyLayoutData,
+            final FacetHolder facetHolder) {
+        final RenderedAdjustedFacet renderedAdjustedFacet = facetHolder.getFacet(RenderedAdjustedFacet.class);
+        if(isDoOp(renderedAdjustedFacet)) {
+            final int adjusted = renderedAdjustedFacet.value();
+            propertyLayoutData.setRenderedAsDayBefore(adjusted != 0);
+        }
+    }
+
+    protected void setSortedByIfAny(
+            final CollectionLayoutData collectionLayoutData,
+            final FacetHolder facetHolder) {
+        final SortedByFacet sortedByFacet = facetHolder.getFacet(SortedByFacet.class);
+        if(isDoOp(sortedByFacet)) {
+            final Class<? extends Comparator<?>> className = sortedByFacet.value();
+            if(className != null) {
+                collectionLayoutData.setSortedBy(className.getCanonicalName());
+            }
+        }
+    }
+
+    protected void setTypicalLengthIfAny(
+            final PropertyLayoutData propertyLayoutData,
+            final FacetHolder facetHolder) {
+        final TypicalLengthFacet typicalLengthFacet = facetHolder.getFacet(TypicalLengthFacet.class);
+        if(isDoOp(typicalLengthFacet)) {
+            final int typicalLength = typicalLengthFacet.value();
+            if(typicalLength > 0) {
+                propertyLayoutData.setTypicalLength(typicalLength);
+            }
+        }
+    }
+
+
+    @Programmatic
+    @Override
+    public void minimal(final G grid, final Class<?> domainClass) {
+        normalize(grid, domainClass);
+        grid.visit(new Grid.VisitorAdapter() {
+            @Override
+            public void visit(final ActionLayoutData actionLayoutData) {
+                actionLayoutData.getOwner().getActions().remove(actionLayoutData);
+            }
+
+            @Override
+            public void visit(final CollectionLayoutData collectionLayoutData) {
+                collectionLayoutData.getOwner().getCollections().remove(collectionLayoutData);
+            }
+
+            @Override
+            public void visit(final PropertyLayoutData propertyLayoutData) {
+                propertyLayoutData.getOwner().getProperties().remove(propertyLayoutData);
+            }
+
+            @Override
+            public void visit(final DomainObjectLayoutData domainObjectLayoutData) {
+                final DomainObjectLayoutDataOwner owner = domainObjectLayoutData.getOwner();
+                owner.setDomainObject(new DomainObjectLayoutData());
+            }
+        });
+    }
+
+
+    // //////////////////////////////////////
+
+    protected SpecificationLoader specificationLookup;
+
+    public void setSpecificationLoader(final SpecificationLoader specificationLookup) {
+        this.specificationLookup = specificationLookup;
+    }
+
+    @Inject
+    protected TranslationService translationService;
+
+    @Inject
+    protected JaxbService jaxbService;
+
+    @Inject
+    protected DomainObjectContainer container;
+
+
+    protected DeploymentCategory deploymentCategory;
+
+    @Programmatic
+    @Override
+    public void setDeploymentCategory(final DeploymentCategory deploymentCategory) {
+        this.deploymentCategory = deploymentCategory;
+    }
+
+
+}