<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mikaël Geljić on Medium]]></title>
        <description><![CDATA[Stories by Mikaël Geljić on Medium]]></description>
        <link>https://medium.com/@mkgl?source=rss-899ed73c4627------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fyM7WkAq2HQof7YmCKLqFw.jpeg</url>
            <title>Stories by Mikaël Geljić on Medium</title>
            <link>https://medium.com/@mkgl?source=rss-899ed73c4627------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 02:12:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mkgl/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Bring your own API with Magnolia REST 2.1]]></title>
            <link>https://medium.com/@mkgl/bring-your-own-api-with-magnolia-rest-2-1-539c3eb3d430?source=rss-899ed73c4627------2</link>
            <guid isPermaLink="false">https://medium.com/p/539c3eb3d430</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[magnolia]]></category>
            <category><![CDATA[jax-rs]]></category>
            <category><![CDATA[rest]]></category>
            <dc:creator><![CDATA[Mikaël Geljić]]></dc:creator>
            <pubDate>Fri, 22 Feb 2019 09:30:12 GMT</pubDate>
            <atom:updated>2019-02-22T09:30:12.555Z</atom:updated>
            <content:encoded><![CDATA[<p>Last year, <strong>Magnolia REST modules went 2.1</strong>; and it’s been quite a harvesting release, enough for me to take a look back.</p><p>Building upon the <a href="https://documentation.magnolia-cms.com/display/DOCS/Delivery+endpoint+API+v2">Content Delivery API</a> introduced in 2.0 in fall 2017, 2.1 brings <strong>dynamic paths</strong> for endpoints (aka backbone for delivery endpoints in separate files/modules), <strong>content localization</strong>, <strong>asset references</strong>, as well as <strong>reference links</strong>. For an overview of these features, <a href="https://documentation.magnolia-cms.com/display/DOCS56/Release+notes+for+Magnolia+CORE+5.6.5">release notes &amp; highlights</a> will happily guide you through. In this post, we’re taking a look under the hood, then hop on a basic example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JdkKMb1rolUOkMEJdTr6AA.jpeg" /><figcaption>under the bike at Belgo brewery, Saigon</figcaption></figure><h4>Standard Node serialization (goodbye Jackson)</h4><p>REST 2.0 introduced the short-format JSON serialization of JCR nodes. How was that done?</p><p>It could have been as simple as deriving a hypotheticalSimpleRepositoryNode pojo and letting Jackson do the object mapping. Instead of doing that, we rethought the JSON serialization for JCR items altogether, relying more extensively on standard, enterprise Java APIs. As of Magnolia 5.6, we were roughly on a Java EE 7 baseline. Therefore we had JAX-RS 2.0, and most of all JSON-P 1.0, the <a href="https://javaee.github.io/jsonp/">JSON Processing API</a> (JSR 374).</p><p>For the writing process, JSON-P has two APIs to choose from: an Object Model API — for constructing and manipulating in-memory object trees — and a Streaming API for writing JSON to a stream on the fly. We chose the latter, which pairs very well with JCR’s NodeIterators — both for traversing child-nodes and for digesting results of JCR queries. Sample usage for the JCR API is illustrated below.</p><pre>JsonGenerator json = Json.<strong>createGenerator</strong>(out);<br>json.<strong>writeStartObject</strong>();<br>json.<strong>write</strong>(<strong>&quot;</strong><a href="http://twitter.com/id"><strong>@id</strong></a><strong>&quot;</strong>, <strong>node.getIdentifier()</strong>);</pre><pre>PropertyIterator properties = node.getProperties();<br>while (properties.hasNext()) {<br>    Property property = properties.nextProperty();<br>    json.<strong>write</strong>(property.getName(), property.getString());<strong><br></strong>}<br>...<br>json.<strong>writeEnd</strong>();</pre><p>We built this into JAX-RS MessageBodyWriters for both Node and NodeIterator, producing objects and arrays, respectively.</p><p>Should anything go awry, we also provide an ExceptionMapper&lt;RepositoryException&gt;, assigning reasonable HTTP status codes to common JCR exception types.</p><p><strong>This makes it dead-simple to write custom JCR endpoints</strong>. Since MessageBodyWriters are standard Provider classes, all one has to do is to return a JCR Node (or NodeIterator); let Magnolia write it, and handle exceptions for you.</p><pre>@GET<br>@Path(&quot;/monsters&quot;)<br>@Produces(<em>APPLICATION_JSON</em>)<br>public <strong>NodeIterator</strong> getContacts() throws RepositoryException {<br>    Session session = ctxProvider.get().getJCRSession(&quot;contacts&quot;);<br><br>    Query query = QueryBuilder.<em>inWorkspace</em>(session.getWorkspace())<br>            .nodeTypes(List.<em>of</em>(&quot;mgnl:contact&quot;))<br>            .conditions(Map.<em>of</em>(<br>                    &quot;organizationName&quot;, List.<em>of</em>(&quot;Monsters Inc.&quot;)))<br>            .build();<br><br>    QueryResult result = <strong>query.execute</strong>();<br>    return result.<strong>getNodes</strong>();<br>}</pre><p>But there’s more: since version 2.1, we also provide a similar writer for Assets, from the Magnolia DAM API; these may be external media assets as much as JCR assets.</p><p>Historically, Magnolia has always been highly flexible for registering servlets into the filter chain; this has been extensively used — if not abused to fulfill RESTful tasks. Now I hope I’m making it clear there’s a better way to do that. 😊</p><p>Check out <a href="https://gist.github.com/mkgl/ba8c6e9789b5c4f102930684c0dda810">the Gist</a> over at GitHub ❤️; in the next post I’ll shed some light on dynamic paths for endpoints.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=539c3eb3d430" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Validating Multi-value fields in Magnolia]]></title>
            <link>https://medium.com/@mkgl/validating-multi-value-fields-in-magnolia-c9638e270428?source=rss-899ed73c4627------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9638e270428</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[magnolia]]></category>
            <category><![CDATA[vaadin]]></category>
            <category><![CDATA[validation]]></category>
            <dc:creator><![CDATA[Mikaël Geljić]]></dc:creator>
            <pubDate>Mon, 08 Oct 2018 16:21:14 GMT</pubDate>
            <atom:updated>2018-10-08T16:21:14.757Z</atom:updated>
            <content:encoded><![CDATA[<p>Custom field validation is a recurring topic when developing Magnolia projects and <a href="https://documentation.magnolia-cms.com/display/DOCS/My+first+content+app">content apps</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*t5JEhC-l8eKxu9qeFEJjkg.png" /></figure><blockquote>DISCLAIMER: As of Magnolia 5.7, <a href="https://documentation.magnolia-cms.com/display/DOCS/Field+definition">Admincentral forms</a> are still based on the Vaadin 7 data API, which is deprecated since Vaadin 8.</blockquote><p>As it turns out, they require a significant amount of boilerplate code and configuration; let’s summarize first what you need here:</p><ul><li>A Vaadin <a href="https://vaadin.com/docs/v7/framework/components/components-fields.html#components.fields.validation">Validator</a> (either <a href="https://vaadin.com/docs/v7/framework/components/components-fields.html#components.fields.validation.builtin">stock</a> or <a href="https://vaadin.com/docs/v7/framework/components/components-fields.html#components.fields.validation.custom">custom</a>)</li><li>A Magnolia <a href="https://documentation.magnolia-cms.com/display/DOCS/Field+validators">FieldValidatorDefinition</a></li><li>A Magnolia FieldValidatorFactory</li><li>The Magnolia <a href="https://documentation.magnolia-cms.com/display/DOCS/Field+definition">FieldDefinition</a> that glues it together</li></ul><p>And to make it even less obvious, you don’t get to configure these quite like for fields (despite having an analog 3-tier component pattern); in fact, there is no registry for validators.</p><p>Fortunately, it still proves to be reasonably easy. 🙂</p><h4>Validating the amount of ingredients</h4><p>For the purpose of this post, I decided to show a somewhat <em>real</em> scenario: validating the number of entries within a multi-value field. This is something we get asked *a lot* at Magnolia.</p><p>Let’s start with the Vaadin Validator. As the amount of entries is a plain number, and since Vaadin has an IntegerRangeValidator out-of-the-box, this should do the trick, right?. But wait, Magnolia’s MultiField is not typed to take integer values as input; its value type is a PropertysetItem — essentially a plain HashMap of Vaadin Properties. So let’s create our own Validator class, and delegate to an inner IntegerRangeValidator.</p><pre>class EntryCountValidator extends AbstractValidator&lt;Item&gt; {<br>    private final IntegerRangeValidator delegate;<br> <br>    public EntryCountValidator(String errorMessage, Integer minValue, Integer maxValue) {<br>        super(errorMessage);<br>        <strong>delegate = new IntegerRangeValidator(errorMessage, minValue, maxValue);<br>    </strong>}<br> <br>    @Override<br>    public void validate(Object value) throws InvalidValueException {<br>        // isValidType ensures that value can safely be cast to TYPE<br>        if (!isValidType(value)) {<br>            throw new InvalidValueException(getErrorMessage());<br>        }<br>        Item item = (Item) value;<br>        <strong>delegate.validate(item.getItemPropertyIds().size());<br>    </strong>}<br>}</pre><p>So far so good. Next, in order to configure it, we need a definition for it. To keep it concise/self-contained, I use the definition as an “outer wrapper”, so that its class name remains somewhat canonical for the YAML config; then the Vaadin Validator impl becomes a private nested class, because well, it shall only be instantiated by the FieldValidatorFactory.</p><p>Same story for the factory, I implemented it as a private nested class; and spared the configuration by overriding/hard-coding the definition’s factoryClass to it. Class names are a bit prolix, shall we say.</p><pre>private static class EntryCountValidatorFactory extends AbstractFieldValidatorFactory&lt;EntryCountValidatorDefinition&gt; implements FieldValidatorFactory {<br> <br>    @Inject<br>    public EntryCountValidatorFactory(EntryCountValidatorDefinition definition) {<br>        super(definition);<br>    }<br> <br>    @Override<br>    public Validator createValidator() {<br>        return new EntryCountValidator(getI18nErrorMessage(), definition.getMinValue(), definition.getMaxValue());<br>    }<br>}</pre><p>That’s pretty it for a starter, really. Here’s what you can do next:</p><ul><li>Add configuration as needed to your ValidatorDefinition (and pass it on to your validator)</li><li>Add i18n translations for the validation messages</li></ul><p>See <a href="https://gist.github.com/mkgl/9b9acdc1070705aacb3a8411e22bd9dd">the complete Gist</a> over at GitHub ❤️.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9638e270428" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>