http://git-wip-us.apache.org/repos/asf/isis/blob/2f2714cc/adocs/documentation/src/main/asciidoc/guides/ugfun/_ugfun_programming-model_mixins.adoc ---------------------------------------------------------------------- diff --git a/adocs/documentation/src/main/asciidoc/guides/ugfun/_ugfun_programming-model_mixins.adoc b/adocs/documentation/src/main/asciidoc/guides/ugfun/_ugfun_programming-model_mixins.adoc new file mode 100644 index 0000000..1a0a9a3 --- /dev/null +++ b/adocs/documentation/src/main/asciidoc/guides/ugfun/_ugfun_programming-model_mixins.adoc @@ -0,0 +1,346 @@ +[[_ugfun_programming-model_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/ + + + + +Syntactically, a mixin is defined using either the xref:../rgant/rgant.adoc#_rgant_Mixin[`@Mixin`] annotation or using xref:../rgant/rgant.adoc#_rgant_DomainObject_nature[`@DomainObject#nature()`] attribute (specifying a nature of `Nature.MIXIN`). + + + +[source,java] +---- +@Mixin(method="coll") // <1> +public class Customer_orders { // <2> + + private final Customer customer; + public Customer_orders(final Customer customer) { // <3> + this.customer = customer; + } + + @Action(semantics=SemanticsOf.SAFE) // <4> + @ActionLayout(contributed=Contributed.AS_ASSOCIATION) // <4> + @CollectionLayout(render=RenderType.EAGERLY) + public List<Order> coll() { // <1> + return repositoryService.findOrdersFor(customer); + } + + @Inject + RepositoryService repositoryService; +} +---- +<1> indicates that this is a mixin, with "coll" as the name of the main method +<2> The contributed member is inferred from the name, after the "_"; in other words "orders" +<3> The mixee is `Customer`. +This could also be an interface. +<4> Indicates that the action should be interpreted as a collection. +This requires that the action has safe semantics, ie does not alter state/no side-effects. + + + + + + + +'''' +'''' + +== Contributed services + +Contributed services provide many of the same benefits as xref:../ugbtb/ugbtb.adoc#_ugbtb_decoupling_mixins[mixins]; +indeed mixins are an evolution and refinement of the contributions concept. + +[WARNING] +==== +It's possible that contributions may be deprecated and eventually removed in a future version of the framework, to be replaced entirely by mixins. +==== + +The main difference between contributed services and mixins is that the actions of a contributed service will +contribute to _all_ the parameters of its actions, whereas a mixin only contributes to the type accepted in its +constructor. Also, contributed services are long-lived +singletons, whereas mixins are instantiated as required (by the framework) and then discarded almost immediately. + +[NOTE] +==== +There's further useful information on contributed services in the reference guide, discussing the xref:../rgant/rgant.adoc#_rgant-DomainService_nature[@DomainService#nature()] attribute, for the `NatureOfService.VIEW_CONTRIBUTIONS_ONLY` nature. +==== + + +=== Syntax + +Any n-parameter action provided by a service will automatically be contributed to the list of actions for each of its (entity) parameters. From the viewpoint of the entity the action is called a contributed action. + +For example, given a service: + +[source,java] +---- +public interface Library { + public Loan borrow(Loanable l, Borrower b); +} +---- + +and the entities: + +[source,java] +---- +public class Book implements Loanable { ... } +---- + +and + +[source,java] +---- +public class LibraryMember implements Borrower { ... } +---- + +then the `borrow(...)` action will be contributed to both `Book` and to `LibraryMember`. + +This is an important capability because it helps to decouple the concrete classes from the services. + +If necessary, though, this behaviour can be suppressed by annotating the service action with `@org.apache.isis.applib.annotations.NotContributed`. + +For example: + +[source,java] +---- +public interface Library { + @NotContributed + public Loan borrow(Loanable l, Borrower b); +} +---- + +If annotated at the interface level, then the annotation will be inherited by every concrete class. Alternatively the annotation can be applied at the implementation class level and only apply to that particular implementation. + +Note that an action annotated as being `@NotContributed` will still appear in the service menu for the service. If an action should neither be contributed nor appear in service menu items, then simply annotate it as `@Hidden`. + + +## Contributed Action + +NOTE: FIXME + +## Contributed Property + +NOTE: FIXME + +## Contributed Collection + +NOTE: FIXME + + + + + +== Contributed Collection + +The example below shows how to contribute a collection: + +[source,java] +---- +@Mixin +public class DocumentHolderDocuments { + + private final DocumentHolder holder; + public DocumentHolderDocuments(DocumentHolder holder) { this.holder = holder; } + + @Action(semantics=SemanticsOf.SAFE) // <1> + @ActionLayout(contributed = Contributed.AS_ASSOCIATION) // <2> + @CollectionLayout(render = RenderType.EAGERLY) + public List<Document> documents() { // <3> + ... + } + public boolean hideDocuments() { ... } // <4> +} +---- +<1> required; actions that have side-effects cannot be contributed as collections +<2> required; otherwise the mixin will default to being rendered as an action +<3> must accept no arguments. + The mixin is a collection rather than a property because the return type is a collection, not a scalar. +<4> supporting methods follow the usual naming conventions. + (That said, in the case of collections, because the collection is derived/read-only, the only supporting method that is relevant is `hideXxx()`). + +The above will result in a contributed collection for all types that implement/extend from `DocumentHolder` (so is probably for a mixin across modules). + + + +== Contributed Property + +Contributed properties are defined similarly, for example: + +[source,java] +---- +@Mixin +public class DocumentHolderMostRecentDocument { + + private final DocumentHolder holder; + public DocumentHolderDocuments(DocumentHolder holder) { this.holder = holder; } + + @Action(semantics=SemanticsOf.SAFE) // <1> + @ActionLayout(contributed = Contributed.AS_ASSOCIATION) // <2> + public Document> mostRecentDocument() { // <3> + ... + } + public boolean hideMostRecentDocument() { ... } // <4> +} +---- +<1> required; actions that have side-effects cannot be contributed as collections +<2> required; otherwise the mixin will default to being rendered as an action +<3> must accept no arguments. + The mixin is a property rather than a collection because the return type is a scalar. +<4> supporting methods follow the usual naming conventions. + (That said, in the case of properties, because the property is derived/read-only, the only supporting method that is relevant is `hideXxx()`). + + +== Contributed Action + +Contributed properties are defined similarly, for example: + +[source,java] +---- +@Mixin +public class DocumentHolderAddDocument { + + private final DocumentHolder holder; + public DocumentHolderDocuments(DocumentHolder holder) { this.holder = holder; } + + @Action() + @ActionLayout(contributed = Contributed.AS_ACTION) // <1> + public Document> addDocument(Document doc) { + ... + } + public boolean hideAddDocument() { ... } // <2> +} +---- +<1> recommended +<2> supporting methods follow the usual naming conventions. + + +== Inferred Name + +Where the mixin follows the naming convention `SomeType_mixinName` then the method name can be abbreviated to "$$". +The mixin name is everything after the last '_'. + +For example: + +[source,java] +---- +@Mixin +public class DocumentHolder_documents { + + private final DocumentHolder holder; + public DocumentHolder_documents(DocumentHolder holder) { this.holder = holder; } + + @Action(semantics=SemanticsOf.SAFE) + @ActionLayout(contributed = Contributed.AS_ASSOCIATION) + @CollectionLayout(render = RenderType.EAGERLY) + public List<Document> $$() { // <1> + ... + } + public boolean hide$$() { ... } // <2> +} +---- +<1> using "$$" as the reserved method name +<2> supporting methods as usual + +The character "$" is also recognized as a separator between the mixin type and mixin name. +This is useful for mixins implemented as nested static types, discussed below. + + +== As Nested Static Classes + +As noted in the introduction, while mixins were originally introduced as a means of allowing contributions from one module to the types of another module, they are also a convenient mechanism for grouping functionality/behaviour against a concrete type. +All the methods and supporting methods end up in a single construct, and the dependency between that functionality and the rest of the object is made more explicit. + +When using mixins in this fashion, it is idiomatic to write the mixin as a nested static class, using the naming convention described above to reduce duplication. + +For example: + +[source,java] +---- +public class Customer { + + @Mixin + public static class placeOrder { // <1> + + private final Customer customer; + public documents(Customer customer) { this.customer = customer; } // <2> + + @Action + @ActionLayout(contributed = Contributed.AS_ACTION) + public List<Order> $$(Product p, int quantity) { // <3> + ... + } + public boolean hide$$() { ... } // <4> + public String validate0$$(Product p) { ... } + } +} +---- +<1> Prior to `1.13.2`, had to be prefixed by an "_"; this is no longer required because "$" is also recognized as a way of parsing the class name in order to infer the mixin's name (eg `Customer$placeOrder`). +<2> typically contributed to concrete class +<3> using the "$$" reserved name +<4> supporting methods as usual + + +Moreover, the mixin class can be capitalized if desired. +Thus: + +[source,java] +---- +public class Customer { + + @Mixin + public static class PlaceOrder { // <1> + + private final Customer customer; + public documents(Customer customer) { this.customer = customer; } // <2> + + @Action + @ActionLayout(contributed = Contributed.AS_ACTION) + public List<Order> $$(Product p, int quantity) { // <3> + ... + } + public boolean hide$$() { ... } // <4> + public String validate0$$(Product p) { ... } + } +} +---- + + +In other words, all of the following are allowed: + +* `public static class Documents { ... }` +* `public static class documents { ... }` +* `public static class _Documents { ... }` +* `public static class _documents { ... }` + +The reserved method name "$$" can also be changed using xref:../rgant/rgant.adoc#_rgant_Mixin_method[`@Mixin#method()`] or xref:../rgant/rgant.adoc#_rgant_DomainObject_mixinMethod[`@DomainObject#mixinMethod()`]. + + + + + + + + +== Programmatic usage + +When a domain object is rendered, the framework will automatically instantiate all required mixins and delegate to them +dynamically. If writing integration tests or fixtures, or (sometimes) just regular domain logic, then you may need to +instantiate mixins directly. + +For this you can use the +xref:../rgsvc/rgsvc.adoc#_rgsvc_api_DomainObjectContainer_object-creation-api[`DomainObjectContainer#mixin(...)` +method. For example: + +[source,java] +---- +DocumentHolder_documents mixin = container.mixin(DocumentHolder_documents.class, customer); +---- + +The xref:../ugtst/ugtst.adoc#__ugtst_integ-test-support_bootstrapping_IntegrationTestAbstract[`IntegrationTestAbstract`] and +xref:../rgcms/rgcms.adoc#_rgcms_classes_super_FixtureScript[`FixtureScript`] classes both provide a `mixin(...)` convenience +method. +
http://git-wip-us.apache.org/repos/asf/isis/blob/2f2714cc/adocs/documentation/src/main/asciidoc/guides/ugfun/_ugfun_programming-model_properties-vs-parameters.adoc ---------------------------------------------------------------------- diff --git a/adocs/documentation/src/main/asciidoc/guides/ugfun/_ugfun_programming-model_properties-vs-parameters.adoc b/adocs/documentation/src/main/asciidoc/guides/ugfun/_ugfun_programming-model_properties-vs-parameters.adoc new file mode 100644 index 0000000..e588c44 --- /dev/null +++ b/adocs/documentation/src/main/asciidoc/guides/ugfun/_ugfun_programming-model_properties-vs-parameters.adoc @@ -0,0 +1,38 @@ +[[_ugfun_programming-model_properties-vs-parameters]] += Properties vs Parameters +: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/ + + +In many cases the value types of properties and of action parameters align. +For example, a `Customer` entity might have a `surname` property, and there might also be corresponding `changeSurname`. +Ideally we want the surname property and surname action parameter to use the same value type. + +Since JDO/DataNucleus handles persistence, its annotations are requiredto specify semantics such as optionality or maximum length on properties. +However, they cannot be applied to action parameters. +It is therefore necessary to use Apache Isis' equivalent annotations for action parameters. + +The table below summarises the equivalence of some of the most common cases. + +.Comparing annotations of Properties vs Action Parameters +[cols="2,3,3", options="header"] +|=== +|value type/semantic +|(JDO) property +|action parameter + +|string (length) +|`@javax.jdo.annotations.Column(length=50)` +|`@javax.jdo.annotations.Parameter(maxLength=50)` + +|big decimal (precision) +|`@javax.jdo.annotations.Column(scale=2)` +|`@javax.validation.constraints.Digits(fraction=2)` + +|optionality +|`@Column(allowsNull="true")` +|`@Nullable` or `ParameterLayout(optionality=Optionality.OPTIONAL`) (also `@Optional`, now deprecated) +|=== + + http://git-wip-us.apache.org/repos/asf/isis/blob/2f2714cc/adocs/documentation/src/main/asciidoc/guides/ugfun/_ugfun_programming-model_properties.adoc ---------------------------------------------------------------------- diff --git a/adocs/documentation/src/main/asciidoc/guides/ugfun/_ugfun_programming-model_properties.adoc b/adocs/documentation/src/main/asciidoc/guides/ugfun/_ugfun_programming-model_properties.adoc new file mode 100644 index 0000000..0ab9bad --- /dev/null +++ b/adocs/documentation/src/main/asciidoc/guides/ugfun/_ugfun_programming-model_properties.adoc @@ -0,0 +1,369 @@ +[[_ugfun_programming-model_properties]] += Property +: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/ + + +A property is an instance variable of a domain object, of a scalar type, that holds some state about either a xref:../ugfun/ugfun.adoc#__ugfun_programming-model_class-definition_entities[domain entity] or a xref:../ugfun/ugfun.adoc#__ugfun_programming-model_class-definition_view-models[view model]. + +For example, a ``Customer``'s `firstName` would be a property, as would their `accountCreationDate` that they created their account. +All properties have at least a "getter" method, and most properties have also a "setter" method (meaning that they are mutable). +Properties that do _not_ have a setter method are derived properties, and so are not persisted. + +Formally speaking, a property is simply a regular JavaBean getter, returning a scalar value recognized by the framework. +Most properties (those that are editable/modifiable) will also have a setter and (if persisted) a backing instance field. +And most properties will also have a number of annotations: + +* Apache Isis defines its own set own `@Property` annotation for capturing domain semantics. +It also provides a `@PropertyLayout` for UI hints (though the information in this annotation may instead be provided by a supplementary xref:../ugvw/ugvw.adoc#_ugvw_layout[`.layout.xml`] file + +* the properties of domain entities are often annotated with the JDO/DataNucleus `@javax.jdo.annotations.Column` annotation. +For property references, there may be other annotations to indicate whether the reference is bidirectional. +It's also possible (using annotations) to define a link table to hold foreign key columns. + +* for the properties of view models, then JAXB annotations such as `@javax.xml.bind.annotation.XmlElement` will be present + +Apache Isis recognises some of these annotations for JDO/DataNucleus and JAXB and infers some domain semantics from them (for example, the maximum allowable length of a string property). + +Since writing getter and setter methods adds quite a bit of boilerplate, it's common to use link:https://projectlombok.org/[Project Lombok] to code generate these methods at compile time (using Java's annotation processor) simply by adding the `@lombok.Getter` and `@lombok.Setter` annotations to the field. +The xref:guides/ugfun.adoc#_ugfun_getting-started_simpleapp-archetype[SimpleApp archetype] uses this approach. + + +[[__ugfun_programming-model_properties_value-vs-reference-types]] +== Value vs Reference Types + +Properties can be either a value type (strings, int, date and so on) or be a reference to another object (for example, an `Order` referencing the `Customer` that placed it). + +For example, to map a string value type: + +[source,java] +---- +@lombok.Getter @lombok.Setter // <1> +private String notes; +---- +<1> using link:https://projectlombok.org/[Project Lombok] annotations to reduce boilerplate + +You could also add the `@Property` annotation if you wished: + +[source,java] +---- +@Property +@lombok.Getter @lombok.Setter +private String notes; +---- + +Although in this case it is not required (none of its attributes have been set). + +Or to map a reference type: + +[source,java] +---- +@lombok.Getter @lombok.Setter +private Customer customer; +---- + +It's ok for a xref:../ugfun/ugfun.adoc#__ugfun_programming-model_class-definition_entities[domain entity] to reference another domain entity, and for a xref:../ugfun/ugfun.adoc#__ugfun_programming-model_class-definition_view-models[view model] to reference both view model and domain entities. +However, it isn't valid for a domain entity to hold a persisted reference to view model (DataNucleus will not know how to persist that view model). + +[NOTE] +==== +For further details on mapping associations, see the JDO/DataNucleus documentation for link:http://www.datanucleus.org/products/accessplatform_4_1/jdo/orm/one_to_many.html[one-to-many] associations, link:http://www.datanucleus.org/products/accessplatform_4_1/jdo/orm/many_to_one.html[many-to-one] associations, link:http://www.datanucleus.org/products/accessplatform_4_1/jdo/orm/many_to_many.html[many-to-many] associations, and so on. +==== + +For domain entities, the annotations for mapping value types tend to be different for properties vs action parameters, because JDO annotations are only valid on properties. +The table in the xref:../ugfun/ugfun.adoc#_ugfun_programming-model_properties-vs-parameters[Properties vs Parameters] section provides a handy reference of each. + + +[[__ugfun_programming-model_properties_optional-properties]] +== Optional Properties + +(For domain entities) JDO/DataNucleus' default is that a property is assumed to be mandatory if it is a primitive type (eg `int`, `boolean`), but optional if a reference type (eg `String`, `BigDecimal` etc). +To override optionality in JDO/DataNucleus the `@Column(allowsNull="...")` annotations is used. + +Apache Isis on the other hand assumes that all properties (and action parameters, for that matter) are mandatory, not optional. +These defaults can also be overridden using Apache Isis' own annotations, specifically `@Property(optionality=...)`, or (because it's much less verbose) using `@javax.annotation.Nullable`. + +These different defaults can lead to incompatibilities between the two frameworks. +To counteract that, Apache Isis also recognizes and honours JDO's `@Column(allowsNull=...)`. + +For example, you can write: + +[source,java] +---- +@javax.jdo.annotations.Column(allowsNull="true") +@lombok.Getter @lombok.Setter +private LocalDate date; +---- + +rather than the more verbose: + +[source,java] +---- +@javax.jdo.annotations.Column(allowsNull="true") +@Property(optionality=Optionality.OPTIONAL) +@lombok.Getter @lombok.Setter +private LocalDate date; +---- + +The framework will search for any incompatibilities in optionality (whether specified explicitly or defaulted implicitly) between Isis' defaults and DataNucleus, and refuse to boot if any are found (fail fast). + +[[__ugfun_programming-model_properties_editable-properties]] +== Editable Properties + +Apache Isis provides the capability to allow individual properties to be modified. +This is specified using the `@Property(editing=...)` attribute. + +For example: + +[source,java] +---- +@Property(editing = Editing.ENABLED) +@lombok.Getter @lombok.Setter +private String notes; +---- + +If this is omitted then whether editing is enabled or disabled is defined globally, in the `isis.properties` configuration file; see xref:../rgcfg/rgcfg.adoc#__rgcfg_configuring-core_isis-objects-editing[reference configuration guide] for further details. + + +[[__ugfun_programming-model_properties_ignoring-properties]] +== Ignoring Properties + +By default Apache Isis will automatically render all properties in the xref:../ugvw/ugvw.adoc[UI] or in the xref:../ugvro/ugvro.adoc[REST API]. +To get Apache Isis to ignore a property (exclude it from its metamodel), annotate the getter using `@Programmatic`. + +Similarly, you can tell JDO/DataNucleus to ignore a property using the `@javax.jdo.annotations.NotPersistent` annotation. +This is independent of Apache Isis; in other words that property will still be rendered in the UI (unless also annotated with `@Programmatic`). + +For view models, you can tell JAXB to ignore a property using the `@javax.xml.bind.annotation.XmlTransient` annotation. +Again, this is independent of Apache Isis. + + +[[__ugfun_programming-model_properties_derived-properties]] +== Derived Properties + +Derived properties are those with a getter but no setter. +Provided that the property has not been annotated with `@Programmatic`, these will still be rendered in the UI, but they will be read-only (not editable) and their state will not be persisted. + +Subtly different, it is also possible to have non-persisted but still editable properties. +In this case you will need a getter and a setter, but with the getter annotated using `@NotPersistent`. +The implementation of these getters and setters will most likely persist state using other properties (which might be hidden from view using `@Programmatic`). + +For example: + +[source,java] +---- +@javax.jdo.annotations.NotPersistent +@Property(editing=Editing.ENABLED) +public String getAddress() { return addressService.toAddress( getLatLong() ); } // <1> +public void setAddress(String address) { setLatLong(addressService.toLatLong(address)); } + +@javax.jdo.annotations.Column +private String latLong; +@Programmatic +public String getLatLong() { return latLong; } // <2> +public void setLatLong(String latLong) { this.latLong = latLong; } + +@javax.inject.Inject +AddressService addressService; // <3> +---- +<1> the representation of the address, in human readable form, eg "10 Downing Street, London, UK" +<2> the lat/long representation of the address, eg "51.503363;-0.127625" +<3> an injected service that can convert to/from address and latLong. + + + +[[__ugfun_programming-model_properties_datatypes]] +== Data types + +This section shows specific considerations for various datatypes, in particular how to annotate them for DataNucleus mapping to the persistence object store. + + + +[[__ugfun_programming-model_properties_datatypes_strings]] +=== ``String``s (Length) + +By default JDO/DataNucleus will map string properties to a `VARCHAR(255)`. +To limit the length, use the `@Column(length=...)` annotation. + +For example: + +[source,java] +---- +@javax.jdo.annotations.Column(length=50) +@lombok.Getter @lombok.Setter +private String firstName +---- + +This is a good example of a case where Apache Isis infers domain semantics from the JDO annotation. + + + +[[__ugfun_programming-model_properties_datatypes-joda-dates]] +=== JODA Dates + +Isis' JDO objectstore bundles DataNucleus' http://www.datanucleus.org/documentation/products/plugins.html[built-in support] for Joda `LocalDate` and `LocalDateTime` datatypes, meaning that entity properties of these types will be persisted as appropriate data types in the database tables. + +It is, however, necessary to annotate your properties with `@javax.jdo.annotations.Persistent`, otherwise the data won't actually be persisted. +See the link:http://db.apache.org/jdo/field_types.html[JDO docs] for more details on this. + +Moreover, these datatypes are _not_ in the default fetch group, meaning that JDO/DataNucleus will perform an additional `SELECT` query for each attribute. +To avoid this extra query, the annotation should indicate that the property is in the default fetch group. + +For example, the `ToDoItem` (in the https://github.com/isisaddons/isis-app-todoapp[todoapp example app] (not ASF)) defines the `dueBy` property as follows: + +[source,java] +---- +@javax.jdo.annotations.Persistent(defaultFetchGroup="true") +@javax.jdo.annotations.Column(allowsNull="true") +@Getter @Setter +private LocalDate dueBy; +---- + + +[[__ugfun_programming-model_properties_datatypes_bigdecimals]] +=== ``BigDecimal``s (Precision) + +Working with `java.math.BigDecimal` properties takes a little care due to scale/precision issues. + +For example, suppose we have: + +[source,java] +---- +@lombok.Getter @lombok.Setter +private BigDecimal impact; +---- + +JDO/DataNucleus creates, at least with HSQL, the table with the field type as NUMERIC(19). No decimal digits are admitted. (Further details http://hsqldb.org/doc/2.0/guide/sqlgeneral-chapt.html#sgc_numeric_types[here]). + +What this implies is that, when a record is inserted, a log entry similar to this one appears: + +[source,java] +---- +INSERT INTO ENTITY(..., IMPACT, ....) VALUES (...., 0.5, ....) +---- + +But when that same record is retrieved, the log will show that a value of "0" is returned, instead of 0.5. + +The solution is to explicitly add the scale to the field like this: + +[source,java] +---- +@javax.jdo.annotations.Column(scale=2) +@lombok.Getter @lombok.Setter +private BigDecimal impact; +---- + +In addition, you should also set the scale of the `BigDecimal`, using `setScale(scale, roundingMode)`. + +More information can be found http://www.opentaps.org/docs/index.php/How_to_Use_Java_BigDecimal:_A_Tutorial[here] and http://www.tutorialspoint.com/java/math/bigdecimal_setscale_rm_roundingmode.htm[here]. + + + +[[__ugfun_programming-model_properties_datatypes_blobs]] +=== ``Blob``s + +Apache Isis configures JDO/DataNucleus so that the properties of type `org.apache.isis.applib.value.Blob` and `org.apache.isis.applib.value.Clob` can also be persisted. + +As for xref:../ugfun/ugfun.adoc#__ugfun_programming-model_properties_datatypes_joda-dates[Joda dates], this requires the `@javax.jdo.annotations.Persistent` annotation. +However, whereas for dates one would always expect this value to be retrieved eagerly, for blobs and clobs it is not so clear cut. + +For example, in the `ToDoItem` class (of the https://github.com/isisaddons/isis-app-todoapp/blob/0333852ddd18ad67e3356fccf805aa442246790d/dom/src/main/java/todoapp/dom/todoitem/ToDoItem.java#L442[todoapp example app] (non-ASF) the `attachment` property is as follows: + +[source,java] +---- +@javax.jdo.annotations.Persistent(defaultFetchGroup="false", columns = { + @javax.jdo.annotations.Column(name = "attachment_name"), + @javax.jdo.annotations.Column(name = "attachment_mimetype"), + @javax.jdo.annotations.Column(name = "attachment_bytes", jdbcType="BLOB", sqlType = "LONGVARBINARY") +}) +@Property( + optionality = Optionality.OPTIONAL +) +@lombok.Getter @lombok.Setter +private Blob attachment; +---- + +The three `@javax.jdo.annotations.Column` annotations are required because the mapping classes that Apache Isis provides (https://github.com/apache/isis/blob/isis-1.4.0/component/objectstore/jdo/jdo-datanucleus/src/main/java/org/apache/isis/objectstore/jdo/datanucleus/valuetypes/IsisBlobMapping.java#L59[IsisBlobMapping] and https://github.com/apache/isis/blob/isis-1.4.0/component/objectstore/jdo/jdo-datanucleus/src/main/java/org/apache/isis/objectstore/jdo/datanucleus/valuetypes/IsisClobMapping.java#L59[IsisClobMapping]) map to 3 columns. +(It is not an error to omit these `@Column` annotations, but without them the names of the table columns are simply suffixed `_0`, `_1`, `_2` etc. + +If the `Blob` is mandatory, then use: + +[source,java] +---- +@javax.jdo.annotations.Persistent(defaultFetchGroup="false", columns = { + @javax.jdo.annotations.Column(name = "attachment_name", allowsNull="false"), + @javax.jdo.annotations.Column(name = "attachment_mimetype", allowsNull="false"), + @javax.jdo.annotations.Column(name = "attachment_bytes", + jdbcType="BLOB", sqlType = "LONGVARBINARY", + allowsNull="false") +}) +@Property( + optionality = Optionality.MANDATORY +) +@lombok.Getter @lombok.Setter +private Blob attachment; +---- + +[NOTE] +==== +If specifying a `sqlType` of "LONGVARBINARY" does not work, try instead "BLOB". +There can be differences in behaviour between JDBC drivers. +==== + +[[__ugfun_programming-model_properties_datatypes_clobs]] +=== ``Clob``s + + +Mapping `Clob`s works in a very similar way to xref:../ugfun/ugfun.adoc#__ugfun_programming-model_properties_datatypes_blobs[``Blob``]s, but the `jdbcType` and `sqlType` attributes will, respectively, be `CLOB` and `LONGVARCHAR`: + +[source,java] +---- +@javax.jdo.annotations.Persistent(defaultFetchGroup="false", columns = { + @javax.jdo.annotations.Column(name = "attachment_name"), + @javax.jdo.annotations.Column(name = "attachment_mimetype"), + @javax.jdo.annotations.Column(name = "attachment_chars", + jdbcType="CLOB", sqlType = "LONGVARCHAR") +}) +private Clob doc; +@Property( + optionality = Optionality.OPTIONAL +) +public Clob getDoc() { + return doc; +} +public void setDoc(final Clob doc) { + this.doc = doc; +} +---- + +[NOTE] +==== +If specifying a `sqlType` of "LONGVARCHAR" does not work, try instead "CLOB". There can be differences in behaviour between JDBC drivers. +==== + + +[[__ugfun_programming-model_properties_datatypes_mapping-to-varbinary-or-varchar]] +=== Mapping to VARBINARY or VARCHAR + +Instead of mapping to a sqlType of `LONGVARBINARY` (or perhaps `BLOB`), you might instead decide to map to a `VARBINARY`. +The difference is whether the binary data is held "on-row" or as a pointer "off-row"; with a `VARBINARY` the data is held on-row and so you will need to specify a length. + +For example: + +[source,java] +---- +@javax.jdo.annotations.Column(name = "attachment_bytes", jdbcTypr="BLOB", sqlType = "VARBINARY", length=2048) +---- + +The same argument applies to `LONGVARCHAR` (or `CLOB`); you could instead map to a regular `VARCHAR`: + +[source,java] +---- +@javax.jdo.annotations.Column(name = "attachment_chars", sqlType = "VARCHAR", length=2048) +---- +Support and maximum allowed length will vary by database vendor. + + + + http://git-wip-us.apache.org/repos/asf/isis/blob/2f2714cc/adocs/documentation/src/main/asciidoc/guides/ugfun/_ugfun_programming-model_view-models.adoc ---------------------------------------------------------------------- diff --git a/adocs/documentation/src/main/asciidoc/guides/ugfun/_ugfun_programming-model_view-models.adoc b/adocs/documentation/src/main/asciidoc/guides/ugfun/_ugfun_programming-model_view-models.adoc new file mode 100644 index 0000000..37929da --- /dev/null +++ b/adocs/documentation/src/main/asciidoc/guides/ugfun/_ugfun_programming-model_view-models.adoc @@ -0,0 +1,631 @@ +[[_ugfun_programming-model_view-models]] += View Models + +: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/ + + + + +NOTE: FIXME - move the stuff from ugbtb here + +NOTE: FIXME - deprecate the @ViewModel stuff, emphasise using JAXB only + + + + +[[__ugfun_building-blocks_view-models_typical-implementation]] +== Typical Implementation + +Apache Isis offers several ways to implement view models, but the most flexible/powerful is to annotate the class using JAXB annotations. +For example: + +[source,java] +---- +@XmlRootElement(name = "invoiceRun") // <1> +@XmlType( + propOrder = { // <2> + ... + } +) +public class InvoiceRun { + ... +} +---- +<1> The JAXB `@XmlRootElement` annotation indicates this is a view model to Apache Isis, which then uses JAXB to serialize the state of the view model between interactions +<2> All properties of the view model must be listed using the `XmlType#propOrder` attribute. + +Use JAXB elements such as `@XmlElement` for properties and the combination of `@XmlElementWrapper` and `@XmlElement` for collections. +Properties can be ignored (for serialization) using `@XmlTransient`. + + +'''' +'''' + +[[_ugbtb_view-models_jaxb]] +== JAXB-annotated View Models/DTOs + +As noted in the xref:../ugfun/ugfun.adoc#_ugfun_building-blocks_view-models[introduction], view models can also be defined using JAXB annotations. +The serialized form of these view models is therefore XML, which also enables these view models +to act as DTOs. + +In case it's not obvious, these DTOs are still usable as "regular" view models; they will render in the xref:../ugvw/ugvw.adoc#[Wicket viewer] just like any other. +In fact, these JAXB-annotated view models are in many regards the most powerful of all the various ways of writing view models: + +* their entire state (collections as well as properties) is automatically managed from interaction to interaction. + ++ +In contrast, using xref:../rgant/rgant.adoc#_rgant-ViewModel[`@ViewModel`] (or its xref:../rgant/rgant.adoc#_rgant-DomainObject_nature[`@DomainObject#nature()`] equivalent) will only manage the state of properties, but not collections. +And if using the xref:../rgcms/rgcms.adoc#_rgcms_classes_super_ViewModel[`ViewModel`] interface, then the programmer must write all the state management (lots of boilerplate). + +* JAXB-annotated view models are "in effect" editable. + +The examples in this section uses the DTO for `ToDoItem`, taken from the (non-ASF) http://github.com/isisaddons/isis-app-todoapp[Isis addons' todoapp]. +This DTO is defined as follows: + +[source,java] +---- +package todoapp.app.viewmodels.todoitem.v1; // <1> +@XmlRootElement(name = "toDoItemDto") // <2> +@XmlType( + propOrder = { // <3> + "majorVersion", "minorVersion", + "description", "category", ... + "toDoItem", "similarItems" + } +) +@DomainObjectLayout( + titleUiEvent = TitleUiEvent.Doop.class // <4> +) +public class ToDoItemV1_1 implements Dto { // <5> + @XmlElement(required = true, defaultValue = "1") // <6> + public final String getMajorVersion() { return "1"; } + @XmlElement(required = true, defaultValue = "1") // <7> + public String getMinorVersion() { return "1"; } + + @XmlElement(required = true) // <8> + @Getter @Setter + protected String description; + @XmlElement(required = true) + @Getter @Setter + protected String category; + ... + + @Getter @Setter // <9> + protected ToDoItem toDoItem; + @XmlElementWrapper // <10> + @XmlElement(name = "todoItem") + @Getter @Setter + protected List<ToDoItem> similarItems = Lists.newArrayList(); +} +---- +<1> package name encodes major version; see discussion on xref:../ugbtb/ugbtb.adoc#__ugbtb_view-models_jaxb_versioning[versioning] +<2> identifies this class as a view model and defines the root element for JAXB serialization +<3> all properties in the class must be listed; (they can be ignored using `@XmlTransient`) +<4> demonstrating use of UI events for a subscriber to provide the DTO's title; see xref:../rgant/rgant.adoc#_rgant-DomainObjectLayout_titleUiEvent[`@DomainObjectLayout#titleUiEvent()`]. +<5> class name encodes (major and) minor version; see discussion on xref:../ugbtb/ugbtb.adoc#__ugbtb_view-models_jaxb_versioning[versioning] +<6> again, see discussion on xref:../ugbtb/ugbtb.adoc#__ugbtb_view-models_jaxb_versioning[versioning] +<7> again, see discussion on xref:../ugbtb/ugbtb.adoc#__ugbtb_view-models_jaxb_versioning[versioning] +<8> simple scalar properties +<9> reference to a persistent entity; discussed xref:../ugbtb/ugbtb.adoc#__ugbtb_view-models_jaxb_referencing-domain-entities[below] +<10> reference to a collection of persistent entities; again discussed xref:../ugbtb/ugbtb.adoc#__ugbtb_view-models_jaxb_referencing-domain-entities[below] + + + +[[__ugbtb_view-models_jaxb_referencing-domain-entities]] +=== Referencing Domain Entities + +It's quite common for view models to be "backed by" (be projections of) some underlying domain entity. +The `ToDoItemDto` we've been using as the example in this section is an example: there is an underlying `ToDoItem` entity. + +It wouldn't make sense to serialize out the state of a persistent entity: the point of a DTO is to act as a facade on top of the entity so that the implementation details (of the entity's structure) don't leak out to the consumer. +However, the identity of the underlying entity can be well defined; Apache Isis defines the xref:../rgcms/rgcms.adoc#_rgcms_schema-common[Common schema] which defines the `<oid-dto>` element (and corresponding `OidDto` class): the object's type and its identifier. +This is basically a formal XML equivalent to the `Bookmark` object obtained from the xref:../rgsvc/rgsvc.adoc#_rgsvc_api_BookmarkService[`BookmarkService`]. + +There is only one requirement to make this work: every referenced domain entity must be annotated with xref:../rgant/rgant.adoc#_rgant-XmlJavaTypeAdapter[`@XmlJavaTypeAdapter`], specifying the framework-provided `PersistentEntityAdapter.class`. +This class is similar to the `BookmarkService`: it knows how to create an `OidDto` from an object reference. + +Thus, in our view model we can legitimately write: + +[source,java] +---- +package todoapp.app.viewmodels.todoitem.v1; +... +public class ToDoItemV1_1 implements Dto { + ... + @Getter @Setter + protected ToDoItem toDoItem; +} +---- + +All we need to do is remember to add that `@XmlJavaTypeAdapter` annotation to the referenced entity: + +[source,java] +---- +@XmlJavaTypeAdapter(PersistentEntityAdapter.class) +public class ToDoItem ... { + ... +} +---- + + +It's also possible for a DTO to hold collections of objects. +These can be of any type, either simple properties, or references to other objects. +The only bit of boilerplate that is required is the `@XmlElementWrapper` annotation. +This instructs JAXB to create an XML element (based on the field name) to contain each of the elements. +(If this is omitted then the contents of the collection are at the same level as the properties; almost certainly not what is required). + +For example, the DTO also contains: + +[source,java] +---- +package todoapp.app.viewmodels.todoitem.v1; +... +public class ToDoItemV1_1 implements Dto { + ... + @XmlElementWrapper + @XmlElement(name = "todoItem") + @Getter @Setter + protected List<ToDoItem> similarItems = Lists.newArrayList(); +} +---- + + +There's nothing to prevent a JAXB DTO from containing rich graphs of data, parent containing children containing children. +Be aware though that all of this state will become the DTO's memento, ultimately converted into a URL-safe form, by way of the xref:../rgsvc/rgsvc.adoc#_rgsvc_spi_UrlEncodingService[`UrlEncodingService`]. + +There are limits to the lengths of URLs, however. +Therefore the DTO should not include state that can easily be derived from other information. +If the URL does exceed limits, then provide a custom implementation of xref:../rgsvc/rgsvc.adoc#_rgsvc_spi_UrlEncodingService[`UrlEncodingService`] to handle the memento string in some other fashion (eg substituting it with a GUID, with the memento cached somehow on the server). + + + + + +[[__ugbtb_view-models_jaxb_versioning]] +=== Versioning + +The whole point of using DTOs (in Apache Isis, at least) is to define a formal contact between two inter-operating but independent applications. +Since the only thing we can predicate about the future with any certainty is that it one or both of these applications will change, we should version DTOs from the get-go. +This allows us to make changes going forward without unnecessarily breaking existing consumers of the data. + +[NOTE] +==== +There are several ways that versioning might be accomplished; we base our guidelines on this link:http://www.xfront.com/Versioning.pdf[article] taken from Roger Costello's blog, well worth a read. +==== + +We can distinguish two types of changes: + +* backwardly compatible changes +* breaking changes. + +We can immediately say that the XSD namespace should change only when there is a major/breaking change, if following link:http://semver.org[semantic versioning] that means when we bump the major version number v1, v2, etc. + +XML namespaces correspond (when using JAXB) to Java packages. +We should therefore place our DTOs in a package that contains only the major number; this package will eventually contain a range of DTOs that are intended to be backwardly compatible with one another. +The package should also have a `package-info.java`; it is this that declares the XSD namespace: + +[source,java] +---- +@javax.xml.bind.annotation.XmlSchema( + namespace = "http://viewmodels.app.todoapp/todoitem/v1/Dto.xsd", // <1> + xmlns = { + @javax.xml.bind.annotation.XmlNs( + namespaceURI = "http://isis.apache.org/schema/common", + prefix = "com" + ) + }, + elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED +) +package todoapp.app.viewmodels.todoitem.v1; // <2> +---- +<1> the namespace URI, used by the DTO residing in this package. +<2> the package in which the DTO resides. Note that this contains only the major version. + +Although there is no requirement for the namespace URI to correspond to a physical URL, it should be unique. +This usually means including a company domain name within the string. + +As noted above, this package will contain multiple DTO classes all with the same namespace; these represent a set of minor versions of the DTO, each subsequent one intended to be backwardly compatible with the previous. +Since these DTO classes will all be in the same package (as per the xref:../ugbtb/ugbtb.adoc#__ugbtb_view-models_jaxb_using-packages-to-version[advice above]), the class should therefore include the minor version name: + +[source,java] +---- +package todoapp.app.viewmodels.todoitem.v1; // <1> +... +public class ToDoItemV1_1 implements Dto { // <2> + ... +} +---- +<1> package contains the major version only +<2> DTO class contains the (major and) minor version + + +We also recommend that each DTO instance should also specify the version of the XSD schema that it is logically compatible with. +Probably most consumers will not persist the DTOs; they will be processed and then discarded. +However, it would be wrong to assume that is the case in all cases; some consumers might choose to persist the DTO (eg for replay at some later state). + +Thus: + +[source,java] +---- +public class ToDoItemV1_1 implements Dto { + @XmlElement(required = true, defaultValue = "1") + public final String getMajorVersion() { return "1"; } // <1> + @XmlElement(required = true, defaultValue = "1") + public String getMinorVersion() { return "1"; } // <2> + ... +} +---- +<1> returns the major version (in sync with the package) +<2> returns the minor version (in sync with the class name) + +These methods always return a hard-coded literal. +Any instances serialized from these classes will implicitly "declare" the (major and) minor version of the schema with which they are compatible. +If a consumer has a minimum version that it requires, it can therefore inspect the XML instance itself to determine if it is able to consume said XML. + +If a new (minor) version of a DTO is required, then we recommend copying-and-pasting the previous version, eg: + +[source,java] +---- +public class ToDoItemV1_2 implements Dto { + @XmlElement(required = true, defaultValue = "1") + public final String getMajorVersion() { return "1"; } + @XmlElement(required = true, defaultValue = "2") + public String getMinorVersion() { return "2"; } + ... +} +---- + +Obviously, only changes made must be backward compatible, eg new members must be optional. + +Alternatively, you might also consider simply editing the source file, ie renaming the class and bumping up the value returned by `getMinorVersion()`. + +We also _don't_ recommend using inheritance (ie `ToDoItemV1_2` should not inherit from `ToDoItemV1_1`; this creates unnecessary complexity downstream if generating XSDs and DTOs for the downstream consumer. + + +[[__ugbtb_view-models_jaxb_generating-xsds-and-dtos]] +=== Generating XSDs and DTOs + +In the section xref:../ugbtb/ugbtb.adoc#__ugbtb_view-models_jaxb_referencing-domain-entities[above] it was explained how a view model DTO can transparent reference any "backing" entities; these references are converted to internal object identifiers. + +However, if the consumer of the XML is another Java process (eg running within an Apache Camel route), then you might be tempted/expect to be able to use the same DTO within that Java process. +After a little thought though you'll realize that (duh!) of course you cannot; the consumer runs in a different process space, and will not have references to those containing entities. + +There are therefore two options: + +* either choose not to have the view model DTO reference any persistent entities, and simply limit the DTO to simple scalars. + ++ +Such a DTO will then be usable in both the Apache Isis app (to generate the original XML) and in the consumer. +The xref:../rgsvc/rgsvc.adoc#_rgsvc_api_BookmarkService[`BookmarkService`] can be used to obtain the object identifiers + +* alternatively, generate a different DTO for the consumer from the XSD of the view model DTO. + +The (non-ASF) http://github.com/isisaddons/isis-app-todoapp[Isis addons' todoapp] uses the second approach; generating the XSD and consumer's DTO is mostly just boilerplate `pom.xml` file. +In the todoapp this can be found in the `todoapp-xsd` Maven module, whose `pom.xml` is structured as two profiles: + +[source,xml] +---- +<project ... > + <artifactId>todoapp-xsd</artifactId> + <dependencies> + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>todoapp-app</artifactId> + </dependency> + </dependencies> + <profiles> + <profile> + <id>isis-xsd</id> + <activation> + <property> + <name>!skip.isis-xsd</name> + </property> + </activation> + ... + </profile> + <profile> + <id>xjc</id> + <activation> + <property> + <name>!skip.xjc</name> + </property> + </activation> + ... + </profile> + </profiles> +</project> +---- + +The `isis-xsd` profile generates the XSD using the xref:../rgmvn/rgmvn.adoc#_rgmvn_xsd[`xsd` goal] of Isis' maven plugin: + +[source,xml] +---- +<build> + <plugins> + <plugin> + <groupId>org.apache.isis.tool</groupId> + <artifactId>isis-maven-plugin</artifactId> + <version>${isis.version}</version> + <configuration> + <appManifest>todoapp.dom.ToDoAppDomManifest</appManifest> + <jaxbClasses> + <jaxbClass>todoapp.app.viewmodels.todoitem.v1.ToDoItemV1_1</jaxbClass> + </jaxbClasses> + <separate>false</separate> + <commonSchemas>false</commonSchemas> + </configuration> + <dependencies> + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>todoapp-dom</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>com.google.guava</groupId> + <artifactId>guava</artifactId> + <version>16.0.1</version> + </dependency> + </dependencies> + <executions> + <execution> + <phase>generate-sources</phase> + <goals> + <goal>xsd</goal> + </goals> + </execution> + </executions> + </plugin> + <plugin> + <artifactId>maven-assembly-plugin</artifactId> + <version>2.5.3</version> + <configuration> + <descriptor>src/assembly/dep.xml</descriptor> + </configuration> + <executions> + <execution> + <id>create-archive</id> + <phase>package</phase> + <goals> + <goal>single</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> +</build> +---- + +The `todoapp.dom.ToDoAppDomManifest` is a cut-down version of the app manifest that identifies only the `dom` domain services. + +The `xjc` profile, meanwhile, uses the `maven-jaxb2-plugin` (a wrapper around the `schemagen` JDK tool) to generate a DTO from the XSD generated by the preceding profile: + +[source,xml] +---- +<build> + <plugins> + <plugin> + <groupId>org.jvnet.jaxb2.maven2</groupId> + <artifactId>maven-jaxb2-plugin</artifactId> + <version>0.12.3</version> + <executions> + <execution> + <id>xjc-generate</id> + <phase>generate-sources</phase> + <goals> + <goal>generate</goal> + </goals> + </execution> + </executions> + <configuration> + <removeOldOutput>true</removeOldOutput> + <schemaDirectory> + target/generated-resources/isis-xsd/viewmodels.app.todoapp + </schemaDirectory> + <schemaIncludes> + <schemaInclude>todoitem/v1/Dto.xsd</schemaInclude> + </schemaIncludes> + <bindingDirectory>src/main/resources</bindingDirectory> + <bindingIncludes> + <bindingInclude>binding.xml</bindingInclude> + </bindingIncludes> + <catalog>src/main/resources/catalog.xml</catalog> + </configuration> + </plugin> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>build-helper-maven-plugin</artifactId> + <version>1.9.1</version> + <executions> + <execution> + <id>add-source</id> + <phase>generate-sources</phase> + <goals> + <goal>add-source</goal> + </goals> + <configuration> + <sources> + <source>target/generated-sources/xjc</source> + </sources> + </configuration> + </execution> + </executions> + </plugin> + </plugins> +</build> +---- + + +'''' +'''' + +== (Non-JAXB) View Models + +NOTE: FIXME - consider this as deprecated + +This section describes how to implement view models. + +Fundamentally all view models' state is serialized into +a string memento; this memento is then held by the client (browser) in the form of a URL. As you might imagine, this +URL can become quite long, but Apache Isis offers a mechanism (the xref:../rgsvc/rgsvc.adoc#_rgsvc_spi_UrlEncodingService[`UrlEncodingService`]) if it exceeds the maximum length for a URL +(2083 characters). Also, of course, this string memento must only contain characters that it is valid for use within +a URL. + +While the underlying technique is the same irrespective of use case, the programming model provides various ways of +defining a view model so that the original intent is not lost. They are: + +.View model programming model +[cols="1a,4a,2a", options="header"] +|=== + +| Use case +| Code +| Description + + +| External entity +|[source,java] +---- +@DomainObject(nature=Nature.EXTERNAL_ENTITY) +public class CustomerRecordOnSAP { ... } +---- +|Annotated with xref:../rgant/rgant.adoc#_rgant-DomainObject_nature[`@DomainObject#nature()`] and a nature of `EXTERNAL_ENTITY`, with memento derived automatically from the properties of the domain object. Collections are ignored, as are any properties annotated as xref:../rgant/rgant.adoc#_rgant-Property_notPersisted[not persisted]. + +| In-memory entity +|[source,java] +---- +@DomainObject(nature=Nature.INMEMORY_ENTITY) +public class Log4JAppender { ... } +---- +|As preceding, but using a nature of `INMEMORY_ENTITY`. + +|Application view model +|[source,java] +---- +@DomainObject(nature=Nature.VIEW_MODEL) +public class Dashboard { ... } +---- +|As preceding, but using a nature of `VIEW_MODEL`. + +|Application view model +| +[source,java] +---- +@ViewModel +public class Dashboard { ... } +---- + +|Annotated with xref:../rgant/rgant.adoc#_rgant-ViewModel[`@ViewModel`] annotation (effectively just an alias)' memento is as preceding: from "persisted" properties, collections ignored + +|Application view model +| +[source,java] +---- +public class ExcelUploadManager implements ViewModel { + public String viewModelMemento() { ... } + public void viewModelInit(String memento) { ... } +} +|Implement xref:../rgcms/rgcms.adoc#_rgcms_classes_super_ViewModel[`ViewModel`] interface. The memento is as defined by the +interface's methods: the programmer has full control (but also full responsibility) for the string memento. + +|DTO +| +[source,java] +---- +@XmlRootElement("customer") +public class CustomerDto { ... } +---- +|Annotate using JAXB xref:../rgant/rgant.adoc#_rgant-XmlRootElement[`@XmlRootElement`] annotation. Memento +derived automatically by serializing the XML graph as implied by the JAXB annotations. Note that (unlike `@ViewModel` +et al) this state _can_ include collections. +|=== + +JAXB-annotated DTOs are discussed in more detail immediately xref:rg.adoc#_ugbtb_view-models_jaxb[below]. + + + +'''' +'''' + + + +This section describes how to implement view models. + +Fundamentally all view models' state is serialized into +a string memento; this memento is then held by the client (browser) in the form of a URL. As you might imagine, this +URL can become quite long, but Apache Isis offers a mechanism (the xref:../rgsvc/rgsvc.adoc#_rgsvc_spi_UrlEncodingService[`UrlEncodingService`]) if it exceeds the maximum length for a URL +(2083 characters). Also, of course, this string memento must only contain characters that it is valid for use within +a URL. + +While the underlying technique is the same irrespective of use case, the programming model provides various ways of +defining a view model so that the original intent is not lost. They are: + +.View model programming model +[cols="1a,4a,2a", options="header"] +|=== + +| Use case +| Code +| Description + + +| External entity +|[source,java] +---- +@DomainObject(nature=Nature.EXTERNAL_ENTITY) +public class CustomerRecordOnSAP { ... } +---- +|Annotated with xref:../rgant/rgant.adoc#_rgant-DomainObject_nature[`@DomainObject#nature()`] and a nature of `EXTERNAL_ENTITY`, with memento derived automatically from the properties of the domain object. Collections are ignored, as are any properties annotated as xref:../rgant/rgant.adoc#_rgant-Property_notPersisted[not persisted]. + +| In-memory entity +|[source,java] +---- +@DomainObject(nature=Nature.INMEMORY_ENTITY) +public class Log4JAppender { ... } +---- +|As preceding, but using a nature of `INMEMORY_ENTITY`. + +|Application view model +|[source,java] +---- +@DomainObject(nature=Nature.VIEW_MODEL) +public class Dashboard { ... } +---- +|As preceding, but using a nature of `VIEW_MODEL`. + +|Application view model +| +[source,java] +---- +@ViewModel +public class Dashboard { ... } +---- + +|Annotated with xref:../rgant/rgant.adoc#_rgant-ViewModel[`@ViewModel`] annotation (effectively just an alias)' memento is as preceding: from "persisted" properties, collections ignored + +|Application view model +| +[source,java] +---- +public class ExcelUploadManager implements ViewModel { + public String viewModelMemento() { ... } + public void viewModelInit(String memento) { ... } +} +|Implement xref:../rgcms/rgcms.adoc#_rgcms_classes_super_ViewModel[`ViewModel`] interface. The memento is as defined by the +interface's methods: the programmer has full control (but also full responsibility) for the string memento. + +|DTO +| +[source,java] +---- +@XmlRootElement("customer") +public class CustomerDto { ... } +---- +|Annotate using JAXB xref:../rgant/rgant.adoc#_rgant-XmlRootElement[`@XmlRootElement`] annotation. Memento +derived automatically by serializing the XML graph as implied by the JAXB annotations. Note that (unlike `@ViewModel` +et al) this state _can_ include collections. +|=== + +JAXB-annotated DTOs are discussed in more detail immediately xref:rg.adoc#_ugbtb_view-models_jaxb[below]. + + + http://git-wip-us.apache.org/repos/asf/isis/blob/2f2714cc/adocs/documentation/src/main/asciidoc/guides/ugfun/images/core-concepts/building-blocks/types-of-domain-object.png ---------------------------------------------------------------------- diff --git a/adocs/documentation/src/main/asciidoc/guides/ugfun/images/core-concepts/building-blocks/types-of-domain-object.png b/adocs/documentation/src/main/asciidoc/guides/ugfun/images/core-concepts/building-blocks/types-of-domain-object.png deleted file mode 100644 index 1ec6e18..0000000 Binary files a/adocs/documentation/src/main/asciidoc/guides/ugfun/images/core-concepts/building-blocks/types-of-domain-object.png and /dev/null differ http://git-wip-us.apache.org/repos/asf/isis/blob/2f2714cc/adocs/documentation/src/main/asciidoc/guides/ugfun/images/core-concepts/building-blocks/types-of-domain-object.pptx ---------------------------------------------------------------------- diff --git a/adocs/documentation/src/main/asciidoc/guides/ugfun/images/core-concepts/building-blocks/types-of-domain-object.pptx b/adocs/documentation/src/main/asciidoc/guides/ugfun/images/core-concepts/building-blocks/types-of-domain-object.pptx deleted file mode 100644 index c0be2a5..0000000 Binary files a/adocs/documentation/src/main/asciidoc/guides/ugfun/images/core-concepts/building-blocks/types-of-domain-object.pptx and /dev/null differ http://git-wip-us.apache.org/repos/asf/isis/blob/2f2714cc/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/domain-services/hexagonal-architecture-addons.png ---------------------------------------------------------------------- diff --git a/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/domain-services/hexagonal-architecture-addons.png b/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/domain-services/hexagonal-architecture-addons.png deleted file mode 100644 index af32db1..0000000 Binary files a/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/domain-services/hexagonal-architecture-addons.png and /dev/null differ http://git-wip-us.apache.org/repos/asf/isis/blob/2f2714cc/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/tips-n-tricks/action-semantics-are-you-sure.png ---------------------------------------------------------------------- diff --git a/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/tips-n-tricks/action-semantics-are-you-sure.png b/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/tips-n-tricks/action-semantics-are-you-sure.png deleted file mode 100644 index f0cf269..0000000 Binary files a/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/tips-n-tricks/action-semantics-are-you-sure.png and /dev/null differ http://git-wip-us.apache.org/repos/asf/isis/blob/2f2714cc/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/tips-n-tricks/are-you-sure-happy-case.png ---------------------------------------------------------------------- diff --git a/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/tips-n-tricks/are-you-sure-happy-case.png b/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/tips-n-tricks/are-you-sure-happy-case.png deleted file mode 100644 index 1981c09..0000000 Binary files a/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/tips-n-tricks/are-you-sure-happy-case.png and /dev/null differ http://git-wip-us.apache.org/repos/asf/isis/blob/2f2714cc/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/tips-n-tricks/are-you-sure-sad-case.png ---------------------------------------------------------------------- diff --git a/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/tips-n-tricks/are-you-sure-sad-case.png b/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/tips-n-tricks/are-you-sure-sad-case.png deleted file mode 100644 index 6182447..0000000 Binary files a/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/tips-n-tricks/are-you-sure-sad-case.png and /dev/null differ http://git-wip-us.apache.org/repos/asf/isis/blob/2f2714cc/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/tips-n-tricks/are-you-sure.png ---------------------------------------------------------------------- diff --git a/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/tips-n-tricks/are-you-sure.png b/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/tips-n-tricks/are-you-sure.png deleted file mode 100644 index e1a76fe..0000000 Binary files a/adocs/documentation/src/main/asciidoc/guides/ugfun/images/how-tos/tips-n-tricks/are-you-sure.png and /dev/null differ http://git-wip-us.apache.org/repos/asf/isis/blob/2f2714cc/adocs/documentation/src/main/asciidoc/guides/ugfun/ugfun.adoc ---------------------------------------------------------------------- diff --git a/adocs/documentation/src/main/asciidoc/guides/ugfun/ugfun.adoc b/adocs/documentation/src/main/asciidoc/guides/ugfun/ugfun.adoc index 432c473..b548183 100644 --- a/adocs/documentation/src/main/asciidoc/guides/ugfun/ugfun.adoc +++ b/adocs/documentation/src/main/asciidoc/guides/ugfun/ugfun.adoc @@ -47,11 +47,12 @@ The remaining guides are: include::_ugfun_core-concepts.adoc[leveloffset=+1] -include::_ugfun_getting-started.adoc[leveloffset=+1] -include::_ugfun_domain-class-ontology.adoc[leveloffset=+1] +include::_ugfun_building-blocks.adoc[leveloffset=+1] + +include::_ugfun_getting-started.adoc[leveloffset=+1] -include::_ugfun_class-structure.adoc[leveloffset=+1] +include::_ugfun_programming-model.adoc[leveloffset=+1] include::_ugfun_ui-hints.adoc[leveloffset=+1] include::_ugfun_crud.adoc[leveloffset=+1] @@ -60,3 +61,5 @@ include::_ugfun_business-rules.adoc[leveloffset=+1] include::_ugfun_drop-downs-and-defaults.adoc[leveloffset=+1] +include::_ugfun_available-domain-services.adoc[leveloffset=+1] + http://git-wip-us.apache.org/repos/asf/isis/blob/2f2714cc/adocs/documentation/src/main/asciidoc/guides/ugodn/_ugodn_hints-and-tips.adoc ---------------------------------------------------------------------- diff --git a/adocs/documentation/src/main/asciidoc/guides/ugodn/_ugodn_hints-and-tips.adoc b/adocs/documentation/src/main/asciidoc/guides/ugodn/_ugodn_hints-and-tips.adoc index de70245..1efd665 100644 --- a/adocs/documentation/src/main/asciidoc/guides/ugodn/_ugodn_hints-and-tips.adoc +++ b/adocs/documentation/src/main/asciidoc/guides/ugodn/_ugodn_hints-and-tips.adoc @@ -24,6 +24,7 @@ See also hints-n-tips chapters in the: include::_ugodn_hints-and-tips_overriding-jdo-annotations.adoc[leveloffset=+1] include::_ugodn_hints-and-tips_handling-mandatory-properties-in-subtypes.adoc[leveloffset=+1] +include::_ugodn_hints-and-tips_mapping-to-a-view.adoc[leveloffset=+1] include::_ugodn_hints-and-tips_subtype-entity-not-fully-populated.adoc[leveloffset=+1] include::_ugodn_hints-and-tips_java8.adoc[leveloffset=+1] http://git-wip-us.apache.org/repos/asf/isis/blob/2f2714cc/adocs/documentation/src/main/asciidoc/guides/ugodn/_ugodn_hints-and-tips_mapping-to-a-view.adoc ---------------------------------------------------------------------- diff --git a/adocs/documentation/src/main/asciidoc/guides/ugodn/_ugodn_hints-and-tips_mapping-to-a-view.adoc b/adocs/documentation/src/main/asciidoc/guides/ugodn/_ugodn_hints-and-tips_mapping-to-a-view.adoc new file mode 100644 index 0000000..a50c2a0 --- /dev/null +++ b/adocs/documentation/src/main/asciidoc/guides/ugodn/_ugodn_hints-and-tips_mapping-to-a-view.adoc @@ -0,0 +1,9 @@ +[[_ugodn_hints-and-tips_mapping-to-a-view]] += Mapping to a View +: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/ + + +NOTE: FIXME - as per Estatio's Invoice stuff + http://git-wip-us.apache.org/repos/asf/isis/blob/2f2714cc/adocs/documentation/src/main/asciidoc/guides/ugvro/_ugvro_simplified-representations.adoc ---------------------------------------------------------------------- diff --git a/adocs/documentation/src/main/asciidoc/guides/ugvro/_ugvro_simplified-representations.adoc b/adocs/documentation/src/main/asciidoc/guides/ugvro/_ugvro_simplified-representations.adoc index 3a61eb3..ef4e697 100644 --- a/adocs/documentation/src/main/asciidoc/guides/ugvro/_ugvro_simplified-representations.adoc +++ b/adocs/documentation/src/main/asciidoc/guides/ugvro/_ugvro_simplified-representations.adoc @@ -7,370 +7,24 @@ The representations defined by the RO spec are very rich and enable complex client-side applications to be built. -However, their sophistication can be an impediment to their use if one wishes to write a simple app using third-party -components that expect to consume much simpler representations. Examples of such tools are +However, their sophistication can be an impediment to their use if one wishes to write a simple app using third-party components that expect to consume much simpler representations. +Examples of such tools are link:http://angular-ui.github.io/bootstrap/[Angular Bootstrap], link:http://vitalets.github.io/angular-xeditable/[Angular XEditable], link:https://github.com/mgcrea/angular-strap[Angular Strap]. -As of `1.11.0`, Apache Isis provides support for its own simplified representation for the most commonly-used -representations. This is implemented using the `ContentNegotiationService` described in the +As of `1.11.0`, Apache Isis provides support for its own simplified representation for the most commonly-used representations. +This is implemented using the `ContentNegotiationService` described in the xref:../ugvro/ugvro.adoc#_ugvro_architecture[architecture] chapter. -[[__ugvro_simplified-representations_apache-isis-profile]] -== The Apache Isis "Profile" - -The RO spec uses the standard `Accept` header for content negotiation, and defines its own "profile" for the standard -representations; these take the form: - -[source] ----- -Accept: application/json;profile="urn:org.restfulobjects:repr-types/xxx" ----- - -where "xxx" varies by resource. The detail can be found in section 2.4.1 of the RO spec. - -The Apache Isis viewer also defines its own "Isis" profile which enables the client to request simplified -representations for the most frequently accessed resources. This is done by specifying an `Accept` header of: - -[source] ----- -Accept: application/json;profile="urn:org.apache.isis/v1" ----- - -Not every resource supports this header, but the most commonly accessed ones do. In each case the server will set the -`Content-Type` header so that the client knows how to process the representation. - -The link:https://www.youtube.com/watch?v=HMSqapQDY_4[screencast] demonstrates the feature. - - - -The sections below explain in a little more detail what is returned when this profile is activated. - - -[[__ugvro_simplified-representations_domain-object]] -== Domain Object - -If a domain object resource (section 14) is accessed with the Apache Isis profile, the resultant representation is a -JSON object with simple key/value pairs for each property. - -The contents of any collections are also eagerly returned, consisting of an array of elements of each referenced -object. Each such element contains key/value pairs of each property (in other words, a grid of data is returned). -Each element also has a special `$$href` property (so that the client can easily navigate to a resource for that -object) and a `$$title` property (to use as a label, eg the hyperlink text). - -In addition, the representation defined by the RO spec is also included, under a special `$$ro` property. - -For example, using the (non-ASF) http://github.com/isisaddons/isis-app-todoapp[Isis addons' todoapp], accessing -this resource: - -[source] ----- -http://localhost:8080/restful/objects/TODO/45 ----- - -with an `Accept` request header of: - -[source] ----- -Accept: application/json;profile="urn:org.apache.isis/v1" ----- - -returns the following representation: - -[source] ----- -{ - "$$href" : "http://localhost:8080/restful/objects/TODO/45", // <1> - "$$instanceId" : "45", // <2> - "$$title" : "Buy bread due by 2015-12-04", // <3> - "description" : "Buy bread", // <4> - "category" : "Domestic", - "subcategory" : "Shopping", - "complete" : false, - "atPath" : "/users/sven", - ... - "similarTo" : [ { // <5> - "$$href" : "http://localhost:8080/restful/objects/TODO/46", - "$$instanceId" : "46", - "$$title" : "Buy milk due by 2015-12-04", - "description" : "Buy milk", - "category" : "Domestic", - ... - }, { - "$$href" : "http://localhost:8080/restful/objects/TODO/47", - "$$instanceId" : "47", - "$$title" : "Buy stamps due by 2015-12-04", - "description" : "Buy stamps", - "category" : "Domestic", - ... - }, - ... - } ], - "dependencies" : [ ], - "$$ro" : { // <6> - "links" : [ ... ], - "extensions" : { ... }, - "title" : "Buy bread due by 2015-12-04", - "domainType" : "TODO", - "instanceId" : "45", - "members" : { ... } - } -} ----- -<1> hyperlink to the representation -<2> instance id of the domain object (unique within its type) -<3> title of the domain object -<4> all the properties of the domain object (to which the caller has access), as key/value pairs -<5> contents of each collection -<6> special `$$ro` json-prop, being the normal RO Spec representation for this object - -with a `Content-Type` header: - -[source] ----- -Content-Type: application/json; - profile="urn:org.apache.isis/v1";repr-type="object" ----- - - -[[__ugvro_simplified-representations_object-collection]] -== Domain Object Collection - -If a domain object collection (section 17) is accessed with this profile, then the resultant representation is as -an array of elements of key/value for each referenced object, and again each element the containing the key/value -pairs of the properties of that object (a grid, again). + - -In addition, the representation defined by the RO spec is also included, as a special object with a single `$$ro` -property. - -For example, using the (non-ASF) http://github.com/isisaddons/isis-app-todoapp[Isis addons' todoapp], accessing -this resource: - -[source] ----- -http://localhost:8080/restful/objects/TODO/45/collections/similarTo ----- - -with an `Accept` request header of: - -[source] ----- -Accept: application/json;profile="urn:org.apache.isis/v1" ----- - -returns the following representation: - -[source] ----- -[ // <1> -{ - "$$href" : "http://localhost:8080/restful/objects/TODO/46", // <2> - "$$instanceId" : "46", // <3> - "$$title" : "Buy milk due by 2015-12-04", // <4> - "description" : "Buy milk", // <5> - "category" : "Domestic", - ... -}, { - "$$href" : "http://localhost:8080/restful/objects/TODO/47", - "$$title" : "Buy stamps due by 2015-12-04", - "description" : "Buy stamps", - "category" : "Domestic", - ... -}, { - "$$href" : "http://localhost:8080/restful/objects/TODO/48", - "$$title" : "Mow lawn due by 2015-12-10", - "description" : "Mow lawn", - "category" : "Domestic", - ... -}, -... -, { - "$$ro" : { // <6> - "id" : "similarTo", - "memberType" : "collection", - "links" : [ ... ], - "extensions" : { ... }, - "value" : [ ... ] - } -} -] ----- -<1> returns a JSON array, not a JSON object -<2> hyperlink to the representation -<3> instance id of the domain object (unique within its type) -<4> title of the domain object -<5> all the properties of the domain object (to which the caller has access), as key/value pairs -<6> last element is a special object with a single `$$ro` json-prop, being the normal RO Spec representation for this object - -with a `Content-Type` header: - -[source] ----- -Content-Type: application/json;profile="urn:org.apache.isis/v1";repr-type="object-collection" ----- - - -[[__ugvro_simplified-representations_action-invocation]] -== Action Invocation - -When an action is invoked, it can return a domain object, a list, a scalar, or return nothing. - -=== Returning an Object - -If the action returned an object, then the domain object representation described -xref:../ugvro/ugvro.adoc#__ugvro_simplified-representations_domain-object[above] is returned. - -For example, using the (non-ASF) http://github.com/isisaddons/isis-app-todoapp[Isis addons' todoapp], accessing -this resource: - -[source] ----- -http://localhost:8080/restful/objects/TODO/45/actions/updateCost/invoke ----- - -with an `Accept` request header of: - -[source] ----- -Accept: application/json;profile="urn:org.apache.isis/v1" ----- - -returns the following representation: - -[source] ----- - -{ - "$$href" : "http://localhost:8080/restful/objects/TODO/45", - "$$instanceId" : "45", - "$$title" : "Buy bread due by 2015-12-04", - "description" : "Buy bread", - "category" : "Domestic", - "subcategory" : "Shopping", - "complete" : false, - ... - "similarTo" : [ ... ] - ... - "$$ro" : { ... } -} ----- - -with a `Content-Type` of: - -[source] ----- -Content-Type: application/json;profile="urn:org.apache.isis/v1";repr-type="object" ----- - -\... in other words no different to a representation obtained of the returned domain object directly. - - -=== Returning a List - -On the other hand if the action returned a list (a "standalone" collection, then an array representation is returned. -This is very similar to that returned by a -xref:../ugvro/ugvro.adoc#__ugvro_simplified-representations_object-collection[(parented) object collection], though with a -slightly different `Content-Type` to distinguish. - -For example, using the (non-ASF) http://github.com/isisaddons/isis-app-todoapp[Isis addons' todoapp], accessing -this resource: - -[source] ----- -http://localhost:8080/restful/services/ToDoItems/actions/notYetComplete/invoke ----- - -with an `Accept` request header of: - -[source] ----- -Accept: application/json;profile="urn:org.apache.isis/v1" ----- - -returns the following representation: - -[source] ----- -[ { - "$$href" : "http://localhost:8080/restful/objects/TODO/45", - "$$instanceId" : "45", - "$$title" : "Buy bread due by 2015-12-04", - "description" : "Buy bread", - "category" : "Domestic", - ... -}, { - "$$href" : "http://localhost:8080/restful/objects/TODO/46", - "$$instanceId" : "46", - "$$title" : "Buy milk due by 2015-12-04", - "description" : "Buy milk", - "category" : "Domestic", - ... -}, -... -, { - "$$ro" : { - "links" : [ ... ] - "resulttype" : "list", - "result" : { ... } - "value" : [ ... ], - "links" : [ ... ], - "extensions" : { } - } - } -} ] ----- - -with a `Content-Type` header: - -[source] ----- -Content-Type: application/json;profile="urn:org.apache.isis/v1";repr-type="list" ----- - -=== Returning Scalar/Nothing - -Note that actions returning scalar values or nothing (which includes `void` actions) are not supported; for these the -regular RO spec representation will be returned. - - -[[__ugvro_simplified-representations_other-representations]] -== Supporting other Representations - -Sometimes though you may want to extend or change the representations generated. This might be because you want to -write a RESTful client that uses a particular library (say a Javascript library or web components) that can only handle representations in a certain form. - -Or, you might want to have Apache Isis generate representations according to some other "standard", of which there are -many: - -* Mike Kelly's http://stateless.co/hal_specification.html[HAL] specification -* Mike Amundsen's http://amundsen.com/media-types/collection/[Collection+JSON] specification -* Kevin Swiber's https://github.com/kevinswiber/siren[Siren] specification -* Steve Klabnik's http://jsonapi.org/[JSON API] specification -* Gregg Cainus' https://github.com/cainus/hyper-json-spec[Hyper+JSON] specification -* the W3C's https://www.w3.org/TR/json-ld/[JSON-LD] specification -* Markus Lanthaler's http://www.markus-lanthaler.com/hydra/[Hydra] specification. - -A good discussion about the relative merits of several of these different hypermedia formats can be found https://groups.google.com/forum/#!msg/api-craft/NgjzQYVOE4s/EAB2jxtU_TMJ[here]. - -Or, of course, you may have your own internal specification that you wish to use. - -Supporting any of these alternative representations can be achieved by providing a suitable implementation of -`ContentNegotiationService`. The existing implementations (eg `ContentNegotiationServiceSimplified`) can be used as a -starting point. - -[NOTE] -==== -These will, admittedly, need to access the internal APIs for the Apache Isis metamodel, and you should be aware that -these are not formal API; they may change over time. That said, they are very stable and have not changed -significantly over the last few years. -==== - - - -include::__ugvro_simplified-representations_configuration-properties.adoc[leveloffset=+1] +include::_ugvro_simplified-representations_apache-isis-profile.adoc[leveloffset=+1] +include::_ugvro_simplified-representations_domain-object.adoc[leveloffset=+1] +include::_ugvro_simplified-representations_object-collection.adoc[leveloffset=+1] +include::_ugvro_simplified-representations_action-invocation.adoc[leveloffset=+1] +include::_ugvro_simplified-representations_other-representations.adoc[leveloffset=+1] +include::_ugvro_simplified-representations_configuration-properties.adoc[leveloffset=+1] http://git-wip-us.apache.org/repos/asf/isis/blob/2f2714cc/adocs/documentation/src/main/asciidoc/guides/ugvro/_ugvro_simplified-representations_action-invocation.adoc ---------------------------------------------------------------------- diff --git a/adocs/documentation/src/main/asciidoc/guides/ugvro/_ugvro_simplified-representations_action-invocation.adoc b/adocs/documentation/src/main/asciidoc/guides/ugvro/_ugvro_simplified-representations_action-invocation.adoc new file mode 100644 index 0000000..d1ac550 --- /dev/null +++ b/adocs/documentation/src/main/asciidoc/guides/ugvro/_ugvro_simplified-representations_action-invocation.adoc @@ -0,0 +1,128 @@ +[[_ugvro_simplified-representations_action-invocation]] += Action Invocation +: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/ + + + +When an action is invoked, it can return a domain object, a list, a scalar, or return nothing. + +== Returning an Object + +If the action returned an object, then the domain object representation described +xref:../ugvro/ugvro.adoc#__ugvro_simplified-representations_domain-object[above] is returned. + +For example, using the (non-ASF) http://github.com/isisaddons/isis-app-todoapp[Isis addons' todoapp], accessing +this resource: + +[source] +---- +http://localhost:8080/restful/objects/TODO/45/actions/updateCost/invoke +---- + +with an `Accept` request header of: + +[source] +---- +Accept: application/json;profile="urn:org.apache.isis/v1" +---- + +returns the following representation: + +[source] +---- + +{ + "$$href" : "http://localhost:8080/restful/objects/TODO/45", + "$$instanceId" : "45", + "$$title" : "Buy bread due by 2015-12-04", + "description" : "Buy bread", + "category" : "Domestic", + "subcategory" : "Shopping", + "complete" : false, + ... + "similarTo" : [ ... ] + ... + "$$ro" : { ... } +} +---- + +with a `Content-Type` of: + +[source] +---- +Content-Type: application/json;profile="urn:org.apache.isis/v1";repr-type="object" +---- + +\... in other words no different to a representation obtained of the returned domain object directly. + + +== Returning a List + +On the other hand if the action returned a list (a "standalone" collection, then an array representation is returned. +This is very similar to that returned by a +xref:../ugvro/ugvro.adoc#__ugvro_simplified-representations_object-collection[(parented) object collection], though with a +slightly different `Content-Type` to distinguish. + +For example, using the (non-ASF) http://github.com/isisaddons/isis-app-todoapp[Isis addons' todoapp], accessing +this resource: + +[source] +---- +http://localhost:8080/restful/services/ToDoItems/actions/notYetComplete/invoke +---- + +with an `Accept` request header of: + +[source] +---- +Accept: application/json;profile="urn:org.apache.isis/v1" +---- + +returns the following representation: + +[source] +---- +[ { + "$$href" : "http://localhost:8080/restful/objects/TODO/45", + "$$instanceId" : "45", + "$$title" : "Buy bread due by 2015-12-04", + "description" : "Buy bread", + "category" : "Domestic", + ... +}, { + "$$href" : "http://localhost:8080/restful/objects/TODO/46", + "$$instanceId" : "46", + "$$title" : "Buy milk due by 2015-12-04", + "description" : "Buy milk", + "category" : "Domestic", + ... +}, +... +, { + "$$ro" : { + "links" : [ ... ] + "resulttype" : "list", + "result" : { ... } + "value" : [ ... ], + "links" : [ ... ], + "extensions" : { } + } + } +} ] +---- + +with a `Content-Type` header: + +[source] +---- +Content-Type: application/json;profile="urn:org.apache.isis/v1";repr-type="list" +---- + +== Returning Scalar/Nothing + +Note that actions returning scalar values or nothing (which includes `void` actions) are not supported; for these the +regular RO spec representation will be returned. + +