<?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 Giuseppe Baglio on Medium]]></title>
        <description><![CDATA[Stories by Giuseppe Baglio on Medium]]></description>
        <link>https://medium.com/@giuseppebaglio?source=rss-7f5958c1a602------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ERyIPUhTWH_kp0A4ziIU2w.png</url>
            <title>Stories by Giuseppe Baglio on Medium</title>
            <link>https://medium.com/@giuseppebaglio?source=rss-7f5958c1a602------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 03:40:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@giuseppebaglio/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[How Adobe’s Content AI Solves Enterprise Search’s Problem]]></title>
            <link>https://medium.com/@giuseppebaglio/how-adobes-content-ai-solves-enterprise-search-s-problem-5aca4d751725?source=rss-7f5958c1a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aca4d751725</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[content-strategy]]></category>
            <category><![CDATA[enterprise-software]]></category>
            <category><![CDATA[adobe]]></category>
            <category><![CDATA[semantic-search]]></category>
            <dc:creator><![CDATA[Giuseppe Baglio]]></dc:creator>
            <pubDate>Wed, 22 Oct 2025 14:40:01 GMT</pubDate>
            <atom:updated>2025-10-22T14:51:20.848Z</atom:updated>
            <content:encoded><![CDATA[<h4>Beyond keyword matching with semantic intelligence</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2dR24rAXJCe4FVBfElrufw.jpeg" /></figure><p>The adaptTo() conference delivers technical insights for the AEM community each year. The challenge? Weeks of content require weeks to digest.</p><p>One presentation caught my curiosity: <a href="https://www.youtube.com/watch?v=8i_-ruidNZg&amp;t=309s">“Bringing intelligence on content in AEM with Content AI”</a> by <a href="https://in.linkedin.com/in/nitin-gupta0906">Nitin Gupta</a> and <a href="https://ch.linkedin.com/in/fabriziofortino?trk=people-guest_people_search-card">Fabrizio Fortino</a> from Adobe. Not flashy demos or buzzwords — they’re solving a problem that afflicts every enterprise I’ve worked with, using an approach that breaks from decades of content management thinking.</p><p>What follows is my interpretation of why this matters. I’m eager to validate these insights hands-on, but the architectural decisions signal an important shift in enterprise content strategy.</p><h3>The Real Cost of Fragmented Content Intelligence</h3><p>Here’s a scenario every enterprise knows too well: Your marketing team stores brand assets in AEM, your product documentation lives in Confluence, your legacy content sits in some forgotten CMS, and your customer support knowledge base is somewhere else entirely. When someone needs to find information — or worse, when you want to power an AI assistant — you’re stuck with siloed, semantically disconnected content that your systems can barely search, let alone understand.</p><p>Adobe’s Content AI, recently showcased at an AEM conference, tackles this exact problem. But what makes it interesting isn’t just the technology — it’s the strategic architecture decisions that reveal where enterprise AI is actually heading.</p><h3>The Infrastructure-First Approach That Changes Everything</h3><p>The most overlooked insight from the Content AI presentation is this: <strong>treating search as infrastructure rather than as a UI layer</strong>. This isn’t just semantic wordplay — it’s a fundamental reconceptualization that aligns with Gartner’s recent <a href="https://www.gartner.com/en/documents/6341979">recommendations</a> on rethinking enterprise search for AI assistance.</p><p>Traditional enterprise search has been treated as a thin veneer on top of content repositories. You index some fields, add a search box, maybe throw in some filters, and call it done. Content AI flips this model by building search as a foundational platform layer that can power multiple use cases simultaneously.</p><h3>Why This Matters for Organizations</h3><p>Consider the typical enterprise AI implementation:</p><ul><li>You want to add a chatbot? Build a RAG system from scratch.</li><li>Need semantic asset search? Different implementation.</li><li>Want to enable AI-powered content recommendations? Yet another custom solution.</li></ul><p>Each requires its own ingestion pipeline, embedding generation, vector storage, and retrieval logic. Content AI consolidates this into a unified intelligent content layer that serves all these use cases from the same infrastructure.</p><h3>The Multi-Model Strategy: Hedging Your Bets on AI Evolution</h3><p>One of the most pragmatic aspects of Content AI is its support for <strong>vector spaces</strong> — configurations that allow multiple embedding models to coexist on the same content. You might use one model optimized for short queries and another for capturing broader semantics, or run A/B tests between open-source and commercial models.</p><p>This isn’t just about flexibility — it’s about risk management. The AI landscape changes rapidly. Models that are state-of-the-art today may be obsolete in six months. By decoupling your content layer from specific model implementations, you can evolve your AI capabilities without re-indexing or re-architecting your entire system.</p><p>The genius here is in the <strong>index-centric enrichment pipelines</strong>. When you want to experiment with a new embedding model or adjust your semantic search strategy, you don’t touch the original content. The system can reprocess from the indexing layer, making iteration fast and low-risk.</p><h3>Solving the Multilingual Problem Without Thinking About It</h3><p>The demo showed something remarkable: asking questions in German and getting accurate responses from English content with zero additional configuration. For global enterprises spending significant resources on localization and multilingual search, this is transformative.</p><p>Traditional approaches require language-specific analyzers, translation layers, or maintaining parallel content structures. Semantic search with multilingual embeddings collapses this complexity — the system understands meaning, not just words.</p><h3>The Context-Aware Answer Generation Nobody’s Talking About</h3><p>While everyone focuses on RAG and chatbots, Content AI’s contextual metadata processing reveals something more sophisticated. In the demo, changing the user’s location context from India to San Francisco completely altered the generated response to “where to park” — same question, different answer based on context.</p><p>This isn’t just personalization. It’s all about creating systems that can truly understand that queries aren’t just isolated inputs but are part of a bigger picture. Your role, location, department, permissions, and a dozen other contextual factors should shape the response. Most RAG implementations treat every query identically; Content AI builds context sensitivity into the architecture.</p><h3>The Real Challenge: Content That Doesn’t Live in AEM</h3><p>The acquisition component for external content sources is where Content AI moves from “interesting” to “essential.” Most enterprises don’t have all their content in one system — they have legacy CMSs, partner websites, documentation scattered across platforms, and decades of institutional knowledge in various formats.</p><p>Content AI’s approach of making external content “first-class citizens” alongside AEM content is the only realistic path forward. The alternative — migrating everything to a single repository — is a fantasy that’s never going to happen for most organizations.</p><h3>What This Means for Your Content Strategy</h3><p>If you’re an enterprise content strategist or architect, here are the practical implications:</p><p><strong>1. Stop thinking about content management systems as silos.</strong> Your content strategy should assume that content will live in multiple places and focus on creating a unified intelligent layer above them.</p><p><strong>2. Invest in metadata and structure now.</strong> Semantic search is powerful, but structured metadata still matters for filtering, permissions, and precise retrieval. The hybrid approach combining semantic and lexical search is the winning pattern.</p><p><strong>3. Plan for continuous evaluation.</strong> The feedback loops and evaluation pipelines mentioned in the presentation aren’t optional — they’re how you prevent AI systems from degrading over time. Build user feedback mechanisms from day one.</p><p><strong>4. Rethink permissions and access control.</strong> When content from multiple sources feeds into AI responses, ensuring proper authorization becomes more complex but also more critical. The system needs to respect ACLs across all source systems.</p><h3>The Guardrails Question</h3><p>One detail that shouldn’t be overlooked: the demonstration of content guardrails blocking harmful queries. As enterprises rush to deploy AI, they often underestimate the need for safety layers. Content AI builds this in at the architecture level — guardrails at input and output gates.</p><p>This is the right approach. You can’t bolt on safety as an afterthought when you’re exposing AI systems to users, especially in public-facing scenarios.</p><h3>Where Enterprise AI is Actually Heading</h3><p>Content AI represents a maturation of enterprise AI thinking. The hype cycle has moved past “add a chatbot” toward building robust infrastructure that can support multiple AI use cases over time. The key principles that emerge:</p><ul><li><strong>Consolidation over proliferation</strong>: One intelligent content layer instead of many point solutions</li><li><strong>Flexibility over commitment</strong>: Support multiple models and approaches simultaneously</li><li><strong>Infrastructure over features</strong>: Build platforms, not just end-user interfaces</li><li><strong>Context over uniformity</strong>: Understand that the same query needs different answers in different situations</li></ul><h3>The Bottom Line</h3><p>If you’re evaluating enterprise AI strategies, the question isn’t whether to adopt semantic search or RAG or AI assistants. The question is: Do you have the content infrastructure to do any of these well?</p><p>Content AI’s architecture suggests that success requires treating your content layer as intelligent infrastructure — unified, enriched, and optimized for retrieval — rather than as a collection of repositories with search boxes bolted on top.</p><p>The technology is impressive, but the strategic insight is what matters: in the age of AI, your content infrastructure is your competitive advantage. Build it right, and you can experiment with any AI use case. Get it wrong, and you’ll be re-architecting with every new trend.</p><p>Can’t wait to dig into more videos from the conference — there’s so much to unpack.</p><p>What’s your organization’s biggest challenge with enterprise content and AI? Share your thoughts in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aca4d751725" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering HTL: Developer’s Guide to Writing Clean Code]]></title>
            <link>https://medium.com/@giuseppebaglio/mastering-htl-developers-guide-to-writing-clean-code-020b02748aa0?source=rss-7f5958c1a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/020b02748aa0</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[adobe-experience-manager]]></category>
            <dc:creator><![CDATA[Giuseppe Baglio]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 15:22:49 GMT</pubDate>
            <atom:updated>2025-03-17T15:22:49.186Z</atom:updated>
            <content:encoded><![CDATA[<h4>From naming conventions to block statements, discover the key principles for writing clean and effective HTL code.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*LTrZ06WYkkCy7dNrEV9ySw.jpeg" /></figure><p>In this blog post, we’ll take a deep dive into HTL, exploring its core features, best practices, and how you can write efficient and maintainable code using this language. Whether you’re new to AEM development or looking to refine your skills, this guide will help you harness the full potential of HTL.</p><h3>What is HTL?</h3><p>HTL is a server-side templating language specifically designed for AEM. It allows developers to create reusable HTML templates with embedded logic, separating the presentation layer from business logic. Unlike JSP, which often mixes Java code directly into the markup, HTL enforces a cleaner separation of concerns, making it easier to maintain and debug.</p><p>Key features of HTL include:</p><ul><li>Security by default: Automatic XSS protection ensures that output is sanitized unless explicitly overridden.</li><li>Readable syntax: HTL uses familiar HTML-like syntax, reducing the learning curve for front-end developers.</li><li>Integration with Sling Models: HTL works seamlessly with Sling Models, enabling clean data binding between Java objects and templates.</li><li>Performance optimization: HTL compiles into Java classes during runtime, ensuring high performance without sacrificing flexibility.</li></ul><h3>Best Practices for Writing HTL Components</h3><p>HTML Template Language (HTL) is a game-changer for building dynamic, maintainable, and scalable web experiences in Adobe Experience Manager (AEM). But like any powerful tool, its true potential is unlocked only when used thoughtfully.</p><h4>Naming Conventions</h4><p>When naming variables, models, and resources, aim for consistency and descriptiveness. For example, instead of using generic names like item or data, adopt prefixes that reflect the component or context. A good rule of thumb is to use a format like componentName-property. This will make your code more readable and also help avoid naming conflicts, especially in larger projects.</p><pre>&lt;sly data-sly-use.hero=&quot;com.example.models.HeroComponent&quot;&gt;<br>    &lt;h1&gt;${hero.title}&lt;/h1&gt;<br>&lt;/sly&gt;</pre><p>Here, hero clearly indicates that the variable belongs to the HeroComponent. This small step can save hours of debugging and confusion down the line.</p><h4>Avoid Inline Logic: Keep Your Templates Clean</h4><p>One of the most common pitfalls in HTL development is embedding complex logic directly into templates. While it might seem convenient to include a quick calculation or condition within your HTL file, this approach quickly leads to cluttered and hard-to-maintain code</p><p>Instead, delegate complex logic to Sling Models. These Java-based classes are designed to handle business logic and expose data to your HTL templates in a clean, reusable way. By keeping your HTL files focused on rendering, you ensure that they remain lightweight and easy to read.</p><p>For instance, instead of writing:</p><pre>&lt;p&gt;${properties.showBanner ? &#39;Banner Visible&#39; : &#39;Banner Hidden&#39;}&lt;/p&gt;</pre><p>You could move the logic to a Sling Model:</p><pre>@Model(adaptables = Resource.class)<br>public class BannerComponent {<br>    @ValueMapValue<br>    private boolean showBanner;<br><br>    public String getBannerStatus() {<br>        return showBanner ? &quot;Banner Visible&quot; : &quot;Banner Hidden&quot;;<br>    }<br>}</pre><p>And then reference it in your HTL:</p><pre>&lt;sly data-sly-use.banner=&quot;com.example.models.BannerComponent&quot;&gt;<br>    &lt;p&gt;${banner.bannerStatus}&lt;/p&gt;<br>&lt;/sly&gt;</pre><p>This separation of concerns improves readability and also makes your code easier to test and debug.</p><h4>Optimize Loops and Iterations: Preprocess Data Early</h4><p>Loops are a common feature in HTL, especially when working with collections like lists or arrays. However, iterating over large datasets directly in your templates can lead to performance bottlenecks. To avoid this, preprocess your data in Sling Models before passing it to your HTL files.</p><p>For example, if you’re displaying a list of products, filter and sort the dataset in your model:</p><pre>@Model(adaptables = Resource.class)<br>public class ProductListComponent {<br>    @ValueMapValue<br>    private List&lt;Product&gt; allProducts;<br><br>    public List&lt;Product&gt; getFilteredProducts() {<br>        return allProducts.stream()<br>                          .filter(product -&gt; product.isActive())<br>                          .sorted(Comparator.comparing(Product::getName))<br>                          .collect(Collectors.toList());<br>    }<br>}</pre><p>Then, iterate over the preprocessed list in your HTL:</p><pre>&lt;ul data-sly-list.product=&quot;${productList.filteredProducts}&quot;&gt;<br>    &lt;li&gt;${product.name}&lt;/li&gt;<br>&lt;/ul&gt;</pre><p>This approach minimizes runtime overhead and keeps your HTL templates clean and focused on rendering.</p><h4>Use Descriptive Variable Names: Context Matters</h4><p>Imagine trying to decipher what item refers to in a loop. Is it a product? A blog post? A user profile? Without context, even simple code can become confusing. That’s why using descriptive variable names is crucial.</p><p>Instead of defaulting to generic names asitem, choose names that reflect the context of your data. For example:</p><pre>&lt;ul data-sly-list.tag=&quot;${model.tags}&quot;&gt;<br>    &lt;li&gt;${tag.title}&lt;/li&gt;<br>&lt;/ul&gt;</pre><p>Here, tag immediately conveys that the variable represents a tag object. This small change can make a big difference in how quickly others (and the future you) can understand your code.</p><h3>Expression Language Guidelines: Writing Cleaner and Safer HTL Code</h3><p>When working with HTML Template Language (HTL), mastering the expression language is key to writing efficient, secure, and maintainable code. Expressions in HTL allow you to dynamically inject data into your templates, but how you use them can make a significant difference in the quality of your code. Below, we’ll explore some of the important guidelines for using HTL’s expression language effectively.</p><h4>Set Display Context Only When Necessary</h4><p>One of the standout features of HTL is its ability to automatically determine the appropriate display context for expressions. This means that in most cases, you don’t need to explicitly set a display context. For example:</p><pre>&lt;p&gt;${teaser.title}&lt;/p&gt;</pre><p>Here, HTL will automatically infer that teaser.title should be treated as plain text. Explicitly setting a display context is only necessary when the default behaviour doesn’t align with your needs. For instance, if you’re injecting HTML content, you might specify the html context:</p><pre>&lt;div&gt;${teaser.htmlContent @ context=&#39;html&#39;}&lt;/div&gt;h</pre><p>By avoiding unnecessary context declarations, you keep your code cleaner and easier to read.</p><h4>Use the Safest Possible Display Context</h4><p>Security should always be a priority when working with dynamic content. HTL provides a range of display contexts to ensure your output is properly escaped and sanitized. To maximize security, always choose the safest context that fits your scenario. Here’s a quick breakdown of common contexts:</p><ul><li>number : For numeric values.</li><li>uri : For URLs or paths.</li><li>text : For plain text content.</li><li>html : For injecting safe HTML markup.</li></ul><p>For example, if you’re injecting a URL, use the uri context:</p><pre>&lt;a href=&quot;${link.url @ context=&#39;uri&#39;}&quot;&gt;Visit Link&lt;/a&gt;</pre><p>Choosing the wrong context can expose your application to vulnerabilities like Cross-Site Scripting (XSS). Always err on the side of caution and select the most restrictive context that meets your requirements (full list of <a href="https://github.com/adobe/htl-spec/blob/master/SPECIFICATION.md#121-display-context">Display Context</a>).</p><h4>Avoid Unnecessary Expressions for Literals</h4><p>It might seem obvious, but redundant expressions can clutter your code and make it harder to maintain. For example, consider this snippet:</p><pre>&lt;p&gt;${&quot;Hello World&quot;}&lt;/p&gt;</pre><p>This is functionally identical to:</p><pre>&lt;p&gt;Hello World&lt;/p&gt;</pre><p>By removing unnecessary expressions, you simplify your templates and reduce cognitive load for anyone reading your code. Reserve expressions for dynamic data, not static content.</p><h4>Simplify Code with Logical Operators</h4><p>HTL supports logical operators, which can help you write cleaner and more concise code. Instead of relying on ternary operators, you can often achieve the same result with logical || (OR) or &amp;&amp; (AND) operators.</p><p>For example, instead of writing:</p><pre>&lt;p&gt;${properties.subtitle ? properties.subtitle : &#39;No subtitle available&#39;}&lt;/p&gt;</pre><p>You can simplify it to:</p><pre>&lt;p&gt;${properties.subtitle || &#39;No subtitle available&#39;}&lt;/p&gt;</pre><p>This approach reduces verbosity and improves readability. Logical operators are particularly useful for providing fallback values or handling optional properties.</p><h4>Utilize Native URI Manipulation Features</h4><p>Building URLs manually can be error-prone and time-consuming. Fortunately, HTL includes built-in URI manipulation capabilities that simplify this process. For example, you can append query parameters or modify file extensions without hardcoding strings:</p><pre>&lt;a href=&quot;${link.url @ extension=&#39;html&#39;}&quot;&gt;Read More&lt;/a&gt;</pre><p>Using these native features ensures consistency and reduces the risk of mistakes. Rolling your own URI builder or hardcoding URLs is discouraged because it introduces unnecessary complexity and the potential for errors.</p><h3>Block Statements Best Practices: Writing Clean and Maintainable HTL Code</h3><p>Block statements are the backbone of HTML Template Language (HTL), enabling developers to inject logic, iterate over data, and structure templates efficiently. However, using block statements effectively requires adherence to best practices that prioritize clarity, performance, and maintainability. Below, we’ll explore some important guidelines for working with block statements in HTL.</p><h4>Use sly Tag for Non-Markup Elements</h4><p>The sly tag is a powerful tool in HTL that allows you to include logic or functionality without cluttering your final HTML output. Any element of the sly tag is automatically unwrapped during rendering, meaning it won’t appear in the final markup.</p><p>For example:</p><pre>&lt;sly data-sly-use.teaser=&quot;com.example.models.TeaserComponent&quot;&gt;<br>    &lt;h1&gt;${teaser.title}&lt;/h1&gt;<br>&lt;/sly&gt;</pre><p>The sly tag ensures that only the &lt;h1&gt; element appears in the rendered HTML. This keeps your templates clean and avoids unnecessary elements in the DOM.</p><p>Note: If you’re using HTL 1.0 (AEM 6.0), you’ll need to explicitly add the data-sly-unwrap attribute to achieve the same behaviour.</p><h4>Organize data-sly-use Statements at the Top Level</h4><p>When working with data-sly-use, it’s crucial to place these statements at the top level of your template. Since identifiers created with data-sly-use are global, organizing them at the top makes it easier to spot naming conflicts and prevents redundant initializations.</p><p>For example:</p><pre>&lt;sly data-sly-use.teaser=&quot;com.example.models.TeaserComponent&quot;<br>     data-sly-use.navigation=&quot;com.example.models.NavigationComponent&quot;&gt;<br>    &lt;h1&gt;${teaser.title}&lt;/h1&gt;<br>    &lt;nav&gt;${navigation.links}&lt;/nav&gt;<br>&lt;/sly&gt;</pre><p>This approach ensures that all dependencies are declared upfront, improving readability and maintainability.</p><h4>Follow lowerCamelCase Naming Convention</h4><p>Consistency in naming conventions improves code readability and reduces confusion. In HTL, identifiers should follow the lowerCamelCase convention, where the first word is lowercase, and subsequent words are capitalized (e.g., sampleIdentifierName).</p><p>For example:</p><pre>&lt;sly data-sly-use.teaserComponent=&quot;com.example.models.TeaserComponent&quot;&gt;<br>    &lt;h1&gt;${teaserComponent.title}&lt;/h1&gt;<br>&lt;/sly&gt;</pre><p>This standard aligns with common programming practices and ensures compatibility with HTL’s internal handling of identifiers.</p><h4>Reuse Expressions with Identifiers</h4><p>Reusing expressions not only optimizes performance but also enhances code clarity. Instead of repeating the same expression multiple times, define an identifier with data-sly-set and reuse it:</p><pre>&lt;sly data-sly-set.fullName=&quot;${user.firstName + &#39; &#39; + user.lastName}&quot;&gt;<br>    &lt;p&gt;Welcome, ${fullName}!&lt;/p&gt;<br>    &lt;p&gt;Your profile is ready, ${fullName}.&lt;/p&gt;<br>&lt;/sly&gt;</pre><p>This approach allows the HTL compiler to cache the result, reducing redundant evaluations and improving efficiency.</p><h4>Use Descriptive Variable Names in Lists</h4><p>When iterating over lists, avoid using default variable names like item. Instead, choose names that reflect the context of the data. For example:</p><pre>&lt;ul data-sly-list.tag=&quot;${model.tags}&quot;&gt;<br>    &lt;li&gt;${tag.title}&lt;/li&gt;<br>&lt;/ul&gt;</pre><p>Here, tag provides meaningful context, making the code easier to read and understand.</p><h4>Prioritize Block Statements Over Regular Attributes</h4><p>Block statements should always come before regular HTML attributes. This ensures that variables declared via data-sly-use or other block statements are available when needed. Additionally, block statements often determine whether an element appears at all (data-sly-test) or multiple times (data-sly-repeat), making their placement critical.</p><pre>&lt;div data-sly-test=&quot;${properties.showBanner}&quot; class=&quot;banner&quot;&gt;<br>    &lt;p&gt;This banner is visible!&lt;/p&gt;<br>&lt;/div&gt;</pre><p>Placing data-sly-test before the class attribute ensures logical consistency and avoids potential issues.</p><h4>Leverage Existing HTML Elements for Block Statements</h4><p>Whenever possible, attach block statements to existing HTML elements instead of creating additional wrappers. This keeps your templates concise and avoids unnecessary complexity.</p><p>For example:</p><pre>&lt;h1 data-sly-text=&quot;${teaser.title}&quot;&gt;&lt;/h1&gt;</pre><p>This approach eliminates the need for extra &lt;sly&gt; tags or divs, resulting in cleaner code.</p><h3>Avoid Certain Block Statement Types</h3><p>Certain block statements, such as element, attribute, and text, can make your code harder to read and maintain. Instead, opt for more explicit and straightforward alternatives.</p><p>For example, instead of:</p><pre>&lt;div data-sly-element=&quot;${headlineElement}&quot;&gt;${event.year}&lt;/div&gt;<br>&lt;span data-sly-text=&quot;${event.year}&quot;&gt;&lt;/span&gt;<br>&lt;a data-sly-attribute.href=&quot;${event.link}&quot; href=&quot;#&quot;&gt;&lt;/a&gt;</pre><p>Use:</p><pre>&lt;h2&gt;${event.year}&lt;/h2&gt;<br>&lt;p&gt;${event.year}&lt;/p&gt;<br>&lt;a href=&quot;${event.link}&quot;&gt;&lt;/a&gt;</pre><p>This simplifies your templates and avoids unnecessary abstraction.</p><h4>Separate Template Definitions</h4><p>Templates should be defined in separate files to keep your codebase organized and modular. This approach makes it easier to reuse templates across components and improves maintainability.</p><p>For example:</p><pre>&lt;!-- teaser.html --&gt;<br>&lt;template data-sly-template.teaser=&quot;${@ title, text}&quot;&gt;<br>    &lt;h1&gt;${title}&lt;/h1&gt;<br>    &lt;p&gt;${text}&lt;/p&gt;<br>&lt;/template&gt;<br><br>&lt;!-- main.html --&gt;<br>&lt;sly data-sly-use.teaserModel=&quot;com.example.models.TeaserComponent&quot;<br>     data-sly-call=&quot;${teaser @ title=teaserModel.title, text=teaserModel.text}&quot;&gt;&lt;/sly&gt;</pre><p>By separating concerns, you create a cleaner and more scalable architecture.</p><h4>Prefer data-sly-set Over data-sly-test</h4><p>While data-sly-test can be used to set variable bindings, it’s better to use data-sly-set for this purpose. Using data-sly-test for variable assignments can unintentionally hide elements if the expression evaluates to false, leading to debugging challenges.</p><p>For example, instead of:</p><pre>&lt;sly data-sly-test.fullName=&quot;${user.firstName + &#39; &#39; + user.lastName}&quot;&gt;<br>    &lt;p&gt;Welcome, ${fullName}!&lt;/p&gt;<br>&lt;/sly&gt;</pre><p>Use:</p><pre>&lt;sly data-sly-set.fullName=&quot;${user.firstName + &#39; &#39; + user.lastName}&quot;&gt;<br>    &lt;p&gt;Welcome, ${fullName}!&lt;/p&gt;<br>&lt;/sly&gt;</pre><p>This approach avoids unintentionally hiding elements if the expression evaluates to false. It also ensures predictable behaviour and makes debugging easier, especially when multiple data-sly-test statements are involved. By using data-sly-set, you clearly define variables without affecting the visibility of elements</p><h3>Minimize Unnecessary sly Tags</h3><p>Avoid wrapping elements with sly tags unless absolutely necessary. Instead, attach block statements directly to relevant HTML elements. This reduces visual noise and makes your intentions clearer.</p><p>For example:</p><pre>&lt;h1 data-sly-text=&quot;${teaser.title}&quot;&gt;&lt;/h1&gt;</pre><p>This is cleaner than:</p><pre>&lt;sly data-sly-text=&quot;${teaser.title}&quot;&gt;&lt;/sly&gt;</pre><h3>Use Explicit End Tags for sly</h3><p>Finally, always use explicit end tags for sly elements. Unlike void or foreign elements, sly must be closed with an explicit &lt;/sly&gt; tag. Self-closing tags are not allowed and will result in errors.</p><p>For example:</p><pre>&lt;sly data-sly-use.teaser=&quot;com.example.models.TeaserComponent&quot;&gt;<br>    &lt;h1&gt;${teaser.title}&lt;/h1&gt;<br>&lt;/sly&gt;</pre><p>This ensures compliance with HTL syntax and avoids rendering issues.</p><h3>Final Thoughts</h3><p>In summary, HTL stands out as a powerful tool that not only enhances security and efficiency in component development but also enforces a clear separation between presentation and business logic. By following best practices — such as adhering to proper naming conventions, modularizing components, and leveraging built-in mechanisms like the Use-API — developers can build robust, maintainable, and scalable applications in AEM.</p><p>Remember, while HTL simplifies many aspects of component rendering, the true value lies in how you structure and organize your code. Investing time in establishing consistent coding standards and reusing expressions where possible can significantly reduce technical debt and streamline future development efforts.</p><p>As you refine your HTL components, consider auditing your existing code to ensure it adheres to these best practices. To keep your templates clean, embrace the use of Sling Models and externalized logic, and always strive for a balance between simplicity and functionality.</p><p>Remember that great HTL code tells a story. When another developer looks at your components, they should understand not just what the code does but why it’s structured that way. This approach to writing clear, purposeful code is what sets apart exceptional AEM implementations.</p><h4>Additional Resources and References</h4><ul><li><a href="https://experienceleague.adobe.com/en/docs/experience-manager-htl/content/getting-started">Adobe Getting Started with HTL</a></li><li><a href="https://github.com/adobe/htl-spec/blob/master/SPECIFICATION.md#html-template-language-specification">HTML Template Language Specification</a></li><li><a href="https://experienceleague.adobe.com/en/docs/experience-manager-htl/content/developer-tools">HTL Developer Tools</a></li><li><a href="https://github.com/Netcentric/aem-htl-style-guide/tree/master">AEM HTL Style Guide</a></li><li><a href="https://experienceleague.adobe.com/en/docs/experience-manager-htl/content/code-samples">Adobe Code Samples</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=020b02748aa0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Automate AEM Offline Revision Cleanup]]></title>
            <link>https://medium.com/@giuseppebaglio/how-to-automate-aem-offline-revision-cleanup-f95db0729e71?source=rss-7f5958c1a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/f95db0729e71</guid>
            <category><![CDATA[adobe-experience-manager]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Giuseppe Baglio]]></dc:creator>
            <pubDate>Fri, 21 Feb 2025 09:44:25 GMT</pubDate>
            <atom:updated>2025-02-21T09:44:25.214Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why It Matters (and Why You Should Automate It)</h4><p>Adobe Experience Manager’s Oak repository is like a bustling warehouse: over time, unused data (old checkpoints, orphaned nodes) piles up, slowing performance and eating disk space. While Adobe’s <a href="https://experienceleague.adobe.com/en/docs/experience-manager-65/content/implementing/deploying/deploying/revision-cleanup#how-to-run-offline-revision-cleanup">official documentation</a> explains the <em>what</em> and <em>why</em> of Offline Revision Cleanup (ORC), the <em>how</em> often leaves DevOps executing repetitive tasks.</p><p>I will explore how a simple Bash script can transform this critical-but-tedious process into a one-command operation — safely, efficiently, and with zero manual checklists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ItVJ7Hiv1g3tUwF34vIZLw.png" /><figcaption>Let automation handle the heavy lifting while you focus on something else! ☕📈</figcaption></figure><h3>Why This Script Beats Manual Execution</h3><p>The script isn’t just a wrapper around oak-run.jar. It’s a safety-first automation tool designed for real-world enterprise environments. Here’s what makes it stand out:</p><ol><li><strong>Pre-Flight Checks</strong>: It verifies dependencies (java, lsof), validates paths, and ensures AEM is offline.</li><li><strong>Interactive Prompts</strong> (with an --yes override): No accidental runs.</li><li><strong>Atomic Operations</strong>: Each checkpoint removal and compaction step is isolated. If one fails, the script exits cleanly.</li><li><strong>Color-Coded Logging</strong>: Spot issues at a glance with red errors and green success states.</li></ol><pre># Sample Log Output<br>[INFO] [2023-10-15 14:30:00] Starting offline revision cleanup process  <br>[ERROR] [2023-10-15 14:30:05] Oak command failed: checkpoints segmentstore</pre><h3>Under the Hood: Script Architecture</h3><p>Let’s dissect the critical components:</p><h4>1. Argument Parsing &amp; Validation</h4><p>The script enforces strict input rules. Try passing an invalid port like 99999? It’ll block you. Forget the AEM directory? A friendly error appears.</p><pre># Validate port range<br>if [[ ! &quot;$PORT&quot; =~ ^[0-9]+$ ]] || [ &quot;$PORT&quot; -lt 1 ] || [ &quot;$PORT&quot; -gt 65535 ]; then<br>    log_message &quot;ERROR&quot; &quot;Invalid port number: $PORT&quot;<br>    exit 1<br>fi</pre><h4>2. The Oak Command Engine</h4><p>The run_oak_command function handles all interactions with oak-run.jar, including error trapping. Notice the -Dtar.memoryMapped=true flag, a performance tweak for large repositories: By allowing memory-mapped file access, it reduces I/O overhead during compaction.</p><pre>run_oak_command() {<br>    java -Dtar.memoryMapped=true -jar &quot;$OAK_RUN&quot; &quot;$@&quot;<br>    if [ $? -ne 0 ]; then<br>        log_message &quot;ERROR&quot; &quot;Oak command failed: $@&quot;<br>        exit 1<br>    fi<br>}</pre><h4>3. Safety Nets You’ll Appreciate at 2 AM</h4><ul><li><strong>Port collision prevention</strong>: Script exits if AEM is still up, avoiding data corruption.</li><li><strong>Input validation</strong>: Rejects non-existent paths or invalid ports up front.</li><li><strong>User prompts</strong>: Optional confirmations at each critical stage (unless --yes is set)</li></ul><h3>How to Run It: A Step-by-Step Playbook</h3><ol><li><strong>Prerequisites</strong>:</li></ol><ul><li>AEM instance fully stopped</li><li>oak-run.jar version matching your AEM/Oak deployment</li><li>Backup of crx-quickstart (yes, really!)</li></ul><p>2. <strong>Execute the Script</strong>:</p><pre>./aem-orc-cleanup.sh -d /opt/aem/author -o ./oak-run-1.42.0.jar --yes</pre><p><strong>3. What Happens Next</strong>:</p><ul><li>Segmentstore compaction</li><li>Datastore compaction</li><li>Logs written to stdout</li></ul><p><strong>4. Troubleshooting Cheat Sheet</strong></p><p><strong>Problem</strong>: Script fails with “AEM is still running”<br><strong>Fix</strong>:</p><pre># Find AEM pid among lingering Java processes<br>ps aux | grep java | grep -v grep | awk &#39;{print $2}&#39; <br># Kill AEM process<br>kill -9 AEM_PID</pre><p><strong>Problem</strong>: Oak command failed during compaction<br><strong>Fix</strong>:</p><ol><li>Check Oak/AEM version compatibility</li><li>Ensure adequate disk space (2x repository size)</li><li>Test with --debug for verbose logging</li></ol><p><strong>Problem</strong>: Script fails with Permission denied”<br><strong>Fix</strong>:</p><p>chmod +x aem-orc-cleanup.sh and ensure the user has read/write access to AEM directories.</p><h3><strong>Customizations for Power Users</strong></h3><p>While the base script works out-of-the-box, its real value shines when tailored to your team’s workflow. Here’s how to transform it into a production-ready powerhouse:</p><h3>1. Enhanced Monitoring &amp; Analytics</h3><p>Add a pre-compaction disk usage snapshot to quantify your ROI:</p><pre># Capture before/after metrics  <br>DISK_USAGE_PRE=$(du -sh $CQ_REPO_PATH | awk &#39;{print $1}&#39;)  <br># ... run compaction ...  <br>DISK_USAGE_POST=$(du -sh $CQ_REPO_PATH | awk &#39;{print $1}&#39;)  <br>log_message &quot;INFO&quot; &quot;Disk reclaimed: $DISK_USAGE_PRE → $DISK_USAGE_POST&quot;</pre><h3>2. Intelligent Alerting</h3><p>Replace passive logging with proactive notifications. For example, trigger a Slack alert on failure:</p><pre>if [ $? -ne 0 ]; then  <br>    curl -X POST -H &#39;Content-type: application/json&#39; \  <br>    --data &quot;{\&quot;text\&quot;:\&quot;🚨 AEM ORC failed on $(hostname)\&quot;}&quot; \  <br>    https://hooks.slack.com/services/YOUR_WEBHOOK  <br>fi</pre><h3>3. Dynamic Retry Logic</h3><p>Oak compaction can fail due to transient I/O issues. Add resilience with exponential backoff:</p><pre>MAX_RETRIES=3  <br>RETRY_DELAY=60 # seconds<br>for ((i=1; i&lt;=$MAX_RETRIES; i++)); do  <br>    run_oak_command &quot;compact&quot; &quot;$store&quot;  <br>    if [ $? -eq 0 ]; then  <br>        break  <br>    fi  <br>    sleep $(($RETRY_DELAY * $i))  <br>done</pre><p><em>What’s your killer customization?</em> Please share it in the comments.</p><h3><strong>Final Thoughts: Elevating Maintenance from Chore to Strategic Advantage</strong></h3><p>Let’s face it: tasks like Offline Revision Cleanup rarely make the highlight reel of a developer’s day. They’re the unsung, unglamorous chores that keep systems alive. But the truth is <em>how</em> you handle these tasks defines the reliability of your AEM ecosystem.</p><p>This script isn’t just about avoiding OutOfDiskSpaceErrors or shaving seconds off query times. It’s about <strong>operational maturity</strong>. By automating ORC, you’re not just solving a problem, you’re institutionalizing consistency. You’re replacing tribal knowledge (“How did we do this last time?”) with version-controlled, auditable code.</p><p>For DevOps teams, the payoff is twofold:</p><ol><li><strong>Risk Reduction</strong>: No more “fat-finger” mistakes during manual compaction.</li><li><strong>Scalability</strong>: Apply the same script across dev, stage, and prod environments with predictable results.</li></ol><p><strong>What’s Next?</strong></p><ul><li>Grab the script, tweak it for your team’s alerting/logging stack, and run it in a staging environment.</li><li>Measure the before/after: Disk space reclaimed? Startup times improved? Share the metrics with leadership — it’s a win they’ll understand.</li><li><em>Bonus points</em>: Integrate it into your CI/CD pipeline as a post-deployment health check.</li></ul><p>IMHO the future of AEM ops isn’t about working harder — it’s about scripting smarter. Now, go turn those maintenance windows into something more exciting. (Or at least, something that doesn’t keep you up at night.)</p><p><em>What’s your automation success story? Drop a comment below — I’d love to hear how you’re taming AEM’s complexity.</em></p><pre>#!/bin/bash<br><br><br># =============================================================================<br># AEM Offline Revision Cleanup Script<br># =============================================================================<br># Purpose: Performs maintenance operations on Adobe Experience Manager&#39;s Oak <br># repository, including checkpoint management and compaction.<br>#<br># Source: https://experienceleague.adobe.com/en/docs/experience-manager-65/content/implementing/deploying/deploying/revision-cleanup#how-to-run-offline-revision-cleanup<br>#<br># Version: 1.0.0<br># Author: Giuseppe Baglio<br># =============================================================================<br><br># Color definitions for better readability<br>RED=&#39;\033[0;31m&#39;<br>GREEN=&#39;\e[0;32m&#39;<br>YELLOW=&#39;\e[0;33m&#39;<br>BLUE=&#39;\e[0;34m&#39;<br>NC=&#39;\033[0m&#39; # No Color<br><br><br># Default values for command line arguments<br>PORT=4502<br>CQ_HOME=&quot;&quot;<br>OAK_RUN=&quot;&quot;<br>SKIP_CONFIRMATION=false # Flag to skip user confirmation<br>DEBUG_MODE=false<br><br># Function to display usage/help message<br>show_help() {<br>    cat &lt;&lt; EOF<br>Usage: $(basename &quot;$0&quot;) [OPTIONS]<br><br>Performs offline revision cleanup for an AEM instance, including checkpoint management<br>and compaction of the Oak repository.<br><br>Options:<br>    -h, --help              Display this help message<br>    -p, --port PORT         Specify the AEM instance port (default: 4502)<br>    -d, --aem-dir DIR       Specify the AEM installation directory (required)<br>    -o, --oak-run FILE      Specify the path to oak-run.jar (required)<br>    -y, --yes               Skip confirmation prompts and proceed automatically<br>    --debug                 Enable debug mode for verbose output<br><br>Example:<br>    $(basename &quot;$0&quot;) --port 4502 --aem-dir /path/to/aem --oak-run /path/to/oak-run.jar --yes<br><br>Requirements:<br>    - Java 1.8 or higher<br>    - lsof utility<br>    - AEM must be completely shut down before running this script<br>    - Adequate disk space for compaction<br><br>Note: Always maintain a backup before running this script.<br><br>EOF<br>    exit 1<br>}<br><br># Function to log messages with timestamp<br>log_message() {<br>    local level=$1<br>    shift<br>    local message=$*<br>    local timestamp<br>    timestamp=$(date &#39;+%Y-%m-%d %H:%M:%S&#39;)<br>    <br>    case &quot;$level&quot; in<br>        &quot;INFO&quot;)  printf &quot;${GREEN}[INFO]${NC} &quot;;;<br>        &quot;WARN&quot;)  printf &quot;${YELLOW}[WARN]${NC} &quot;;;<br>        &quot;ERROR&quot;) printf &quot;${RED}[ERROR]${NC} &quot;;;<br>        *)       printf &quot;[${level}] &quot;;;<br>    esac<br>    <br>    printf &quot;[%s] %s\n&quot; &quot;$timestamp&quot; &quot;$message&quot;<br>}<br><br># Function to handle debug output<br>debug_log() {<br>    if [ &quot;$DEBUG_MODE&quot; = true ]; then<br>        log_message &quot;DEBUG&quot; &quot;$*&quot;<br>    fi<br>}<br><br>check_dependencies() {<br>    local dependencies=(&quot;java&quot; &quot;lsof&quot;)<br>    for dep in &quot;${dependencies[@]}&quot;; do<br>        if ! command -v &quot;$dep&quot; &gt; /dev/null 2&gt;&amp;1; then<br>            log_message &quot;ERROR&quot; &quot;&#39;$dep&#39; is not installed. Please install it and try again.&quot;<br>            exit 1<br>        fi<br>        debug_log &quot;Found required dependency: $dep&quot;<br>    done<br>}<br><br># Function to parse command line arguments<br>parse_arguments() {<br>    while [[ $# -gt 0 ]]; do<br>        case $1 in<br>            -h|--help)<br>                show_help<br>                ;;<br>            -p|--port)<br>                PORT=&quot;$2&quot;<br>                shift 2<br>                ;;<br>            -d|--aem-dir)<br>                CQ_HOME=&quot;$2&quot;<br>                shift 2<br>                ;;<br>            -o|--oak-run)<br>                OAK_RUN=&quot;$2&quot;<br>                shift 2<br>                ;;<br>            -y|--yes)<br>                SKIP_CONFIRMATION=true<br>                shift<br>                ;;<br>            --debug)<br>                DEBUG_MODE=true<br>                shift<br>                ;;<br>            *)<br>                log_message &quot;ERROR&quot; &quot;Unknown option: $1&quot;<br>                show_help<br>                ;;<br>        esac<br>    done<br><br>    # Validate required arguments<br>    if [[ ! -d &quot;$CQ_HOME&quot; ]]; then<br>     log_message &quot;ERROR&quot; &quot;AEM directory (-d|--aem-dir) is required and must exist&quot;<br>        show_help<br>    fi<br>    # Validate oak-run.jar<br>    if [[ ! -f &quot;$OAK_RUN&quot; ]]; then<br>        log_message &quot;ERROR&quot; &quot;oak-run.jar not found at &#39;$OAK_RUN&#39;&quot;<br>        exit 1<br>    fi<br> # Validate port number<br>    if [[ ! &quot;$PORT&quot; =~ ^[0-9]+$ ]] || [ &quot;$PORT&quot; -lt 1 ] || [ &quot;$PORT&quot; -gt 65535 ]; then<br>        log_message &quot;ERROR&quot; &quot;Invalid port number: $PORT (must be between 1 and 65535)&quot;<br>        exit 1<br>    fi<br>}<br><br># Function to run oak commands with proper error handling<br>run_oak_command() {<br>    local command=$1<br>    local store=$2<br>    local args=${3:-&quot;&quot;}<br>    <br>    debug_log &quot;Running oak command \&quot;$command\&quot; on $store with args \&quot;$args\&quot;&quot;<br>    <br>    java -Dtar.memoryMapped=true -jar &quot;$OAK_RUN&quot; &quot;$command&quot; &quot;$CQ_REPO_PATH/$store&quot; $args<br>    <br>    if [ $? -ne 0 ]; then<br>        log_message &quot;ERROR&quot; &quot;Oak command failed: $command $store $args&quot;<br>        exit 1<br>    fi<br>}<br><br># Function to check if AEM is running<br>check_aem_off() {<br>    lsof -i tcp:&quot;${PORT}&quot; | awk &#39;NR!=1 {print $2}&#39; | sort -u | wc -l<br>}<br><br># Function to prompt for user confirmation<br>wait_user_input() {<br>    local prompt_message=${1:-&quot;Do you wish to continue&quot;}<br>    local additional_info=$2<br><br>    # If --yes flag was used, skip confirmation<br>    if [ &quot;$SKIP_CONFIRMATION&quot; = true ]; then<br>        log_message &quot;INFO&quot; &quot;Skipping confirmation (--yes flag used)&quot;<br>        return 0<br>    fi<br><br>    # Display additional information if provided<br>    if [ -n &quot;$additional_info&quot; ]; then<br>        printf &quot;\n%s\n&quot; &quot;$additional_info&quot;<br>    fi<br><br><br>    printf &quot;\n${YELLOW}%s [Y/n]${NC} &quot; &quot;$prompt_message&quot;<br>    read -r response<br><br>    case $response in<br>        &quot;y&quot;|&quot;yes&quot;|&quot;Y&quot;|&quot;&quot;)  # Empty response defaults to yes<br>            return 0<br>            ;;<br>        &quot;n&quot;|&quot;N&quot;|&quot;no&quot;)<br>            log_message &quot;INFO&quot; &quot;Operation cancelled by user&quot;<br>            exit 0<br>            ;;<br>        *)<br>            log_message &quot;ERROR&quot; &quot;Please answer &#39;y&#39; for yes or &#39;n&#39; for no (default: y)&quot;<br>            ;;<br>    esac<br><br>}<br><br># Main script execution starts here<br>check_dependencies<br>parse_arguments &quot;$@&quot;<br><br># Set repository paths<br>CQ_SEGMENTSTORE_HOME=&quot;crx-quickstart/repository&quot;<br>CQ_REPO_PATH=&quot;$CQ_HOME/$CQ_SEGMENTSTORE_HOME&quot;<br><br># Validate repository path<br>if [ ! -d &quot;$CQ_REPO_PATH&quot; ]; then<br>    log_message &quot;ERROR&quot; &quot;Repository folder not found: $CQ_REPO_PATH&quot;<br>    exit 1<br>fi<br><br># Check if AEM is running<br>if [ &quot;$(check_aem_off)&quot; -eq 0 ]; then<br>    log_message &quot;WARN&quot; &quot;[!] Always make sure you have a recent backup of the AEM instance.&quot;<br>    log_message &quot;INFO&quot; &quot;Starting offline revision cleanup process&quot;<br>    <br>    # Process both datastore and segmentstore<br>    for store in segmentstore datastore; do<br>        log_message &quot;INFO&quot; &quot;Processing $store...&quot;<br>        <br>        log_message &quot;INFO&quot; &quot;Finding old checkpoints in $store&quot;<br>        wait_user_input<br>        run_oak_command &quot;checkpoints&quot; &quot;$store&quot;<br>        <br>        log_message &quot;INFO&quot; &quot;Removing unreferenced checkpoints from $store&quot;<br>        wait_user_input<br>        run_oak_command &quot;checkpoints&quot; &quot;$store&quot; &quot;rm-unreferenced&quot;<br>        <br>        log_message &quot;INFO&quot; &quot;Running compaction on $store&quot;<br>        wait_user_input<br>        run_oak_command &quot;compact&quot; &quot;$store&quot;<br>        <br>        log_message &quot;INFO&quot; &quot;Completed processing $store&quot;<br>    done<br><br>    log_message &quot;INFO&quot; &quot;Revision cleanup completed successfully&quot;<br>else<br><br> log_message &quot;ERROR&quot; &quot;AEM is still running on port $PORT. Please shut it down first.&quot;<br>    exit 1<br>fi</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f95db0729e71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can Caching of Sling Models Optimize Performance?]]></title>
            <link>https://medium.com/@giuseppebaglio/can-caching-of-sling-models-optimize-performance-545c56b8d35b?source=rss-7f5958c1a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/545c56b8d35b</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[adobe-experience-manager]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Giuseppe Baglio]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 15:26:49 GMT</pubDate>
            <atom:updated>2025-02-12T15:26:49.782Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explore the benefits, pitfalls, and best practices for caching in Sling Models.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2Dqntkkw90Uj_gUQ4ddGw.png" /></figure><p>In Adobe Experience Manager (AEM) development, Sling Models have become the de facto standard for building components. They let us map data from the Java Content Repository (JCR) into simple, annotation-driven POJOs. One powerful — but sometimes tricky — feature of Sling Models is caching. When used correctly, caching can significantly boost performance. When misused, it can lead to memory issues or stale content. In this article, we’ll take a deep dive into how cacheable Sling Models work, what benefits they offer, and how to avoid common pitfalls — all while keeping the conversation friendly and developer-focused.</p><h3>Introduction</h3><p>Imagine a busy AEM site where every page loads smoothly because it reuses model instances rather than reinitializing them every time. That’s the promise of caching in Sling Models. But if we’re not careful, cached models can hold onto more than they should, leading to heavier memory usage or even affecting garbage collection.</p><p>This post is for those who want to balance performance gains with robust design. Whether you’re a seasoned developer or a consultant working in IT services, the insights here will help you decide when to use caching — and when to steer clear.</p><h3>Understanding Sling Models and Caching</h3><p>At its core, a Sling Model is a Java object annotated to automatically inject properties from a resource. For example, a simple model might look like this:</p><pre>@Model(adaptables = Resource.class, cache = true)<br>public class MyComponentModel {<br>    @ValueMapValue<br>    private String title;<br>    <br>    public String getTitle() {<br>        return title;<br>    }<br>}</pre><p>By setting cache = true in the @Model annotation, you tell the Sling Models framework to store the adaptation result. In practice, if you adapt the same resource multiple times during a single request, you get the same instance— a handy trick for reducing processing overhead.</p><p>But here’s the catch: caching is a double-edged sword. It can save you time, yet if the cached model holds onto references (like a ResourceResolver), it might prevent the garbage collector from reclaiming memory. The official <a href="https://sling.apache.org/documentation/bundles/models.html#caching-adaptions-1">Sling Models documentation</a> provides some guidance, but as we’ll see, there’s more nuance in real-world applications.</p><h3>The Cachable Feature of Sling Models</h3><p>Caching is a powerful feature in Sling Models that can dramatically improve the performance of your AEM applications. By storing frequently accessed data in memory, caching reduces the need for repeated computations and database queries, resulting in faster response times and a smoother user experience.</p><h3>Benefits of Caching Sling Models</h3><p>Caching is a powerful feature in Sling Models and here is why you might want to use caching:</p><ul><li><strong>Improved Response Times:</strong> When you cache a model, you avoid the cost of repeatedly running injections and processing business logic. This can reduce page rendering times — especially critical in high-traffic scenarios.</li><li><strong>Resource Efficiency:</strong> Fewer instantiations mean fewer JCR lookups and less CPU overhead. In environments where every millisecond counts, that reduction can be a game changer.</li><li><strong>Enhanced User Experience</strong>: Faster response times and smoother interactions lead to a better overall user experience, which can translate to higher engagement and satisfaction.</li></ul><p>In real-world applications, these benefits translate to faster pages and a smoother user experience — a win for developers and end users alike.</p><h3>Potential Pitfalls</h3><p>Caching isn’t without risks, an improper usage can led to:</p><ul><li><strong>Heap Space Exhaustion</strong>: In older implementations of Sling Models (version 1.4.8 or below), storing the original adaptable in a Sling Model can lead to heap space exhaustion, causing the JVM to crash. This issue has been addressed in later versions, but it’s still important to be aware of the risks.</li></ul><blockquote><em>The model ends up holding onto its adaptable, which prevents normal garbage collection cycles until memory pressure forces cleanup.<br> — summarized </em><a href="https://www.mail-archive.com/dev@sling.apache.org/msg131936.html"><em>original concept</em></a><em> from </em>Paul Bjorkstrand</blockquote><ul><li><strong>Unexpected Behavior</strong>: Improper caching can lead to unpredictable behaviour, such as models being created multiple times when they should be cached. This can result in inconsistent data and a degraded user experience.</li><li><strong>Increased Complexity</strong>: Caching can add complexity to your application, making it more challenging to maintain and debug. It’s essential to carefully consider where and how to implement caching to avoid introducing unnecessary complexity.</li></ul><h3>Best Practices for Implementing Cacheable Sling Models</h3><p>So, how can you get the best out of caching without falling into common traps?</p><ol><li><strong>Be Selective with Caching:</strong> Not every Sling Model should be cached. Reserve caching for models where the overhead of instantiation is significant and the data is relatively static during a request.</li><li><strong>Manage References Carefully:</strong> If your model injects a resource or a ResourceResolver via @Self, clear that reference in a @PostConstruct method to break any reference cycles.</li><li><strong>Monitor and Profile:</strong> Use tools like heap dumps and performance profilers to measure the impact of caching. Compare adaptation times with and without caching to make data-driven decisions.</li></ol><p>For example, rather than writing:</p><pre>@Model(adaptables = SlingHttpServletRequest.class, cache = true)<br>public class CachedModel {<br>    @Self<br>    private SlingHttpServletRequest request;<br>    // ... additional fields and methods<br>}</pre><p>You might add a cleanup step:</p><pre>@PostConstruct<br>private void init() {<br>    // ... perform costly operations<br>    // Release the request to prevent memory retention issues<br>    this.request = null;<br>}</pre><p>This small change can help prevent unwanted memory retention while still reaping the performance benefits of caching.</p><h3>Conclusion and Recommendations</h3><p>In summary, cacheable Sling Models offer a powerful means to improve the performance of your AEM applications by reducing redundant model instantiation and easing resource consumption. However, like any caching strategy, they require careful handling to avoid pitfalls like memory retention and stale data.</p><p><strong>Key takeaways:</strong></p><ul><li>Use caching judiciously in models where performance gains are clear.</li><li>Ensure that references which could block garbage collection are released.</li><li>Continuously monitor performance to make informed adjustments.</li></ul><p>By following these best practices, you can strike the right balance between performance optimization and system stability. I encourage you to experiment with these strategies, monitor your results, and share your insights with the community.</p><h3>Additional Resources</h3><p>For further reading and deeper dives into this topic, check out these resources:</p><ul><li><a href="https://sling.apache.org/documentation/bundles/models.html">Official Sling Models Documentation</a></li><li><a href="https://www.bounteous.com/insights/2020/07/22/aem-sling-models-why-bother/">AEM Sling Models — Why Bother? by Bounteous</a></li><li><a href="https://www.mail-archive.com/dev@sling.apache.org/msg131936.html">Sling Model Caching &amp; GC problems</a></li></ul><p>Happy coding, and may your AEM pages load faster than ever!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=545c56b8d35b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thread Dump Deep Dive: Diagnosing JVM’s Hidden Performance Issues]]></title>
            <link>https://medium.com/@giuseppebaglio/thread-dump-deep-dive-diagnosing-jvms-hidden-performance-issues-beadb1bed78a?source=rss-7f5958c1a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/beadb1bed78a</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[adobe-experience-manager]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Giuseppe Baglio]]></dc:creator>
            <pubDate>Wed, 05 Feb 2025 17:01:04 GMT</pubDate>
            <atom:updated>2025-02-05T17:04:14.741Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Learn how to read thread dumps and take control of your application’s runtime behaviour.</em></h4><p>When your Adobe Experience Manager (or in general any JAVA application) instance shows signs of sluggishness, it’s time to roll up your sleeves and dive into the world of thread dumps. IBM Thread Analyzer (TDA) is here to help you untangle the web of threads and pinpoint performance bottlenecks. In this guide, we’ll walk you through how to use IBM TDA to diagnose performance issues in AEM like a pro.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I40bPPbPGzw_dcdM.jpg" /></figure><h3>Step 1: Download and Install IBM TDA</h3><p>Before you can start analyzing thread dumps, you’ll need to download and install <a href="https://www.ibm.com/support/pages/ibm-thread-and-monitor-dump-analyzer-java-tmda">IBM Thread Analyzer</a>. Head over to the official IBM website or your organization’s repository to grab the latest version. Once downloaded, follow the installation instructions for your operating system. It’s quick, easy, and sets the stage for some serious troubleshooting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hCV_yL2hT8n_RlqCylWZOg.png" /><figcaption>Official IBM dowload page for IBM Thread Analyzer</figcaption></figure><h3>Step 2: Capture Thread Dumps from Your AEM Instance</h3><p>Thread dumps are snapshots of all the threads running in your AEM instance at a specific moment. To capture them:</p><ol><li>Access your AEM server.</li><li>Use tools like jstack, kill -3, or AEM’s built-in functionality to generate thread dumps. There is a well-documented page on <a href="http://erience-cloud-kcs/kbarticles/ka-17452">Adobe Docs</a>.</li><li>Save the thread dump files to your local machine.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQvg_q0jnd0WGUFtshG2lw.png" /><figcaption>Adobe page on how to take thread dumps</figcaption></figure><p>Pro Tip: Capture multiple thread dumps at intervals (e.g., every 10 seconds) to get a clearer picture of long-running issues.</p><h3>Step 3: Open the Thread Dumps in IBM TDA</h3><p>Launch IBM TDA and open the thread dump files you’ve captured. Simply drag and drop the files into the application or use the “Open” option to load them. Once loaded, you’ll see a list of thread dumps on the left-hand panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uwdZZvTdML6ZbOLsz5jsOA.png" /><figcaption>IBM TDA interface with thread dumps listed</figcaption></figure><h3>Step 4: Dive into Thread Details</h3><p>To analyze a specific thread dump:</p><ol><li>Select the file from the listing.</li><li>Click the Thread Detail button at the top</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HdZvKI5bm8WwDfnhYNtwWA.png" /><figcaption>Button Thread Detail in IBM TDA UI</figcaption></figure><p>This will display a detailed view of all the threads in that dump. Now, let’s sort the threads by Stack Depth, ensuring the longest stacks appear at the top. Why? Threads with deeper stacks often indicate more complex operations, which are usually where performance issues hide.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AFLrsPNa2Cp0q6S_nV0Lmw.png" /><figcaption>Thread Detail view sorted by Stack Depth</figcaption></figure><h3>Step 5: Identify Threads of Interest</h3><p>Focus on threads with a stack depth of 10 lines or longer. These threads are typically the ones consuming the most resources. Take notes on any threads that stand out — whether due to their names, states, or stack traces.</p><h3>Step 6: Sort by Thread State</h3><p>Next, sort the threads by their State. Scroll down to the Runnable threads. These are the threads that were actively using CPU time when the dump was taken. Keep an eye out for application-specific threads, such as:</p><ul><li>Background job threads: Handling tasks like indexing or replication.</li><li>Request threads: Named like 127.0.0.1 [timestamp] GET /path HTTP/1.1.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cwb4p9GdX-8SarjhonXIxw.png" /><figcaption>Runnable threads highlighted</figcaption></figure><h3>Step 7: Decode Request Timestamps</h3><p>For each request thread, extract the timestamp from its name (e.g., 1347028187737). This Unix epoch timestamp tells you when the user’s browser made the request. Convert it to a human-readable date/time using a tool like <a href="https://www.epochconverter.com/">https://www.epochconverter.com/</a>. Compare this with the thread dump’s timestamp to calculate how long the request has been active.</p><p>If the difference is unusually large (e.g., several seconds or minutes), it could indicate a bottleneck in your application.</p><p>Pro Tip: Keep an eye out for patterns. Are certain types of requests consistently taking longer? For example, requests involving complex queries or resource-heavy operations might be worth optimizing. Additionally, if you notice that specific URLs or endpoints are frequently associated with long-running threads, consider profiling those areas of your codebase.</p><h3>Step 8: Investigate Waiting Threads</h3><p>Thread analysis requires a nuanced approach that goes beyond simple waiting states. While the IBM Thread Analyzer (TDA) interface provides valuable insights into thread relationships, understanding the full context of thread behavior helps create a more complete picture of your application’s performance characteristics.</p><h4>Understanding Thread States</h4><p>When examining threads in TDA, you’ll encounter several important states:</p><p><em>Runnable</em>: These threads are either currently executing or ready to execute when CPU time becomes available. A Runnable state doesn’t necessarily indicate a problem — it’s the natural state for actively working threads.</p><p><em>Waiting</em>: These threads have temporarily paused execution while waiting for a condition to be met. The waiting state can occur for many legitimate reasons, including:</p><ul><li>Resource availability (database connections, file handles)</li><li>Task completion in other threads</li><li>Scheduled delays</li><li>Network I/O completion</li><li>Message queue operations</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P9GD8Qx9SxE4ugSgSgHfBA.png" /><figcaption>Waiting threads panel with highlighted blocking thread</figcaption></figure><p><em>Blocked</em>: These threads are specifically waiting to acquire a monitor or lock. While similar to waiting, blocked states specifically indicate synchronization-related pauses.</p><h4>Analyzing Thread Relationships</h4><p>When you identify a thread of interest, examine its relationships with other threads using this systematic approach:</p><ol><li>Direct Lock Relationships</li></ol><ul><li>Examine the Waiting Threads panel for immediate dependencies</li><li>Review the stack traces of waiting threads to understand why they’re blocked</li><li>Note the duration of the wait states if available</li></ul><p>2. Resource Usage Patterns</p><ul><li>Look for patterns in resource acquisition and release</li><li>Identify potential resource bottlenecks</li><li>Consider alternative resource management strategies</li></ul><p>3. Architectural Implications</p><ul><li>Evaluate if the observed behaviour aligns with the system’s design</li><li>Consider if the current threading model is appropriate</li><li>Assess the impact on scalability</li></ul><h4>Understanding Lock Types and Visibility</h4><p>Thread dumps may not show all types of contention. Modern Java applications use various synchronization mechanisms:</p><ol><li>Intrinsic Locks (synchronized keyword)</li></ol><ul><li>Visible in thread dumps</li><li>Show clear owner-waiter relationships</li><li>Stack traces indicate synchronization points</li></ul><p>2. Explicit Locks (java.util.concurrent)</p><ul><li>ReentrantLock</li><li>ReadWriteLock</li><li>StampedLock</li><li>May require additional tooling to visualize</li></ul><p>3. Non-blocking Mechanisms (Don’t appear as traditional locks but can impact performance)</p><ul><li>Atomic variables</li><li>ConcurrentHashMap</li><li>CompletableFuture</li></ul><h4>Optimization Strategies</h4><p>When you identify genuine contention issues, consider these approaches:</p><ol><li>Code-Level Improvements</li></ol><ul><li>Reduce lock scope</li><li>Implement finer-grained locking</li><li>Consider non-blocking alternatives</li></ul><p>2. Resource Management</p><ul><li>Optimize pool sizes</li><li>Implement backoff strategies</li><li>Consider caching solutions</li></ul><p>3. Architectural Changes</p><ul><li>Evaluate asynchronous processing</li><li>Consider parallel execution paths</li><li>Implement queue-based approaches</li></ul><p>Remember that thread analysis is an iterative process. Patterns that emerge in one thread dump might not represent consistent behaviour. Always validate your findings across multiple dumps and different time periods before making significant changes to your application.</p><h3>Step 9: Compare Across Multiple Thread Dumps for Long-Running Threads</h3><p>Comparing thread dumps across time reveals important performance patterns in your AEM instance. Start by establishing a baseline during normal operation, including peak usage periods and maintenance windows. This baseline provides context for identifying abnormal thread behaviour.</p><p>To determine if a thread is persistent across time:</p><ol><li>Select multiple thread dumps from different points in time.</li><li>Click the Compare Threads button in IBM TDA.</li><li>Look for threads that remain in the Runnable state across all dumps, especially those with consistently long stack traces.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8_2Jon5HmDDBPnY7hIyOTQ.png" /><figcaption>Button Compare Threads in IBM TDA UI</figcaption></figure><p>Use IBM TDA’s Compare Threads feature to analyze dumps from different time points. Focus on threads that persist across multiple dumps, examining their states, stack depths, and resource usage. Remember that thread persistence alone doesn’t automatically indicate a problem — background services naturally run continuously, while request threads should complete within expected timeframes.</p><p>When analyzing persistent Runnable threads, correlate their behaviour with system metrics like CPU usage, memory consumption, and response times. Consider the thread’s purpose: background services, request processing, or maintenance tasks each have different expected patterns. For request threads, compare their duration against defined service level agreements and business requirements.</p><p>Got a suspicious thread pattern? Don’t jump to conclusions just yet! Try to recreate the issue in your test environment first — it’s like having a dress rehearsal before the main show. Take a good look at your code, double-check those config settings, and consider what else might be stirring up trouble in your environment. Keep track of what you find with real performance numbers and test results — you’ll thank yourself later.</p><p>Once you’re sure you’ve caught a real performance culprit (backed by solid evidence, of course), it’s time to fix it.</p><h3>Step 10: Explore Monitor Details and Identify Idle Threads</h3><p>If analyzing threads doesn’t yield actionable insights, switch to the Monitor Detail view:</p><ol><li>Go back to the thread listing.</li><li>Select a thread dump and click the Monitor Detail button.</li><li>IBM TDA will display a tree view of monitor-owning threads and their waiting threads.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ld2CWgFC2-Bf_GmaibjgAQ.png" /><figcaption>Button Monitor Detail in IBM TDA UI</figcaption></figure><p>This view helps you identify threads that are holding monitors and causing contention. Understanding thread monitors is like viewing the nervous system of your application. These synchronization mechanisms control how threads access shared resources, preventing potential conflicts and ensuring smooth operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qv_qcT1awcK55PWvtOgOgw.png" /><figcaption>Monitor Detail tree view</figcaption></figure><p>Monitor interactions can reveal critical performance insights. Some threads will be actively processing requests, while others wait for resource acquisition or participate in coordinated activities. Not all waiting or idle threads indicate a problem — they’re often part of the application’s natural resource management strategy.</p><p>However, not all threads are equally important:</p><ul><li>Ignore idle thread pool threads: These threads typically have ≤10 stack lines and are part of thread pools like the servlet engine. They’re usually harmless unless they dominate the thread pool.</li><li>Focus on application-specific monitors: Look for monitors tied to your application’s business logic, such as database connections, caching mechanisms, or custom synchronization blocks.</li></ul><p>Remember that thread and monitor analysis is both an art and a science. Each application has unique characteristics, so approach performance optimization with curiosity and a holistic perspective. The goal is not to eliminate all waiting threads but to understand and optimize their interactions.</p><p>Advanced Tip: If you notice certain monitors are frequently contended, consider refactoring your code to reduce lock granularity. For example:</p><ul><li>Replace coarse-grained locks with fine-grained ones.</li><li>Use non-blocking algorithms or concurrent data structures where possible.</li><li>Optimize database queries to reduce the time threads spend waiting for locks.</li></ul><h3>Bonus Insight: the Collector Service</h3><p>In some thread dumps, you might notice the <em>Collector Service</em> appearing frequently. This service handles tasks like Garbage Collection, memory management, and resource cleanup. While the Collector Service might seem like a mysterious background process, understanding its behaviour is key to maintaining optimal system performance — think of it like a diligent janitor in a large office building.</p><p>When you notice frequent Collector Service activity, don’t immediately assume disaster. It’s normal for the Collector Service to show up occasionally, but excessive activity could indicate underlying issues:</p><ul><li>Memory leaks: Objects that are not being garbage collected can cause frequent GC cycles.</li><li>High object churn: Rapid creation and destruction of objects can overwhelm the garbage collector.</li><li>Improper JVM settings: Misconfigured heap sizes or GC algorithms can lead to inefficiencies.</li></ul><p>Here are some considerations to optimize resource usage:</p><ul><li>Tuning your JVM settings (e.g., increasing heap size, switching to G1GC).</li><li>Profiling memory usage with tools like <a href="https://eclipse.dev/mat/">Eclipse MAT</a> or <a href="https://www.yourkit.com/">YourKit</a> to identify leaks.</li><li>Reviewing your application’s memory allocation patterns to reduce unnecessary object creation.</li></ul><p>Garbage Collection is not a problem to be solved, but a dynamic system to be understood and optimized. Each application has unique characteristics, and there’s no universal solution.</p><h3>Final Thoughts</h3><p>Thread dump analysis is a developer’s superpower — transforming you from a code writer to a performance detective. IBM Thread Analyzer (TDA) is your key to understanding complex system behaviours, revealing hidden bottlenecks that impact your Java/AEM instance’s performance.</p><p>Like learning an instrument, your skill improves with practice. Each thread dump becomes clearer, revealing intricate patterns of system interactions. The more you analyze, the more intuitive performance optimization becomes.</p><p>Remember, practice makes perfect — the more you analyze thread dumps, the sharper your diagnostic skills will become. 📊💪</p><p>🛠 ️Happy troubleshooting! And don’t forget to share your findings with your team to keep your Java/AEM instance running smoothly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=beadb1bed78a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The DevOps Approach to AEM Packages]]></title>
            <link>https://medium.com/@giuseppebaglio/the-devops-approach-to-aem-packages-08279517e042?source=rss-7f5958c1a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/08279517e042</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[adobe-experience-manager]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Giuseppe Baglio]]></dc:creator>
            <pubDate>Tue, 28 Jan 2025 15:05:09 GMT</pubDate>
            <atom:updated>2025-01-28T15:05:09.181Z</atom:updated>
            <content:encoded><![CDATA[<h3>DevOps Approach to AEM Packages</h3><h4>Automating Creation, Configuration, and Distribution Through Shell Scripting</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nz2ML1eXbJIasknvN9sugQ.jpeg" /><figcaption>Let the script handle the heavy lifting while you enjoy your coffee break! ☕🤖</figcaption></figure><p>Adobe Experience Manager (AEM) packages are the unsung heroes of content management — powerful containers that bundle everything from code and configurations to critical content. But let’s face it: manually creating, configuring, and downloading these packages can feel like a tedious dance of clicks.</p><p>What if you could automate this process with a few keystrokes, ensuring consistency, speed, reliability and less heavy lifting?</p><p>I will show you a Bash script that flips the script (pun intended!) on how AEM developers and admins work with the Package Manager API. Think about crafting packages in seconds, tailoring filters on the fly, and snagging backups with surgical precision — all before your coffee cools to that <em>perfect</em> sipping temperature. ☕</p><blockquote><strong><em>Before we dive in, a quick note</em></strong>: <em>This article is a </em><strong><em>deep dive, </em></strong><em>meticulously detailed and unapologetically technical. We’ll dissect the script’s logic, explore AEM API intricacies, and troubleshoot edge cases. For developers eager to jump straight into the code, you can jump to the bottom of the article. But if you’re here to understand the how and why behind the automation, strap in — we’re going all the way down the rabbit hole.</em> 🕳️</blockquote><h3>1. Script Overview</h3><p>The <strong>create-remote-aem-pkg.sh</strong> script automates interactions with AEM’s Package Manager API, offering a structured approach to package creation, configuration, and distribution. Designed for developers and administrators, it replaces manual workflows with a command-line-driven process that emphasizes consistency and reliability.</p><h4>1.1 Core Functionalities</h4><ul><li><strong>Package Validation</strong>: Checks for existing packages to avoid redundancy before initiating creation.</li><li><strong>Dynamic Filter Injection</strong>: Programmatically defines content paths (e.g., /content/dam, /apps) to include in the package.</li><li><strong>Build Automation</strong>: Triggers package compilation and downloads the output to a specified directory, appending a timestamp to filenames for version control.</li><li><strong>Error Handling</strong>: Validates HTTP responses, folder paths, and authentication to provide actionable feedback during failures.</li><li><strong>Authentication</strong>: Supports basic¹ credential-based authentication via curl.</li></ul><h4>1.2 Key Benefits</h4><ul><li><strong>Efficiency</strong>: Reduces manual steps required for package creation, configuration, and download.</li><li><strong>Consistency</strong>: Ensures uniform package structures and naming conventions across environments.</li><li><strong>Traceability</strong>: Detailed logging at each stage (creation, filtering, building, downloading) aids in auditing and troubleshooting.</li></ul><h4>1.3 Practical Applications</h4><ul><li><strong>Scheduled Backups</strong>: Integrate with cron jobs to regularly archive critical content paths.</li><li><strong>Environment Synchronization</strong>: Replicate configurations or content between AEM instances during deployments.</li><li><strong>Pre-Update Snapshots</strong>: Capture stable states of /etc or /apps before applying system updates.</li></ul><h4>1.4 Prerequisites</h4><ul><li>Access to an AEM instance (credentials, server, port).</li><li>Basic familiarity with Bash scripting and AEM’s Package Manager.</li><li>Permission to create and download packages via the AEM API.</li></ul><h4>1.5 Example Usage</h4><pre>./create-remote-aem-pkg.sh admin securepass123 localhost 4502 backup-group &quot;Content Backup&quot; /backups /content/dam /etc/clientlibs</pre><p>This command creates a package named “Content Backup” under the group backup-group, including /content/dam and /etc/clientlibs, and saves the output to the /backups directory.</p><h3>2. Script Breakdown</h3><p>Let’s dissect the create-remote-aem-pkg.sh script (you can find it at the bottom of the article) to understand how it orchestrates AEM package management. We’ll focus on its structure, key functions, and workflow logic—ideal for developers looking to customize or debug the tool.</p><h4>2.1 Core Functions</h4><ul><li><strong>_log()</strong>: A utility function that prefixes messages with timestamps for clear audit trails.</li></ul><pre>_log () {<br>  echo &quot;[$(date +%Y.%m.%d-%H:%M:%S)] $1&quot;<br>}</pre><p><em>Why it matters</em>: Ensures every action (e.g., “Package built”) is logged with context, simplifying troubleshooting.</p><ul><li><strong>check_last_exec()</strong>: Validates the success of prior commands by checking exit codes and API responses.</li></ul><pre>check_last_exec () {<br>  # Checks $? (exit status) and $CURL_OUTPUT for errors<br>  if [ &quot;$status&quot; -ne 0 ] || [[ $output =~ .*success\&quot;:false* ]]; then<br>    _log &quot;Error detected!&quot;;<br>    exit 1;<br>  fi<br>}</pre><p><em>Why it matters</em>: Prevents silent failures by halting execution on critical errors like authentication issues or invalid paths.</p><h4>2.2 Input Parameters</h4><p>The script accepts seven positional arguments followed by dynamic filters:</p><pre>USR=&quot;$1&quot; # AEM username<br>PWD=&quot;$2&quot; # AEM password<br>SVR=&quot;$3&quot; # Server host (e.g., localhost)<br>PORT=&quot;$4&quot; # Port (e.g., 4502)<br>PKG_GROUP=&quot;$5&quot; # Package group (e.g., &quot;backups&quot;)<br>PKG_NAME=&quot;$6&quot; # Package name (e.g., &quot;dam-backup&quot;)<br>BK_FOLDER=&quot;$7&quot; # Backup directory (e.g., &quot;/backups&quot;)<br>shift 7 # Remaining arguments become filters (e.g., &quot;/content/dam&quot;)</pre><p>Positional arguments ensure simplicity, while shift handles variable filter paths flexibly.</p><h4>2.3 Package Validation &amp; Creation</h4><ul><li><strong>Sanitize Names</strong>: Replaces spaces in PKG_NAME with underscores to avoid URL issues.</li></ul><pre>PKG_NAME=${PKG_NAME// /_}</pre><ul><li><strong>Check Existing Packages</strong>: Uses curl to list packages via AEM’s API, avoiding redundant creations.</li></ul><pre>if [ $(curl ... | grep &quot;$PKG_NAME.zip&quot; | wc -l) -eq 1 ]; then<br>  _log &quot;Package exists—skipping creation.&quot;<br>else<br>  curl -X POST ... # Creates the package<br>fi</pre><h4>2.4 Dynamic Filter Configuration</h4><p>Constructs a JSON array of filters from input paths:</p><pre>FILTERS_PARAM=&quot;&quot;<br>for i in &quot;${!FILTERS[@]}&quot;; do<br>  FILTERS_PARAM+=&quot;{\&quot;root\&quot;: \&quot;${FILTERS[$i]}\&quot;, \&quot;rules\&quot;: []}&quot;<br>  # Adds commas between entries, but not after the last<br>done</pre><p><em>Example output</em>:<br>[{&quot;root&quot;: &quot;/content/dam&quot;}, {&quot;root&quot;: &quot;/apps&quot;}]</p><p>This JSON is injected into the package definition via AEM’s /crx/packmgr/update.jsp endpoint.</p><h4>2.5 Build &amp; Download Workflow</h4><ul><li><strong>Build the Package</strong>: Triggers compilation using AEM’s build command:</li></ul><pre>curl -X POST … -F &quot;cmd=build&quot;</pre><p><em>Note</em>: The script waits for the build to complete before proceeding.</p><ul><li><strong>Download</strong>: Uses curl to fetch the .zip and save it with a timestamped filename:</li></ul><pre>BK_FILE=&quot;$PKG_NAME-$(date +%Y%m%d-%H%M%S).zip&quot;<br>curl -o &quot;$BK_FOLDER/$BK_FILE&quot; ...</pre><h3>3. Error Handling, Security Notes &amp; Logging</h3><p>Robust error handling and logging are critical for unattended scripts like create-remote-aem-pkg.sh, ensuring failures are caught early and logged clearly. Here’s how the script safeguards against unexpected issues and provides actionable insights.</p><h4>3.1 Logging Mechanism</h4><ul><li><strong>Timestamped Logs</strong>: The _log function prefixes every message with a [YYYY.MM.DD-HH:MM:SS] timestamp, creating an audit trail for debugging:</li></ul><pre>_log &quot;Starting backup process...&quot;  <br># Output: [2023.10.25-14:30:45] Starting backup process...</pre><p><em>Why it matters</em>: Timestamps help correlate script activity with AEM server logs or external events (e.g., cron job schedules).</p><ul><li><strong>Verbose Output</strong>: Critical steps, like package creation, filter updates, and downloads, are explicitly logged to track progress.</li></ul><h4>3.2 Error Validation Workflow</h4><p><strong>Pre-Flight Checks</strong>:</p><ul><li>Validates the existence of the backup folder (BK_FOLDER) before proceeding:</li></ul><pre>if [ ! -d &quot;$BK_FOLDER&quot; ]; then  <br>  _log &quot;Backup folder &#39;$BK_FOLDER&#39; does not exist!&quot; &amp;&amp; exit 1  <br>fi  </pre><ul><li>Sanitizes PKG_NAME to avoid URL issues (e.g., spaces replaced with underscores).</li></ul><p><strong>API Response Validation</strong>:<br>The check_last_exec function examines both shell exit codes ($?) and AEM API responses:</p><pre>check_last_exec &quot;Error message&quot; &quot;$CURL_OUTPUT&quot; $CURL_STATUS  </pre><ul><li><strong>Exit Codes</strong>: Non-zero values (e.g., curl network failures) trigger immediate exits.</li><li><strong>API Errors</strong>: Detects success\&quot;:false JSON responses or &quot;HTTP ERROR&quot; strings in AEM output.</li></ul><p><strong>3.3 HTTP Status Verification</strong>:<br>When downloading the package, the script checks for a 200 status code:</p><pre>if [ &quot;$(curl -w &quot;%{http_code}&quot; ...)&quot; -eq &quot;200&quot; ]; then  <br>  # Proceed if download succeeds  <br>else  <br>  _log &quot;Error downloading the package!&quot; &amp;&amp; exit 1  <br>fi  </pre><h4>3.4 Common Failure Scenarios</h4><ul><li>Invalid credentials: check_last_exec catches 401 Unauthorized responses and exits with a clear error message.</li><li>Invalid filter path: AEM API returns success:false, the script logs &quot;Error adding filters&quot; and terminates.</li><li>Disk full: Fails to write BK_FILE, checks file size with -s flag and alerts before exiting.</li><li>AEM instance unreachable:curl exits with a non-zero code, the script logs &quot;Error building the package&quot;.</li></ul><h4>3.5 Security Considerations</h4><ul><li><strong>SSL Certificate Bypass</strong>: The script uses curl -k for simplicity, which skips SSL verification.<br><em>Recommendation for Production</em>: Replace with --cacert to specify a CA bundle.</li><li><strong>Plaintext Passwords</strong>: Credentials are passed as arguments, which may appear in process logs.<br><em>Mitigation</em>: Use environment variables or a secrets vault (e.g., $AEM_PASSWORD).</li></ul><h4>3.6 Debugging Tips</h4><ul><li><strong>Enable Verbose Output</strong>: Temporarily add set -x at the script’s start to print executed commands.</li><li><strong>Test API Calls Manually</strong>: Isolate issues by running critical curl commands outside the script</li><li><strong>Inspect Logs</strong>: Redirect script output to a file for later analysis:</li></ul><pre>./create-remote-aem-pkg.sh ... &gt;&gt; /var/log/aem_backup.log 2&gt;&amp;1  </pre><h3><strong>4. Tailoring the Tool to Your Workflow</strong></h3><p>The create-remote-aem-pkg.sh script is designed to be a starting point—a foundation you can modify to align with your team’s needs. Below are common customizations, along with implementation guidance, to extend its functionality or adapt it to specific use cases.</p><h4>4.1 Adjusting the Backup Filename Format</h4><p>The default filename uses a timestamp ($PKG_NAME-$(date +%Y%m%d-%H%M%S).zip). Modify this to include environment names, project IDs, or semantic versioning:</p><pre># Example: Include environment (e.g., &quot;dev&quot;, &quot;prod&quot;)  <br>BK_FILE=&quot;${PKG_NAME}-${ENV}-$(date +%Y%m%d).zip&quot;  <br><br># Example: Add Git commit SHA for traceability  <br>COMMIT_SHA=$(git rev-parse --short HEAD)  <br>BK_FILE=&quot;${PKG_NAME}-${COMMIT_SHA}.zip&quot;  </pre><p><em>Tip</em>: Ensure date/time formats avoid characters forbidden in filenames (e.g., colons : on Windows).</p><h4>4.2 Expanding or Modifying Filters</h4><p>The script accepts dynamic paths as filters but you can also hardcode frequently used paths or add exclusions:</p><pre># Hardcode essential paths (e.g., &quot;/var/audit&quot;)  <br>DEFAULT_FILTERS=(&quot;/content/dam&quot; &quot;/apps&quot; &quot;/var/audit&quot;)  <br>FILTERS=(&quot;${DEFAULT_FILTERS[@]}&quot; &quot;${@}&quot;)  # Merge with command-line inputs  <br><br># Add exclusion rules (requires AEM API support)  <br>FILTERS_PARAM+=&quot;{\&quot;root\&quot;: \&quot;${FILTERS[$i]}\&quot;, \&quot;rules\&quot;: [{\&quot;modifier\&quot;: \&quot;exclude\&quot;, \&quot;pattern\&quot;: \&quot;.*/test/*\&quot;}]}&quot;  </pre><h4>4.3 Enhancing Security</h4><p><strong>Avoid Plaintext Passwords</strong>:<br>Use environment variables or a secrets manager to inject credentials:</p><pre># Fetch password from environment variable  <br>PWD=&quot;$AEM_PASSWORD&quot;  <br><br># Use AWS Secrets Manager (example)  <br>PWD=$(aws secretsmanager get-secret-value --secret-id aem/prod/password --query SecretString --output text)  </pre><p><strong>Enforce SSL Validation</strong>:<br>Replace curl -k (insecure) with a trusted CA certificate:</p><pre>curl --cacert /path/to/ca-bundle.crt -u &quot;$USR&quot;:&quot;$PWD&quot; ...</pre><h4>4.4 Adding Post-Build Actions</h4><p>Extend the script to trigger downstream processes after a successful download:</p><pre># Example: Upload to cloud storage  <br>aws s3 cp &quot;$BK_FOLDER/$BK_FILE&quot; s3://my-backup-bucket/  <br><br># Example: Validate package integrity  <br>CHECKSUM=$(sha256sum &quot;$BK_FOLDER/$BK_FILE&quot; | cut -d &#39; &#39; -f 1)  <br>_log &quot;SHA-256 checksum: $CHECKSUM&quot;  <br><br># Example: Clean up old backups (retain last 7 days)  <br>find &quot;$BK_FOLDER&quot; -name &quot;*.zip&quot; -mtime +7 -exec rm {} \;  </pre><h4>4.5 Adding Notification Alerts</h4><p>Notify teams of success/failure via Slack, email, or monitoring tools:</p><pre># Post to Slack on failure  <br>curl -X POST -H &#39;Content-type: application/json&#39; \  <br>--data &quot;{\&quot;text\&quot;:\&quot;🚨 AEM backup failed: $(hostname)\&quot;}&quot; \  <br>https://hooks.slack.com/services/YOUR/WEBHOOK/URL  <br><br># Send email via sendmail  <br>if [ $? -ne 0 ]; then  <br>  echo &quot;Subject: Backup Failed&quot; | sendmail admin@mycompany.com  <br>fi  </pre><h3>5. Conclusion</h3><p>Managing AEM packages doesn’t have to be a manual, error-prone chore. With the create-remote-aem-pkg.sh script, you can transform package creation, filtering, and distribution into a streamlined, repeatable process. This tool isn’t just about saving time, it’s about enabling consistency, reliability, and scalability in your AEM operations.</p><h4>Key Takeaways</h4><ol><li><strong>Automation Wins</strong>: By eliminating repetitive GUI interactions, the script reduces human error and frees teams to focus on higher-value tasks.</li><li><strong>Flexibility Matters</strong>: Whether backing up critical content, syncing environments, or preparing for updates, the script adapts to diverse use cases with minimal tweaking.</li><li><strong>Resilience is Key</strong>: Built-in logging, error checks, and security considerations ensure the script behaves predictably, even when things go sideways.</li></ol><p>Great tools are born from real-world challenges. This script is a starting point, think of it as a foundation to build upon as your team’s needs grow. Whether you’re a solo developer or part of a large DevOps team, automation like this exemplifies how small investments in code can yield outsized returns in productivity and peace of mind.</p><p><strong>Ready to take the next step?</strong></p><ul><li>🛠️ <strong>Customize</strong>: Tailor the script using <a href="https://chat.deepseek.com/a/chat/s/4bad1785-c64b-479a-abb5-a39892036c6c#">Section 6</a> as your guide.</li><li>🔍 <strong>Audit</strong>: Review your existing AEM workflows for automation opportunities.</li><li>🤝 <strong>Share</strong>: Mentor your team or write a blog post about your modifications.</li></ul><p>Thank you for following along — now go forth and automate! 🚀</p><h3>Appendix</h3><h4>Complete Code</h4><pre>#!/bin/bash<br>set -eo pipefail<br><br># The script will create a package thought the package manager api:<br># - The package is created, if not already present<br># - Package filters are populated accordingly to specified paths<br># - Package is builded<br># - Package is download to the specified folder<br><br>_log () {<br>  echo &quot;[$(date +%Y.%m.%d-%H:%M:%S)] $1&quot;<br>}<br><br>check_last_exec () {<br>    local message=&quot;$1&quot;<br>    local output=&quot;$2&quot;<br>    local status=$3<br><br>    if [ &quot;$status&quot; -ne 0 ]; then<br>        echo &amp;&amp; echo &quot;$message&quot; &amp;&amp; echo<br>        exit 1<br>    fi<br><br>    if [[ $output =~ .*success\&quot;:false* ]] || [[ $output =~ .*&quot;HTTP ERROR&quot;* ]]; then<br>        _log &quot;$message&quot;<br>        exit 1<br>    fi<br>}<br><br>USR=&quot;$1&quot;<br>PWD=&quot;$2&quot;<br>SVR=&quot;$3&quot;<br>PORT=&quot;$4&quot;<br>PKG_GROUP=&quot;$5&quot;<br>PKG_NAME=&quot;$6&quot;<br>BK_FOLDER=&quot;$7&quot;<br><br>shift 7<br># The following paths will be included in the package<br>FILTERS=($@)<br>BK_FILE=$PKG_NAME&quot;-&quot;$(date +%Y%m%d-%H%M%S).zip<br><br>_log &quot;Starting backup process...&quot;<br>echo &quot;AEM instance: &#39;$SVR&#39;:&#39;$PORT&#39;<br>AEM User: &#39;$USR&#39;<br>Package group: $PKG_GROUP<br>Package name: &#39;$PKG_NAME&#39;<br>Destination folder: $BK_FOLDER<br>Destination file: &#39;$BK_FILE&#39;<br>Filter paths: &quot;<br>printf &#39;\t%s\n\n&#39; &quot;${FILTERS[@]}&quot;<br><br>if [ ! -d &quot;$BK_FOLDER&quot; ]; then<br>  _log &quot;Backup folder &#39;$BK_FOLDER&#39; does not exist!&quot; &amp;&amp; echo<br>  exit 1<br>fi<br><br>PKG_NAME=${PKG_NAME// /_}<br>check_last_exec &quot;Error replacing white space chars from package name!&quot; &quot;&quot; $? || exit 1<br>_log &quot;Removed whitespaces from package name: &#39;$PKG_NAME&#39;&quot;<br>BK_FILE=$PKG_NAME.zip<br>_log &quot;Backup file: &#39;$BK_FILE&#39;&quot;<br><br>_log &quot;Creating the package...&quot;<br>if [ $(curl -k -u &quot;$USR&quot;:&quot;$PWD&quot; &quot;$SVR:$PORT/crx/packmgr/service.jsp?cmd=ls&quot; 2&gt;/dev/null | grep &quot;$PKG_NAME.zip&quot; | wc -l) -eq 1 ]; then<br>  _log &quot; Package &#39;$PKG_GROUP/$PKG_NAME&#39; is already present: skipping creation.&quot;<br>else<br>  curl -k --silent -u &quot;$USR&quot;:&quot;$PWD&quot; -X POST \<br>  &quot;$SVR:$PORT/crx/packmgr/service/.json/etc/packages/$PKG_GROUP/$PKG_NAME?cmd=create&quot; \<br>  -d packageName=&quot;$PKG_NAME&quot; -d groupName=&quot;$PKG_GROUP&quot;<br><br>  check_last_exec &quot;  Error creating the package!&quot; &quot;&quot; $?<br>  _log &quot; Package created&quot;<br>fi<br><br># create filters variable<br>FILTERS_PARAM=&quot;&quot;<br>ARR_LEN=&quot;${#FILTERS[@]}&quot;<br>for i in &quot;${!FILTERS[@]}&quot;; do<br><br>  FILTERS_PARAM=$FILTERS_PARAM&quot;{\&quot;root\&quot;: \&quot;${FILTERS[$i]}\&quot;, \&quot;rules\&quot;: []}&quot;<br><br>  T=$((i+1))<br>  if [ $T -ne $ARR_LEN ]; then<br>   FILTERS_PARAM=$FILTERS_PARAM&quot;, &quot;<br>  fi<br>done<br><br># add filters<br>_log &quot;Adding filters to the package...&quot;<br>CURL_OUTPUT=$(curl -k --silent -u &quot;$USR&quot;:&quot;$PWD&quot; -X POST &quot;$SVR:$PORT/crx/packmgr/update.jsp&quot; \<br>-F path=/etc/packages/&quot;$PKG_GROUP&quot;/&quot;$PKG_NAME&quot;.zip -F packageName=&quot;$PKG_NAME&quot; \<br>-F groupName=&quot;$PKG_GROUP&quot; \<br>-F filter=&quot;[$FILTERS_PARAM]&quot; \<br>-F &quot;_charset_=UTF-8&quot;)<br><br>CURL_STATUS=$?<br><br># Pass the status to the check_last_exec function<br>check_last_exec &quot;Error adding filters to the package!&quot; &quot;$CURL_OUTPUT&quot; $CURL_STATUS<br>_log &quot;  Package filters updated successfully.&quot;<br><br># build package<br>_log &quot;Building the package...&quot;<br>CURL_OUTPUT=$(curl -k -u &quot;$USR&quot;:&quot;$PWD&quot; -X POST \<br>  &quot;$SVR:$PORT/crx/packmgr/service/script.html/etc/packages/$PKG_GROUP/$PKG_NAME.zip&quot; \<br>  -F &quot;cmd=build&quot;)<br><br>check_last_exec &quot; Error building the package!&quot; &quot;$CURL_OUTPUT&quot; $?<br>_log &quot;  Package built.&quot;<br><br># download package<br>_log &quot;Downloading the package...&quot;<br>if [ &quot;$(curl -w &quot;%{http_code}&quot; -o &quot;$BK_FOLDER/$BK_FILE&quot; -k --silent -u &quot;$USR&quot;:&quot;$PWD&quot; &quot;$SVR:$PORT/etc/packages/$PKG_GROUP/$PKG_NAME.zip&quot;)&quot; -eq &quot;200&quot; ]; then<br>  if [ -f &quot;$BK_FOLDER/$BK_FILE&quot; ] &amp;&amp; [ -s &quot;$BK_FOLDER/$BK_FILE&quot; ]; then<br>    _log &quot;  Package $BK_FILE downloaded in $BK_FOLDER.&quot;<br>    exit 0<br>  fi<br>fi<br><br>_log &quot;  Error downloading the package!&quot;<br>exit 1</pre><h4>References</h4><p>[¹] Skipping SSL verification with curl -k is handy for testing, but you’ll want something sturdier in production (for example --cacert)!</p><p>[²] <a href="https://experienceleague.adobe.com/docs/experience-manager-65/administering/contentmanagement/package-manager.html">AEM Package Manager Official Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08279517e042" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVND: The Key to Faster Maven Builds]]></title>
            <link>https://medium.com/@giuseppebaglio/mvnd-the-key-to-faster-maven-builds-11e50f65f270?source=rss-7f5958c1a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/11e50f65f270</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Giuseppe Baglio]]></dc:creator>
            <pubDate>Mon, 20 Jan 2025 09:09:49 GMT</pubDate>
            <atom:updated>2025-01-23T14:59:31.742Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4na-HIVbXnV1Af4NWWfGug.jpeg" /><figcaption>Developer on the fast track to productivity</figcaption></figure><p>If you’ve ever found yourself drumming your fingers on your desk, waiting for a <strong>Maven build</strong> to complete, you’re not alone. <strong>Build times</strong> can be a significant bottleneck in development workflows, especially for <em>large projects</em>. <strong>MVND</strong>, the <strong>Maven Daemon</strong>, is a game-changing tool that’s set to revolutionize your build process.</p><p>The Maven Daemon is an initiative by the <strong>Apache Maven team</strong>. At its core, MVND is designed to do one thing: make your <strong>Maven builds faster</strong>. By keeping a <strong>JVM warm</strong> and reusing it across builds, MVND eliminates the overhead of starting up a new <strong>JVM</strong> for each build, resulting in <em>significant time savings</em>.</p><p>But <em>speed</em> isn’t the only trick up MVND’s sleeve. It brings other <em>benefits</em> to the table:</p><ul><li>Lightning-fast startup times</li><li>Smart caching mechanisms</li><li>Parallel project-building capabilities</li><li>Reduced memory footprint</li></ul><p>I won’t bore you with <em>installation manuals</em> or <em>configuration minutiae</em> in this article, as the <a href="https://github.com/apache/maven-mvnd?tab=readme-ov-file#how-to-install-mvnd">official documentation</a> does an excellent job of covering those details. Instead, we’ll focus on <em>real-world examples</em> to see MVND in action. We’ll measure its performance, compare it to traditional builds, and showcase how it truly shines. Whether you’re working on a <em>small, straightforward project</em> or a <em>large, intricate multi-module system</em>, by the end of this article, you’ll see why MVND is an essential addition to your <em>development workflow</em>.</p><h3>Real-World Performance: Maven vs. MVND Build Times</h3><p>To truly understand the impact of MVND, let’s look at some real-world build times from two different projects. The data below compares the performance of <strong>MVND</strong> and traditional <strong>Maven</strong> builds, showcasing its tangible benefits.</p><h4>Case Study 1: A Simple Project</h4><p>For our first example, we use the Adobe AEM archetype repository², a standard multi-module project that serves as a de facto template for initializing AEM projects. This project is known for its quick build times, making it an excellent candidate for observing MVND&#39;s impact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eX-9A_apTISs-RBTpAFbgA.png" /><figcaption>Simple Project — mvn (left) vs mvnd (right) build time</figcaption></figure><ul><li><strong>Maven Build Time:</strong> 34.669 seconds</li><li><strong>MVND Build Time:</strong> 20.816 seconds</li></ul><p>MVND reduces the build time by approximately <strong>40%</strong>, saving over 11 seconds. While some individual modules may show slightly longer build times with MVND, the overall efficiency gain is undeniable. This improvement is attributed to the MVND&#39;s ability to handle parallelism more effectively, optimizing the build process.</p><h4>Case Study 2: A Complex Project</h4><p>Our second example is a complex, real-world project from one of my client’s production environments. This project, built using the AEM archetype, includes numerous unit tests for core (Java) and UI frontend (Node.js) code, with 697 Java tests and 799 Node.js tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-a99M2-NFkqW7wTGIMAkw.png" /><figcaption>Complex Project — mvn (left) vs mvnd (right) build time</figcaption></figure><ul><li><strong>Maven Build Time:</strong> 02:52 minutes</li><li><strong>MVND Build Time:</strong> 01:41 minutes</li></ul><p>MVND showcases an impressive <strong>41%</strong> reduction in build time, saving 71 seconds. Despite some modules taking slightly longer with MVND, the overall build time improvement is substantial. This suggests that MVND optimization strategies are particularly beneficial also in complex, multi-module projects.</p><h3>Conclusion</h3><p>By reusing <strong>JVM instances</strong> and optimizing <em>parallel execution</em>, MVND offers significant<em> time savings</em> across projects of all sizes. Whether working on a simple prototype or a complex enterprise application, MVND can <em>streamline your build process</em>, allowing you to focus on <em>what matters most</em>.</p><p>MVND stands out for three key reasons:</p><ul><li><strong>Faster Build Times:</strong> The examples above demonstrate a <strong>~40% improvement</strong> in build times with MVND. While the exact gains may vary depending on your project’s size and complexity, you can expect <strong>consistent performance improvements</strong> across a wide range of projects, making MVND a reliable choice for speeding up your builds.</li><li><strong>Ease of Adoption:</strong> As a drop-in replacement for Maven by design, MVND requires minimal changes to your existing setup, making it effortless to integrate into your workflow.</li><li><strong>Credibility:</strong> Backed by the Apache Maven team, MVND is a reliable and well-supported tool that aligns with industry standards.</li></ul><h3>Final Thoughts</h3><p>In a world where every second counts, <strong>MVND</strong> emerges as a game-changer for developers, empowering them to build faster, smarter, and more efficiently. With its proven ability to slash build times by up to <strong>40%</strong>, MVND is a no-brainer for anyone looking to optimize their workflow and boost productivity.</p><p>But don’t just take my word for it — <strong>experience the difference yourself</strong>. Give MVND a try in your projects and witness firsthand how it transforms your build process. Whether you’re working on a small prototype or a large-scale enterprise application, MVND is the tool that helps you focus on what truly matters: delivering high-quality software, faster.</p><p>[¹] <a href="https://github.com/apache/maven-mvnd">https://github.com/apache/maven-mvnd</a></p><p>[²] <a href="https://github.com/adobe/aem-project-archetype">https://github.com/adobe/aem-project-archetype</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11e50f65f270" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplify AEM Configuration Serialization]]></title>
            <link>https://medium.com/@giuseppebaglio/simplify-aem-configuration-serialization-0eec28aeb1cb?source=rss-7f5958c1a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/0eec28aeb1cb</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[code-improvement]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Giuseppe Baglio]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 11:04:03 GMT</pubDate>
            <atom:updated>2025-01-23T14:48:50.305Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*QHiRglwcG_lCHMsmFBZfhQ.jpeg" /><figcaption>Finally, time for coffee breaks!</figcaption></figure><h3>Introduction</h3><p>Managing Context-Aware Configurations¹ serialization in Adobe Experience Manager (AEM) can be a nightmare. From handling nested² Context-Aware Configurations to writing repetitive boilerplate code, developers often find themselves bogged down by complexity.</p><p>Today, we’ll explore a smart solution that simplifies this process: the <strong>GenericConfigSerializer</strong>. This custom Jackson serializer provides a powerful, flexible approach to serializing <strong>Context-Aware Configurations</strong> with minimal <strong>boilerplate code</strong>, making it easier to <strong>maintain</strong> and <strong>scale</strong> your AEM applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1KtRzEc9L6VbVpvB9I3ZuQ.jpeg" /><figcaption>Relaxed fellow programmer after using code from this article</figcaption></figure><h3>Understanding the Serialization Challenge</h3><p>In AEM, Context-Aware Configurations (CAC) provide a flexible way to manage settings across different contexts, such as environments, languages, or regions. However, serializing these configurations can be a daunting task. <strong>Traditional serialization methods</strong> often fall short in three key areas:</p><ul><li><strong>Manual mapping madness </strong>😵‍💫: They require manual mapping of configuration properties, which can lead to tedious, error-prone code that’s hard to maintain.</li><li><strong>Nested complexity </strong>🕸️: They struggle to handle complex, nested configuration hierarchies, making it difficult to serialize and deserialize configurations accurately. Refer to the Perficient blog post for a detailed explanation of nested Context-Aware Configurations in AEM².</li><li><strong>Verbose code </strong>📜: They create verbose and repetitive serialization code that clutters your codebase and makes it harder to focus on the logic that matters.</li></ul><h3><strong>Introducing the </strong>GenericConfigSerializer</h3><p>The <strong>GenericConfigSerializer</strong> is a generic <strong>Jackson serializer</strong> designed to automatically handle the <strong>serialization of Context-Aware Configurations</strong> (CAC) objects.</p><p>For more information on Sling Model exporters, see the Adobe Experience League documentation³ and the Apache Sling documentation⁴.</p><p>Here’s how the serializer works under the hood:</p><ul><li>A generic serializer class that extends Jackson’s StdSerializer class</li><li>A set of methods that handle the serialization of different data types, such as simple properties, arrays, and nested proxy objects</li></ul><p>The serializer’s code is as follows:</p><pre>import com.fasterxml.jackson.annotation.JsonIgnore;<br>import com.fasterxml.jackson.annotation.JsonProperty;<br>import com.fasterxml.jackson.core.JsonGenerator;<br>import com.fasterxml.jackson.databind.SerializerProvider;<br>import com.fasterxml.jackson.databind.ser.std.StdSerializer;<br>import lombok.extern.slf4j.Slf4j;<br><br>import java.io.IOException;<br>import java.lang.reflect.InvocationTargetException;<br>import java.lang.reflect.Method;<br>import java.util.Arrays;<br>import java.util.List;<br>import java.util.stream.Collectors;<br><br>/**<br> * A generic serializer for configuration objects.<br> *<br> * &lt;p&gt;This serializer handles the serialization of Context-Aware Configurations<br> * objects by iterating over their methods and serializing the properties <br> * accordingly.<br> * It supports serialization of arrays and proxy objects.&lt;/p&gt;<br> *<br> * @param &lt;T&gt; the type of the configuration object<br> */<br>@Slf4j<br>public class GenericConfigSerializer&lt;T&gt; extends StdSerializer&lt;T&gt; {<br><br> public GenericConfigSerializer() {<br>  this(null);<br> }<br><br> /**<br>  * Constructor with class type.<br>  *<br>  * @param t the class type of the object to serialize<br>  */<br> public GenericConfigSerializer(Class&lt;T&gt; t) {<br>  super(t);<br> }<br><br> /**<br>  * Serializes the given value.<br>  *<br>  * @param value    the value to serialize<br>  * @param gen      the JSON generator<br>  * @param provider the serializer provider<br>  * @throws IOException if an I/O error occurs<br>  */<br> @Override<br> public void serialize(T value, JsonGenerator gen, SerializerProvider provider) {<br>  try {<br>   gen.writeStartObject();<br>   for (Method method : getConfigPropertyMethods(value)) {<br>    serializeMethod(value, gen, provider, method);<br>   }<br>   gen.writeEndObject();<br>  } catch (IOException e) {<br>   log.error(&quot;Impossible to serialize value: {}&quot;, value, e);<br>  }<br> }<br><br> /**<br>  * Retrieves the configuration property methods.<br>  *<br>  * @param value the configuration object<br>  * @return a list of configuration property methods<br>  */<br> private List&lt;Method&gt; getConfigPropertyMethods(T value) {<br>  return Arrays.stream(value.getClass().getInterfaces()[0].getDeclaredMethods())<br>   .filter(this::isConfigPropertyMethod).filter(this::isNotIgnoredPropertyMethod)<br>   .collect(Collectors.toList());<br> }<br><br> /**<br>  * Serializes a single method.<br>  *<br>  * @param value    the configuration object<br>  * @param gen      the JSON generator<br>  * @param provider the serializer provider<br>  * @param method   the method to serialize<br>  * @throws IOException if an I/O error occurs<br>  */<br> private void serializeMethod(T value, JsonGenerator gen, SerializerProvider provider, Method method) {<br>  try {<br>   Object returnValue = method.invoke(value);<br>   if (returnValue != null) {<br>    String fieldName = getJsonPropertyName(method);<br>    serializeField(gen, provider, fieldName, returnValue);<br>   }<br>  } catch (InvocationTargetException | IllegalAccessException e) {<br>   log.error(&quot;Impossible to serialize method {} (value: {})&quot;, method, value, e);<br>  }<br> }<br><br> /**<br>  * Serializes a field.<br>  *<br>  * @param gen         the JSON generator<br>  * @param provider    the serializer provider<br>  * @param fieldName   the name of the field<br>  * @param returnValue the value of the field<br>  * @throws IOException if an I/O error occurs<br>  */<br> private void serializeField(JsonGenerator gen, SerializerProvider provider, String fieldName, Object returnValue) {<br>  try {<br>   if (returnValue.getClass().isArray()) {<br>    serializeArray(gen, provider, fieldName, (Object[]) returnValue);<br>   } else if (returnValue.getClass().getName().contains(&quot;com.sun.proxy&quot;)) {<br>    gen.writeFieldName(fieldName);<br>    serialize((T) returnValue, gen, provider);<br>   } else {<br>    gen.writeObjectField(fieldName, returnValue);<br>   }<br>  } catch (IOException e) {<br>   log.error(&quot;Impossible to serialize value: {}; fieldName: {}&quot;, returnValue, fieldName, e);<br>  }<br> }<br><br> /**<br>  * Serializes an array field.<br>  *<br>  * @param gen       the JSON generator<br>  * @param provider  the serializer provider<br>  * @param fieldName the name of the field<br>  * @param array     the array to serialize<br>  * @throws IOException if an I/O error occurs<br>  */<br> private void serializeArray(JsonGenerator gen, SerializerProvider provider, String fieldName, Object[] array) {<br>  try {<br>   gen.writeArrayFieldStart(fieldName);<br>   for (Object item : array) {<br>    if (item.getClass().getName().contains(&quot;com.sun.proxy&quot;)) {<br>     serialize((T) item, gen, provider);<br>    } else {<br>     gen.writeObject(item);<br>    }<br>   }<br>   gen.writeEndArray();<br>  } catch (IOException e) {<br>   log.error(&quot;Impossible to serialize array: {}; fieldName: {}&quot;, array, fieldName, e);<br>  }<br> }<br><br> /**<br>  * Determines if a method is a configuration property method.<br>  *<br>  * @param method the method to check<br>  * @return true if the method is a configuration property method, false otherwise<br>  */<br> private boolean isConfigPropertyMethod(Method method) {<br>  // Filter out methods that are not configuration properties<br>  return method.getParameterCount() == 0 &amp;&amp; method.getReturnType() != void.class &amp;&amp;<br>   !method.getName().equals(&quot;annotationType&quot;) &amp;&amp;<br>   !method.getName().equals(&quot;hashCode&quot;);<br> }<br><br> /**<br>  * Determines if a method is ignored based on the @JsonIgnore annotation.<br>  *<br>  * @param method the method to check<br>  * @return true if the method is ignored, false otherwise<br>  */<br> private boolean isNotIgnoredPropertyMethod(Method method) {<br>  return method.getAnnotation(JsonIgnore.class) == null;<br> }<br><br> /**<br>  * Gets the JSON property name from the @JsonProperty annotation if present.<br>  *<br>  * @param method the method to check<br>  * @return the JSON property name<br>  */<br> private String getJsonPropertyName(Method method) {<br>  JsonProperty jsonProperty = method.getAnnotation(JsonProperty.class);<br>  if (jsonProperty != null &amp;&amp; !jsonProperty.value().isEmpty()) {<br>   return jsonProperty.value();<br>  }<br>  return method.getName();<br> }<br>}</pre><h3>Illustrating the serializer with a Product Catalog Configuration</h3><p>This example will illustrate using the GenericConfigSerializer with a <strong>fictional</strong> product catalogue <strong>configuration</strong>. It demonstrates how the serializer can simplify the serialization of complex configurations.</p><pre>@JsonSerialize(using = GenericConfigSerializer.class)<br>@Configuration(label = &quot;Product Catalog Settings&quot;)<br>public @interface ProductCatalogConfig {<br>    @Property(label = &quot;Enable Personalization&quot;, description = &quot;Toggle personalized product recommendations&quot;)<br>    @JsonIgnore<br>    boolean enablePersonalization();<br><br>    @Property(label = &quot;Default Currency&quot;, description = &quot;Standard currency for product pricing&quot;)<br>    String defaultCurrency();<br><br>    @Property(label = &quot;Inventory Threshold&quot;, description = &quot;Low stock warning level&quot;)<br>    int lowStockThreshold();<br><br>    @Property(label = &quot;Shipping Configurations&quot;)<br>    ShippingConfig shippingConfig();<br>}<br><br>@Configuration(label = &quot;Shipping Configuration&quot;)<br>public @interface ShippingConfig {<br>    @Property(label = &quot;Free Shipping Minimum&quot;)<br>    @JsonProperty(&quot;minFreeShipping&quot;)<br>    double freeShippingMinimum();<br><br>    @Property(label = &quot;Supported Shipping Regions&quot;)<br>    String[] supportedRegions();<br><br>    @Property(label = &quot;Express Shipping Enabled&quot;)<br>    boolean expressShippingEnabled();<br>}</pre><p>Class ShippingConfig could have been written to have nested complex classes at <strong>multiple levels</strong> of depth, allowing for a more intricate and hierarchical structure. However, for the <strong>sake of exposition</strong>, I am keeping it relatively simple with only one level of depth to focus on illustrating the concept of using the GenericConfigSerializer.</p><p>As shown in the code above, only the ProductCatalogConfig class has been annotated with @JsonSerialize, which instructs the out-of-the-box AEM Jackson serialization to leverage the GenericConfigSerializer to serialize the object.</p><p>When serialized, the configuration might look like:</p><pre>{<br>    &quot;defaultCurrency&quot;: &quot;USD&quot;,<br>    &quot;lowStockThreshold&quot;: 10,<br>    &quot;shippingConfig&quot;: {<br>        &quot;minFreeShipping&quot;: 50.00,<br>        &quot;supportedRegions&quot;: [&quot;US&quot;, &quot;CA&quot;, &quot;UK&quot;],<br>        &quot;expressShippingEnabled&quot;: true<br>    }<br>}</pre><p>The <strong>GenericConfigSerializer</strong> leverages reflection⁵ techniques to transform configuration serialization. By analyzing interface methods, it identifies and processes the configuration properties with precision and flexibility.</p><p>The serialization <strong>automatically</strong> excludes methods with parameters and ignores standard Java object methods like hashCode(), ensuring only <strong>relevant getter</strong> methods are serialized.</p><p>Annotation-based customization provides developers with granular control. The @JsonIgnore annotation allows selective method exclusion while @JsonProperty enabling custom property naming. This flexibility ensures the serializer adapts to complex configuration structures without compromising code clarity.</p><h4>How to serialize Product Catalog in Sling Models</h4><p>Exposing Context-Aware Configurations (CAC) in <strong>Sling Models</strong> often involves tedious, manual property mapping. Developers would typically write <strong>repetitive</strong> code to extract and map each configuration attribute <strong>individually</strong>, leading to verbose and maintenance-heavy implementations.</p><p>Let’s take as an example the following Sling Model:</p><pre>@Model(adaptables = SlingHttpServletRequest.class)<br>@Exporter(name = ExporterConstants.SLING_MODEL_EXPORTER_NAME, <br>          extensions = ExporterConstants.SLING_MODEL_EXTENSION)<br>public class ProductPageModel {<br>    private String defaultCurrency;<br>    private boolean personalizationEnabled;<br>    private int lowStockThreshold;<br>    private double freeShippingMinimum;<br>    private String[] supportedRegions;<br><br>    @PostConstruct<br>    public void init() {<br>        ProductCatalogConfig config = getCAConfig(resource)<br>            .orElse(null);<br>        <br>        if (config != null) {<br>            this.defaultCurrency = config.defaultCurrency();<br>            this.personalizationEnabled = config.enablePersonalization();<br>            this.lowStockThreshold = config.lowStockThreshold();<br><br>            // Nested configuration handling<br>            ShippingConfig shippingConfig = config.shippingConfig();<br>            if (shippingConfig != null) {<br>                this.freeShippingMinimum = shippingConfig.freeShippingMinimum();<br>                this.supportedRegions = shippingConfig.supportedRegions();<br>            }<br>        }<br>    }<br><br>    // Getter methods for each property<br>    public String getDefaultCurrency() { return defaultCurrency; }<br>    public boolean isPersonalizationEnabled() { return personalizationEnabled; }<br>    public int getLowStockThreshold() { return lowStockThreshold; }<br>    public double getFreeShippingMinimum() { return freeShippingMinimum; }<br>    public String[] getSupportedRegions() { return supportedRegions; <br><br>    private ProductCatalogConfig getCAConfig(Resource resource) {<br>      if (resource == null) {<br>          return null;<br>      }<br>  <br>      ConfigurationBuilder configBuilder = resource.adaptTo(ConfigurationBuilder.class);<br>      if (configBuilder == null) {<br>        return null;<br>      }<br><br>      return configBuilder.as(ProductCatalogConfig.class);<br>    }<br>}</pre><p>Looking at this code, you’ll notice how each field from the Product Catalog Configuration must be manually mapped to local class fields within the init method. This one-to-one mapping approach quickly becomes unsustainable as configurations grow in complexity. As your Product Catalog Configuration expands to include more fields and nested structures, the mapping code grows proportionally, leading to:</p><ul><li>Redundant boilerplate that obscures the actual business logic</li><li>Time-consuming updates when configuration structures change</li><li>Higher risk of mapping errors during implementation</li><li>Increased cognitive load when reading and maintaining the code</li></ul><p>The resulting JSON export might look like:</p><pre>{<br>  &quot;defaultCurrency&quot;: &quot;USD&quot;,<br>  &quot;enablePersonalization&quot;: true,<br>  &quot;lowStockThreshold&quot;: 10,<br>  &quot;shippingConfig&quot;: {<br>      &quot;freeShippingMinimum&quot;: 50.00,<br>      &quot;supportedRegions&quot;: [&quot;US&quot;, &quot;CA&quot;, &quot;UK&quot;],<br>      &quot;expressShippingEnabled&quot;: true<br>  }<br>}      <br></pre><p>With the GenericConfigSerializer, we can simplify the model in a few lines:</p><pre>@Model(adaptables = SlingHttpServletRequest.class)<br>@Exporter(name = ExporterConstants.SLING_MODEL_EXPORTER_NAME, <br>          extensions = ExporterConstants.SLING_MODEL_EXTENSION)<br>public class ProductPageModel {<br>    private ProductCatalogConfig productConfig;<br><br>    @PostConstruct<br>    public void init() {<br>        this.productConfig = getCAConfig(resource);<br>    }<br><br>    private ProductCatalogConfig getCAConfig(Resource resource) {<br>      // same code as before<br>    }<br><br>    // Expose the entire configuration for automatic serialization<br>    public ProductCatalogConfig getProductConfig() {<br>        return productConfig;<br>    }<br>}</pre><p>The resulting JSON export might look like:</p><pre>{<br>    &quot;productConfig&quot;: {<br>        &quot;defaultCurrency&quot;: &quot;USD&quot;,<br>        &quot;enablePersonalization&quot;: true,<br>        &quot;lowStockThreshold&quot;: 10,<br>        &quot;shippingConfig&quot;: {<br>            &quot;freeShippingMinimum&quot;: 50.00,<br>            &quot;supportedRegions&quot;: [&quot;US&quot;, &quot;CA&quot;, &quot;UK&quot;],<br>            &quot;expressShippingEnabled&quot;: true<br>        }<br>    }<br>}</pre><p>Using the GenericConfigSerializer, developers can simplify their Sling Models, <strong>reduce boilerplate code</strong>, and <strong>improve maintainability</strong>. The serializer’s flexibility and customizability make it an ideal solution for handling complex configurations in AEM.</p><h4>Key Transformation Highlights</h4><p>The real power of GenericConfigSerializer becomes evident when we look at its transformative impact. By <strong>eliminating manual property mapping</strong>, the approach dramatically simplifies configuration handling. Developers can now rely on automatic serialization that effortlessly manages configurations without requiring explicit mapping for each attribute.</p><p>One of the most compelling benefits is how seamlessly it <strong>handles nested configurations</strong>. Complex, multi-layered configuration structures that once demanded intricate manual parsing are now <strong>easily</strong> processed. The serializer intelligently navigates through configuration hierarchies, <strong>reducing the cognitive load</strong> on developers.</p><h3>Conclusion</h3><p>The solution significantly reduces boilerplate code, transforming what was once a verbose implementation into concise, elegant code. This lean approach not only makes the code <strong>more readable</strong> but also more <strong>maintainable</strong>. Configuration management becomes far more flexible, allowing developers to modify and adapt configurations <strong>without</strong> getting entangled in <strong>complex serialization logic</strong>.</p><p>By leveraging the <strong>GenericConfigSerializer</strong>, developers can unlock a more efficient and streamlined AEM configuration management approach. With its ability to automatically serialize configurations, handle nested configurations, and eliminate manual property mapping, this solution is a game-changer for any AEM developer looking to <strong>simplify</strong> their workflow and <strong>improve</strong> their productivity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*AKODpdFNMUzIyAb3Q_FMcQ.jpeg" /></figure><p>Honestly, I created the GenericConfigSerializer for one reason: I’m lazy. I hate writing the same code repeatedly, and I’m sure I’m not the only one. But as I started using the serializer in my projects, I realized it could be a game-changer for everyone, not just me. So, I decided to share it with the community.</p><p>Whether you’re building a new AEM project or optimizing an existing one, the GenericConfigSerializer is valuable in your toolkit. Its flexibility and ease of use make it an ideal solution for developers of all levels, from beginners to seasoned experts. By adopting the GenericConfigSerializer, you can take your AEM development to the next level and deliver high-quality solutions faster and more efficiently.</p><p>Ready to simplify your AEM configuration serialization? Try the <strong>GenericConfigSerializer</strong> in your next project and experience the difference. Share your feedback in the comments below!</p><p>[¹] Apache Sling Context-Aware Configuration documentation: <a href="https://sling.apache.org/documentation/bundles/context-aware-configuration/context-aware-configuration.html">https://sling.apache.org/documentation/bundles/context-aware-configuration/context-aware-configuration.html</a></p><p>[²] As projects grow, configuration needs can become intricate, requiring nested configurations to handle multi-layered settings, as discussed in a <a href="https://blogs.perficient.com/2024/12/20/how-nested-context-aware-configuration-makes-complex-configuration-easy-in-aem/">blog post</a> by Perficient</p><p>[³] Adobe Experience League documentation: <a href="https://experienceleague.adobe.com/en/docs/experience-manager-learn/foundation/development/understand-sling-model-exporter">https://experienceleague.adobe.com/en/docs/experience-manager-learn/foundation/development/understand-sling-model-exporter</a></p><p>[⁴] Apache Sling Exporter Framework documentation: <a href="https://sling.apache.org/documentation/bundles/models.html#exporter-framework-1">https://sling.apache.org/documentation/bundles/models.html#exporter-framework-1</a></p><p>[⁵] Java Reflection API: <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/reflection/index.html">https://docs.oracle.com/javase/8/docs/technotes/guides/reflection/index.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0eec28aeb1cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating CDN Cache Invalidation in AEM]]></title>
            <link>https://medium.com/@giuseppebaglio/automating-cdn-cache-invalidation-in-aem-d419b538c8ea?source=rss-7f5958c1a602------2</link>
            <guid isPermaLink="false">https://medium.com/p/d419b538c8ea</guid>
            <category><![CDATA[akamai]]></category>
            <category><![CDATA[cdn]]></category>
            <category><![CDATA[cache-invalidation]]></category>
            <category><![CDATA[aem]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Giuseppe Baglio]]></dc:creator>
            <pubDate>Mon, 11 Dec 2023 17:23:17 GMT</pubDate>
            <atom:updated>2023-12-11T17:49:29.530Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*JufJTopoGkEGClKoWbK2zQ.jpeg" /></figure><p>Content Delivery Networks (CDNs) are commonly used with AEM to improve website performance by <strong>caching</strong> and <strong>serving content</strong> from edge locations closer to users. However, when AEM content changes it can lead to <strong>outdated copies</strong> in the<strong> CDN cache</strong>. Manual cache invalidation is complex and error-prone.</p><p>Though CDNs improved performance, our authors’ new changes weren’t reflected until caches expired. <strong>Clearing the cache manually</strong> post-publish did not scale. <strong>I could not find an existing out-of-the-box solution for this problem.</strong></p><figure><img alt="High-level AEM Architecture with caching" src="https://cdn-images-1.medium.com/max/948/1*AwpkIJMJGv6BnihHg8eUdg.png" /><figcaption>High-level AEM Architecture with caching</figcaption></figure><p>So I developed an <a href="https://github.com/realgpp/aem-cdn-cache-invalidator">open-source AEM library</a> that <strong>listens to publishing events</strong> and <strong>automatically triggers</strong> selective cache <strong>invalidation</strong> based on <strong>configurable rules</strong>.</p><p><a href="https://github.com/realgpp/aem-cdn-cache-invalidator">GitHub - realgpp/aem-cdn-cache-invalidator: AEM library that automatically invalidates cached CDN content when publishing updates. Supports flexible configuration, background processing, and extensibility. Provides APIs and extension points for custom integrations. Reduces manual CDN cache invalidation effort. Out-of-the-box Akamai integration.</a></p><p>The library <strong>reacts to</strong> AEM replication events or resource changes and then runs <strong>asynchronous background jobs</strong> to invalidate cached CDN content related to the published updates. <strong>Flexible APIs</strong> allow <strong>integration with</strong> various CDNs while <strong>extension points</strong> enable customization.</p><h3>The Problem</h3><p>CDNs cache website content like pages, images and JS/CSS assets. This avoids repeatedly serving <strong>static content</strong> from the AEM publish tier which <strong>improves response times</strong>. The CDN only re-fetches assets when they <strong>expire</strong> from the <strong>cache</strong> after a <strong>TTL (Time to Live)</strong>.</p><p>However, updated AEM content can get <strong>outdated copies</strong> lingering in the CDN after publishing. Some examples:</p><ul><li><strong>Publishing</strong> a new content page is not immediately <strong>visible</strong> to users. The older version remains cached.</li><li><strong>Updating</strong> a product image in DAM does not show until the CDN cache expires.</li></ul><p>Depending on the business context, any of these situations can be a really <strong>sensitive issue</strong> that needs to be addressed urgently<strong>. </strong>But sadly, <strong>clearing the cache manually</strong> on every publish is <strong>operationally complex</strong> and <strong>time-consuming</strong>:</p><ul><li>Identifying related URLs is manual and repetitive</li><li>Tedious cache tagging schemes to coordinate flushing</li></ul><p>An automated solution is needed… one that selectively and intelligently invalidates cache only for published updates.</p><h3>Automated Cache Invalidation</h3><p>Library “Automatic CDN Cache Invalidator for AEM” listens to publish events and resource changes, then triggers background cache invalidation per configurable rules. Flexible APIs allow integration with various CDNs.</p><p><a href="https://github.com/realgpp/aem-cdn-cache-invalidator">GitHub - realgpp/aem-cdn-cache-invalidator: AEM library that automatically invalidates cached CDN content when publishing updates. Supports flexible configuration, background processing, and extensibility. Provides APIs and extension points for custom integrations. Reduces manual CDN cache invalidation effort. Out-of-the-box Akamai integration.</a></p><h4>Key Capabilities</h4><ul><li><strong>Automatic triggering</strong>: Reacts to AEM replication events for publishing updates</li><li><strong>Selective invalidation: </strong>Invalidates cache only for specific published paths rather than mass flush</li><li><strong>Async processing: </strong>Uses queue-based jobs framework to offload CDN calls</li><li><strong>Configurable rules: </strong>Flush cache by URL, tag or custom criteria</li><li><strong>Logs:</strong> Detailed logging for tracking</li><li><strong>Akamai support built-in:</strong> Akamai Purge API is integrated</li><li><strong>Flexible CDN integrations: </strong>Easily extendable for other CDNs via APIs</li><li><strong>Extension APIs:</strong> Hooks to personalize behavior</li></ul><p>It solves manual cache management challenges allowing authors to focus on content while optimizing end-user experience.</p><p>Let’s walk through the flow…</p><h3>How it Works</h3><p>The application has configurable OSGi services and listeners for cache invalidation triggered by AEM events.</p><ol><li><strong>Event listening</strong>: Replication or resource change events signify content updates.</li><li><strong>Selective listener: </strong>An OSGi listener consumes events filtering to specific trees. It creates asynchronous jobs with updated paths.</li><li><strong>Background job:</strong> A separate job thread processes paths to extract cache-related metadata like URLs, tags etc.</li><li><strong>CDN API call: </strong>The job makes the API call to invalidate the cache for the computed metadata.</li><li><strong>Cache flush: </strong>The CDN receives the API request and flushes related cached content.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*QRzAOSYe-D0zXEV-em1YUg.jpeg" /><figcaption>Sequence diagram of solution.</figcaption></figure><p>The async approach avoids publish request performance impact. The CDN calls happen out-of-band without blocking AEM.</p><p>The entire flow is configurable via OSGi including supported events, cache criteria, URLs or logic.</p><p>Out-of-the-box integrations make it easy to get started while extension points allow customization. Let’s explore common configuration options…</p><h3>Purging content with Akamai API</h3><p>The project includes reusable services, listeners and jobs supporting caching scenarios like:</p><ul><li>Invalidating pages or assets by <strong>URL</strong></li><li>Website sections by <strong>tag</strong> or <strong>code</strong></li></ul><figure><img alt="Official Akamai Purge API summary" src="https://cdn-images-1.medium.com/max/1024/1*GAkv3qX9SR4JLxd2ruj2tw.png" /><figcaption>Akamai Purge APIs supported by the library</figcaption></figure><p>The following are the Akamai Purge APIs supported out of the box:</p><ul><li><a href="https://techdocs.akamai.com/purge-cache/reference/invalidate-tag">invalidation</a> and <a href="https://techdocs.akamai.com/purge-cache/reference/delete-tag">deletion</a> by Tag</li><li><a href="https://techdocs.akamai.com/purge-cache/reference/invalidate-cpcode">invalidation</a> and <a href="https://techdocs.akamai.com/purge-cache/reference/delete-cpcode">deletion</a> by CP Code</li><li><a href="https://techdocs.akamai.com/purge-cache/reference/invalidate-url">invalidation</a> and <a href="https://techdocs.akamai.com/purge-cache/reference/delete-url">deletion</a> by URL</li></ul><p>The following block, which you can find in the ui.config.example maven module, shows how to configure the Akamai service that comes with the library.</p><pre>// file com.baglio.autocdninvalidator.core.service.impl.AkamaiInvalidationServiceImpl.cfg.json<br>{<br>  &quot;isEnabled&quot;: true,<br>  &quot;configurationID&quot;: &quot;cdn-akamai&quot;,<br>  &quot;hostname&quot;: &quot;localhost:8443&quot;,<br>  &quot;getAkamaiClientToken&quot;: &quot;placeholder_akamai_client_token&quot;,<br>  &quot;getAkamaiAccessToken&quot;: &quot;placeholder_akamai_access_token&quot;,<br>  &quot;getAkamaiClientSecret&quot;: &quot;placeholder_akamai_client_secret&quot;,<br>  &quot;httpClientConfigurationID&quot;: &quot;http-client-akamai&quot;,<br>  &quot;purgeType&quot;: &quot;invalidate&quot;<br>}</pre><p>This service lets you choose how to purge content from the CDN: you can either invalidate or delete it. As you can see, you need to replace placeholders with your Akamai values.</p><p>You also need a dedicated HTTP Client Configuration to work with the Akamai APIs. After that, your service can be used by other sling jobs that handle content-change events.</p><p>Now let’s explore other configuration options that let you customize the library without coding…</p><h3>Configuration Areas</h3><p>The library offers a variety of configuration options to customize its functionality without code customizations. You can adjust these settings to suit your specific needs and preferences.</p><p>I want to keep this introduction brief and engaging but don’t worry if you have questions about the details. You can find more information in the README.md file of the project or in the Javadoc comments if you like to explore the code.</p><p>Key aspects to configure are:</p><ul><li><strong>Observed events: </strong>Replication topics or resource change events that trigger the invalidation jobs.</li></ul><pre>// file com.baglio.autocdninvalidator.core.listeners.ReplicationEventListener-website-generic.cfg.json<br>{<br>  &quot;isEnabled&quot;: true,<br>  &quot;resource.paths&quot;: [<br>    &quot;/content/we-retail&quot;,<br>    &quot;/content/wknd&quot;<br>  ],<br>  &quot;job.topic&quot;: &quot;com/baglio/autocdninvalidator/akamai/generic&quot;,<br>  &quot;filter.regex&quot;: &quot;^/content/(we-retail|wknd)(?!.*products)(?!.*adventures).*$&quot;<br>}</pre><pre>// file com.baglio.autocdninvalidator.core.listeners.DynamicResourceChangeListener-website-generic.cfg.json<br>{<br>  &quot;isEnabled&quot;: false,<br>  &quot;resource.change.types&quot;: [<br>    &quot;CHANGED&quot;<br>  ],<br>  &quot;resource.paths&quot;: [<br>    &quot;/content/we-retail&quot;,<br>    &quot;/content/wknd&quot;<br>  ],<br>  &quot;job.topic&quot;: &quot;com/baglio/autocdninvalidator/akamai/generic&quot;,<br>  &quot;filter.regex&quot;: &quot;^/content/(we-retail|wknd)(?!.*products)(?!.*adventures).*$&quot;<br>}</pre><ul><li><strong>CDN credentials: </strong>API credentials and settings for your provider.</li></ul><pre>// file com.baglio.autocdninvalidator.core.service.impl.AkamaiInvalidationServiceImpl.cfg.json<br>{<br>  &quot;isEnabled&quot;: true,<br>  &quot;configurationID&quot;: &quot;cdn-akamai&quot;,<br>  &quot;getAkamaiClientToken&quot;: &quot;placeholder_akamai_client_token&quot;,<br>  &quot;hostname&quot;: &quot;localhost:8443&quot;,<br>  &quot;getAkamaiAccessToken&quot;: &quot;placeholder_akamai_access_token&quot;,<br>  &quot;getAkamaiClientSecret&quot;: &quot;placeholder_akamai_client_secret&quot;,<br>  &quot;httpClientConfigurationID&quot;: &quot;http-client-akamai&quot;<br>}</pre><ul><li><strong>Invalidation rules: </strong>Filtering rules and cache flush criteria for each job consumer.</li></ul><pre>// file com.baglio.autocdninvalidator.core.jobs.EditorialAssetInvalidationJobConsumer.cfg.json<br>{<br>  &quot;isEnabled&quot;: true,<br>  &quot;job.topics&quot;: [<br>    &quot;com/baglio/autocdninvalidator/akamai/generic&quot;<br>  ],<br>  &quot;cdnConfigurationID&quot;: &quot;cdn-akamai&quot;,<br>  &quot;invalidation.type&quot;: &quot;tag&quot;,<br>  &quot;tagCodeMappings&quot;: [<br>    &quot;/content/we-retail/(..)(/.*)*=tag-dev-$1&quot;,<br>    &quot;/content/we-retail/(..)/.*/experience/.*=tag-dev-$1-experience&quot;,<br>    &quot;/content/wknd/(..)(/.*)*=tag-dev-$1&quot;,<br>    &quot;/content/wknd/(..)/.*/adventures/.*=tag-dev-$1-adventures&quot;<br>  ]<br>}</pre><ul><li><strong>Job topic tuning: </strong>Throttling and parallelization configs for each job topic. Please have a look at the section Custom Job Queue Configuration of project README file.</li></ul><p>These configurations determine how the library responds to AEM events, how many cache jobs run concurrently, and how the service communicates with your CDN provider to purge the cache.</p><p>Now that we have learned the basics, let’s move on to the fun part where we show you how to make the invalidation work on the AEM instance…</p><h3>Enabling Akamai CDN Integration</h3><p>If you want to use this library right away, you don’t need to write any code. Just follow these simple steps:</p><p><strong>Step 1</strong>: Install the ui.config.example module or create the <strong>OSGi config</strong> manually. The ui.config.example module is a sample configuration that provides a working example for <strong>Akamai integration</strong>. You can install it from the package manager or create the OSGi config manually through the web console.</p><p><strong>Step 2</strong>: Enter your Akamai <strong>credentials</strong> and <strong>settings</strong> in the <strong>AkamaiInvalidationServiceImpl config file</strong>. You must provide your Akamai hostname, client token, access token, and client secret in the AkamaiInvalidationServiceImpl config file. You can find these values in your Akamai portal.</p><p><strong>Step 3</strong>: Choose to <strong>listen for</strong> AEM events on Author or Publish.<br>Depending on your setup, you can choose to listen for AEM events on Author or Publish. If you choose Author, the module will detect <strong>publish events</strong> and <strong>invalidate</strong> the <strong>cache</strong> accordingly. If you choose Publish, the module will detect <strong>content updates</strong> and <strong>purge</strong> the <strong>cache</strong> accordingly.</p><p>Now let’s walk through adding support for a new custom CDN provider…</p><h3>Implementing a Custom CDN Provider</h3><p>Now that we’ve explored utilizing the library without coding, what if you encounter the need for a CDN provider that isn’t currently supported?</p><p>The library is designed for <strong>extension</strong> to support new CDN providers. You can easily extend it by following these steps:</p><ol><li>Create a Java class <strong>implementing</strong> the <strong>CdnInvalidationService</strong> <strong>interface</strong>. This interface defines the methods for <strong>purging</strong> the <strong>CDN cache</strong>.</li><li>Implement the logic for <strong>calling</strong> your CDN’s <strong>purge API</strong> in your implementation class.</li><li>Create an <strong>OSGi configuration</strong> for your class with the necessary <strong>credentials</strong> and property values. Make sure to give it a <strong>unique configuration ID</strong> so that it can be identified by the invalidation job.</li><li>Use the configuration ID mentioned above when you create <strong>invalidation job</strong> configurations.</li></ol><p>The library provides <strong>flexibility to customize </strong>the invalidation logic when using the built-in Akamai integration. If you need to <strong>tweak</strong> the <strong>preprocessing</strong> or <strong>postprocessing</strong>, the <em>AbstractInvalidationJob</em> class exposes <strong>hook methods</strong> you can <strong>override</strong> without having to reimplement the full Akamai handling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*OCc5VS-qB5p9yzPBPA5fpw.png" /><figcaption>Phases of job processing procedure.</figcaption></figure><p>With the procedure shown in the above image, you get the benefits of leveraging the existing Akamai capabilities while adapting things like:</p><p>- The <strong>preprocessInvalidationValues</strong> and <strong>postprocessInvalidationValues</strong> methods allow transforming the content paths and invalidation values before and after generating them.</p><p>- The <strong>preprocessPublicUrls</strong> and <strong>postprocessPublicUrls</strong> methods allow updating the public URLs before and after resolving them.</p><p>- The <strong>beforeInvalidation</strong> and <strong>afterInvalidation</strong> methods enable logic before and after making the CDN purge call.</p><p>By selectively overriding these hooks, you can adapt the data and flows to your needs while reusing the bulk of the Akamai integration code. This makes the library very extensible without having to start from scratch.</p><h3>Wrap Up</h3><p>And that’s a wrap! We’ve covered everything from <strong>out-of-the-box setup</strong> to <strong>fully custom integrations</strong> with this CDN invalidator library. I hope you found it an interesting read!</p><p>Did any part leave you scratching your head? Or maybe this library has already helped you invalidate caches more easily?</p><p>Either way, I’d love to hear your thoughts! Let me know what worked, what didn’t, or what other guides would help improve your CDN workflows.</p><p>Even better — I welcome <strong>pull requests</strong> if you have <strong>code changes</strong>, tweaks, or new snippets that can <strong>enhance</strong> this library and tutorial!</p><p>I greatly appreciate you taking the time to provide <strong>feedback</strong> and <strong>contributions</strong>. Your <strong>real-world experiences</strong> will help <strong>evolve</strong> this project and craft content that empowers fellow developers to <strong>master</strong> their <strong>CDN footprints</strong>.</p><p><a href="https://github.com/realgpp/aem-cdn-cache-invalidator">GitHub - realgpp/aem-cdn-cache-invalidator: AEM library that automatically invalidates cached CDN content when publishing updates. Supports flexible configuration, background processing, and extensibility. Provides APIs and extension points for custom integrations. Reduces manual CDN cache invalidation effort. Out-of-the-box Akamai integration.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d419b538c8ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>