Showing posts with label CRXDE. Show all posts
Showing posts with label CRXDE. Show all posts

May 28, 2021
Estimated Post Reading Time ~

Enabling CRXDE Lite in AEM

In order to ensure that AEM installations are as secure as possible, the security checklist recommends disabling WebDAV in production environments.

However, CRXDE Lite depends on the org.apache.sling.jcr.davex bundle to function properly, so disabling WebDAV will effectively disable CRXDE Lite as well.

When this happens, browsing to https://serveraddress:4502/crx/de/index.jsp will display an empty root node, and all HTTP requests to CRXDE Lite resources will fail:

404 Resource at '/crx/server/crx.default/jcr:root/.1.json' not found: No resource found

While this recommendation is intended to reduce attack surfaces as much as possible, system administrators might sometimes need access to CRXDE Lite in order to browse content or debug issues on production instances.

If disabled, you can turn CRXDE Lite on by following the below procedure:

  1. Go to the OSGi Components console at http://localhost:4502/system/console/components
  2. Search for the following component:
    1. org.apache.sling.jcr.davex.impl.servlets.SlingDavExServlet
  3. Click the wrench icon next to it in order to see its configuration options:


4. Create the following configuration:
  • Root path: /crx/server
  • Tick the box under Use absolute URIs.
5. When finished using CRXDE Lite, make sure you disable WebDAV again.

You can also enable CRXDE Lite via cURL, by running this command:

curl -u admin:admin -F "jcr:primaryType=sling:OsgiConfig" -F "alias=/crx/server" -F "dav.create-absolute-uri=true" -F "dav.create-absolute-uri@TypeHint=Boolean" http://localhost:4502/apps/system/config/org.apache.sling.jcr.davex.impl.servlets.SlingDavExServlet



By aem4beginner

January 3, 2021
Estimated Post Reading Time ~

AEM - Restricting CRXDE Access for few users

In AEM, CRXDE access can be disabled by
1. Disabling the required bundles
  • Adobe CRXDE Support (com.adobe.granite.crxde-support)
  • Adobe Granite CRX Explorer (com.adobe.granite.crx-explorer)
  • Adobe Granite CRXDE Lite (com.adobe.granite.crxde-lite)
2. From dispatcher https://helpx.adobe.com/experience-manager/kb/LimitAccessCRXandCRXDE.html

What if CRXDX needs to be disabled/restricted for a few users/groups.

One of the solutions could be to check the user when the user attempts to access CRXDE and block the access or re-route.

Step to Implement the above approach :
1. Create a Sling Filter to check the CRXDE access request.
2. Create an OSGi configuration and service to maintain restriction data(Users, groups, excluded user)
3. Create a clientlibs to re-route the user to another page while accessing CRXDE.

In the Sling Filter get the current user and check against service configuration and if found then replace/redirect one of the existing js to our custom clientlibs js.
Custom clientlibs will then take care of blocking CRXDE.

OSGi Configuration


Custom Clientlibs
Create a clientlibs with redirection code
window.location="/aem/start.html"

You can find the code at :
https://github.com/arunpatidar02/aem63app-repo/tree/master/java/crxde


By aem4beginner

December 29, 2020
Estimated Post Reading Time ~

How to easily access CRX/DE after AEM 6.5.5+ upgrade (SP5)

If you are on AEM 6.5 and have upgraded to Service Pack 5 (AEM version 6.5.5) you might have noticed that you can no longer log in to AEM via CRX/DE

This change was implemented in the SP5 update and according to the CSE that our team worked with:

“The login and logout buttons have been removed on purpose from CRXDE for security reasons (internal ID: GRANITE-27790). Backported to AEM 6.5.5.0 as part NPR-33521.”

The workaround that the CSE suggested was to navigate to:

https://<IP>:<PORT>/libs/granite/core/content/login.html

login and then navigate to /crx/de
You can take that workaround a step further and navigate to
https://<IP>:<PORT>/libs/granite/core/content/login.html?resource=crx/de

the added resource=/crx/de param here is just the AEM param for redirect after authentication. Basically, after you log in, you’ll be redirected to /crx/de

That only works on Author instances, for Publish instances, you have to navigate to the package manager:

https://<IP>:<PORT>/crx/packmgr/index.jsp

login, then navigate to /crx/de



By aem4beginner

December 28, 2020
Estimated Post Reading Time ~

How to revert deployed packages in CRX/DE package manager?

In this tutorial, you will learn how to revert a deployed package in CRX/DE package manager.

The package is uploaded into CRX/DE and not yet replicated.
  1. Visit CRX/DE Lite (http://localhost:4502/crx/packmgr/index.jsp)
  2. Locate the project package.
  3. Click on “more” (the drop-down on the right).
  4. Click on “uninstall” (this will ensure your AEM instance is back to what it was before the installation. Imagine all the “filter paths” have taken a backup snapshot. When uninstalling your package, this will bring your backup snapshot back to life, and delete anything in the folder that is not in the snapshot.)
  5. Delete the current version (unwanted version) of the project package.
  6. Done.
The package is uploaded into CRX/DE and has already been replicated.
  • Visit CRX/DE Lite (http://localhost:4502/crx/packmgr/index.jsp)
  • Locate the project package.
  • Click on “more” (the drop-down on the right).
  • Click on “uninstall” (this will ensure your AEM instance is back to what it was before the installation. Imagine all the “filter paths” have taken a backup snapshot. When uninstalling your package, this will bring your backup snapshot back to life, and delete anything in the folder that is not in the snapshot.)
  • Delete the current version (unwanted version) of the project package.
  • Repeat the above steps for all your AEM instances (Author and Publish AEM servers)
Note:
  • I insist not to replicate the /content folder that holds your site pages. This will replicate(copy) all your web pages to your publish instance. 
  • Even if your site manager indicates whether your page is not active, your page will be copied over to the publish instance and will available to your consumers.


By aem4beginner

May 27, 2020
Estimated Post Reading Time ~

How to Install/Add Bundles, Content Packages or Configurations at Runtime CRX in AEM

Install Bundles, Content Packages, or Configurations at Runtime If you want to install additional packages into the CRX, Create an install folder under the crx-quickstart.
Put your bundles, content packages, or configurations in the install folder. It will pick up while instance start and install into the CRX repository. Packages will install into CRX in the alphabetic order.

References:
AEM Documentation
Adobe Community

You can define additional bundles based on run modes for this you need to create an install.<run mode> folder.

for more information click here


By aem4beginner

May 20, 2020
Estimated Post Reading Time ~

Develop OSGi Bundle Using Adobe CRXDE Lite


It is often confusing as to how to set up an OSGi development environment for CQ5. In this post, I'll set what is to be coded aside, but focus on how to quickly and easily use CRXDE Lite (the web interface of CQ5) for
  1. setting up an OSGi project skeleton for development,
  2. adding libraries to OSGi project's internal build path,
  3. building OSGi projejct,
  4. deploying the compiled OSGi bundle in to CQ5 container.
What OSGi Bundle Can Bring to CQ
CQ5 runs in an Apache Felix OSGi container. To add configurable modular code to CQ, the code must also be an OSGi bundle jar. Out of the box, Adoble CQ5 is deployed with several OSGi components that you can configure them. To extend CQ's functionalities, you can develop your own OSGi bundle and deploy it into Felix, the OSGi container.

For example, if you want to write a custom library in Java that your JSP can import and use from any JSP file, you can develop an OSGi bundle. Or, if you want to some code to be triggered and executed whenever you 'activate/publish' a page node, you can develop an custom Workflow OSGi bundle with code of jobs to be executed whenever such an 'activate/publish' event is fired.

Create OSGi Bundle with CRXDE Lite
Step #1: Create an OSGi bundle project skeleton

Shoot up your CQ instance, log on as admin, go to CRXDE Lite. In CRXDE Lite, find a folder named 'src' (/apps/[your project]/src) under which is where your OSGi project will/should reside. To create a OSGi project skeleton, simply right-click src, select Create, then Create Bundle:


In the pop-up, give information to the bundle you'd create.
  • Symbolic Name: will be used toward the final OSGi bundle jar's name.
  • Name: is the name for displaying purposes in the CQ's Web console interface.
  • Package: is the full Java package name of the bundle you'd create. CQ will create corresponding folder to hold the java code.

After you hit OK, the following file structure with folders will be generated, include a BND file and an Activator.java.




Adobe CQ is not very user friendly. A common mistake developers make is forget to save along the way. Until now, nothing I created so far is saved. I have to explicitly save them by clicking on 'Save All.' You must remember to save often and I'm not going to remind you any more from this point on.



What if you have libraries (e.g., jars) to add to the build path for the project to compile in? I do not know any official documentation from Adobe about this but my experiments indicate if I create a folder named libs at the same level as the src folder, jars put under this libs folder will be built toward the project. In addition, I learned that /etc/crxde/profiles/default/libs/ is probably also part of the buildpath that you can also drop libraries there.

To demonstrate, I created a folder named libs, under which I put a dom4j jar and it will be picked up by CRXDE Lite's default bundle build step. Also, for demonstration purposes, I created some more Java classes (PageActivationEventHandler.java and PostpageActivationWorkflow.java) as if I had developed them and put them under the proper folder just to show where your custom Java source should go.




Step #2: Modify bnd file
BND is a command-line tool used internally by CQ for building OSGi bundles from a given descriptor file (.bnd file) to structure your JARs/Bundles by generating not just the MANIFEST.MF but also bundle up the JAR itself.

It is the auto-generated com.test.service.bnd file that I modified to overwrite the default to export all package and import all package:


Export-Package: * # 1
Import-Package: *
Private-Package: com.test.service
# Include-Resource:
Bundle-Name: Test Bundle
Bundle-Description:
Bundle-SymbolicName: com.test.service
Bundle-Version: 1.0.0-SNAPSHOT
Bundle-Activator: com.test.service.Activator


[1] For some reason, in CRXDE Lite, this '*' is required for making a specific component 'configurable' via CQ's configuration console. Otherwise, even you annotate a component with metatype=true (so Metatype Service data is generated in the metatype.xml file for this component) which in terms instructs CQ5 to provide a configuration page in the Felix Web console, the configuration interface still won't show under Web Console.

Step #3: Build bundle
To build, high-light the .bnd file, select Tools, then Bunld Bundle:


The result is the final bundle jar file generated under a folder named install which is at the same level as the src folder. As a reminder, the generated bundle jar won't show on CRXDE Lite until you refresh the install folder:


Install OSGi Bundle Built by CRXDE Lite
Once a bundle (.jar) file is generated under install folder, this bundle Jar file under install folder will be automatically picked up and installed by CQ5, specifically, by the JCR Installer module implicitly. In other words, if you followed step #3 for the first time that generated the bundle file (.jar) for the first time, the .jar should be installed for you already.

To verify the bundle jar is installed, you can always go to CQ's Web Console (probably at http://localhost:4502/system/console/configMgr), and look under OSGi, Bundles to see if the bundle name specified in step #1 above shows up.


Re-install OSGi Bundle Build by CRXDE Lite
Chances are, you'll be using CRXDE Lite to change your OSGi bundle code, build, install it, change the code, re-build, and re-install it over and over as part of the development process. I concluded the following steps to be most reliable:

1. Delete the old OSGi bundle (.jar) file under install folder. Click 'Save' to persist the deletion. This deletion will remove the bundle from appearing in the OSGi console. In other words, delete the .jar will uninstall the bundle.
2. Modify your OSGi code with enhancement or bug fixes. Rebuild (refer to step #3 as mentioned before) it, which will re-generate bundle file (.jar) under install folder.
3. Go to OSGi Console, locate the Bundle, click on it to bring up a page that only shows that bundle, click on "Refresh Packages."

'Refresh packages' instructs Felix OSGi container to reload the package dependency related to the package.
The same OSGi bundle under your development is now re-deployed.


References
Developing with CRXDE Lite
Hello, OSGi, Part 1: Bundles for beginners


By aem4beginner

May 4, 2020
Estimated Post Reading Time ~

Ways to Replicate a Node

Our first entry discusses how to replicate a node from AEM.

Adobe Experience Manager is a very deep product. If you don’t live and breathe it on a daily basis, you might forget how to perform certain tasks, or maybe you are new to AEM altogether. One task that we have found people struggling with from time to time is how to replicate a node that isn’t a traditional “cq:Page”. 

There are two simple methods that we have used to replicate arbitrary nodes that cannot be replicated using the Touch UI. The first is found under /etc/replication.html, the other is found in the CRXDE Lite.

On /etc/replication.html, find the “Activate Tree” link, which will allow you to specify a path and replicate it:



In CRXDE Lite, use the button on the “Replication” tab:




By aem4beginner

May 3, 2020
Estimated Post Reading Time ~

How to fix CRXDE performance issues

If your CRXDE is too slow or is not loading at all? Try these steps below to possibly fix the issue.

Make sure the crxde:paths property doesn’t include anything that you don't want to load in CRXDE.

  • Open the Content Explorer and browse to /etc/crxde/profiles/default, on the right-hand panel there will be the crxde:paths property, this defines what nodes CRXDE will try to load. Having nodes like /content will make it slow/unresponsive.

Locate and open the CRXDE.ini file and assign more memory to CRXDE.

  • On OSX right-click on CRXDE.app and select Show Package Contents.
  • Browse to Contents/MacOS
  • Open the CRXDE.ini file and change the values for Xms, Xmx and the MaxPermSize to suit your needs and what your system will support.
Delete the .crxde folder

  • CRXDE created a hidden .crxde folder under the user's home directory.
  • Delete that folder

Start CRXDE from the command line.

  • Open -a CRXDE –args -clean (This is for OSX only)

Hope this improves the performance of your CRXDE.


By aem4beginner

May 2, 2020
Estimated Post Reading Time ~

Understanding AEM Login Behavior

The CRX Login Module confirms authentication using a login token. This token is stored as a node in the jcr named under a node named .tokens under the logged-in user’s node (/home/users/user). The name of the specific login token is the date/time of the login. For instance, for admin the path might be:

/home/users/admin/.tokens/2015–04–22T10.57.34.180–04.00
The value of the token is also stored in the browser as a cookie named login-token. Whenever a request comes in, the cookie value and the token in the repository are compared.

In more advanced setups with multiple authors or publishers, the login cookie and login token node are only created on the specific AEM install the user logs into. So, if you have a setup with two authors and two publish servers and the user logs into author 1, their login is only valid on author1. Loading author 2 or the two publishers (for paths that require login like crx/de lite) will require re-authentication.

See this page for more details: Token authentication and token management

If you enable sticky sessions on the dispatcher, all requests by a particular client are always directed to the same instance of author/publisher — whatever the dispatcher is in front of.

There is documentation on the Oak/crx3 website on Oak’s token module.

Here is documentation on the way Sling handles authentication.


By aem4beginner

April 27, 2020
Estimated Post Reading Time ~

How to include custom meta tag headers from AEM Tags

This post explains the approach to include custom meta tag headers from AEM/CQ5 Tags.

Customize the page properties dialog:Customize the page properties dialog to add the field to select custom tags

Copy /libs/foundation/components/page/dialog and /libs/foundation/components/page/tab_basic under custom page rendering component e.g. /apps/training/components/page-content/

Create a node of type cq:widget under tab_basic with the following properties

Name.                 Type.         Value

-----------------------------------------
allowBlank         Boolean     true
fieldLabel          String       Page Type
name                String      ./page-type
namespaces      String[]      page-type
type                 String         tags




Refer https://www.albinsblog.com/2017/03/how-to-customize-page-properties-dialog-dynamic-dropdownlist-aem-cq5-in-touchui-classicui.html for more details on customizing the page properties dialog.

Define new tag namespace & tags:Create new tag namespace(page-type) through http://localhost:4502/tagging



Create required tags under page-type namespace





Override the the head.jsp if the page component is inhering from foundation/components/page. Add required logic in head.jsp to include the custom metatags from AEM tags.
e.g.
<%
%><%@ include file="/libs/foundation/global.jsp"%><%
%><%@ page contentType="text/html; charset=utf-8" import="com.albinsblog.samples.core.TagsUtil,com.day.cq.tagging.*"%><%

TagManager tagManager = resourceResolver.adaptTo(TagManager.class);
String[] pageTypeTags = properties.get("./page-type", String[].class);
String pageTypes = TagsUtil.getTagTitles(tagManager, pageTypeTags);
%><head>
<cq:include script="/libs/wcm/core/components/init/init.jsp"/>
<meta name="page-types" content="<%= pageTypes %>" />
</head>

TagsUtil.java - util class to fetch the tag titles and convert the titles to required formats.

import com.day.cq.tagging.Tag;
import com.day.cq.tagging.TagManager;
public class TagsUtil {
public static String getTagTitles(TagManager tagManager, String[] typeTags) {
StringBuffer typeBuffer = new StringBuffer();
if (typeTags != null) {
for (String typeTagId : typeTags) {
Tag typeTag = tagManager.resolve(typeTagId);
if (typeTag != null) {
String tagPath = typeTag.getTitlePath();
String[] splitTags = tagPath.split(":");
String tagName = splitTags[1];
if (typeTag != null)
typeBuffer.append(tagName + ";"); }
}
if (typeBuffer.length() != 0)
typeBuffer.deleteCharAt(typeBuffer.length() - 1);
}
return typeBuffer.toString();
}
}

Configure required tags in the page properties dialog


The defined meta tag will be added to the page



By aem4beginner

Different approaches to define vanity URL in AEM

This post explains the different approaches to define vanity URL’s in AEM.

Page-Level Vanity URL’s:
Open the page properties from siteadmin


Enter the Vanity URL and select Redirect Vanity URL to redirect to the page.


In this approach,
  • An author can edit the Vanity URL
  • Vanity URL should be unique across the instance
Sling Resource Resolver – URL Mapping:
Open the config manager - http://localhost:4502/system/console/configMgr Select Apache Sling Resource Resolver Factory.
Click the + sign in the URL Mappings.


Enter the resolved URL and the vanity URL in the Text box. /content/geometrixx-outdoors/en/men/coats/edmonton-winter.html:/edmonton-winter

Click Save.



In this approach,
  • The author can’t edit the Vanity URL
  • Vanity URL should be unique across the instance
Sling Resource Mappings:
Open http://localhost:4502/crx/de/index.jsp
Under /etc/map/http create a node of the type sling:Mapping

Create a property called, sling:internalRedirect, of type String with the value of redirect URL - /content/geometrixx-outdoors/en/men/coats/edmonton-winter.html
Create a property called, sling: match, of type String with the value of vanity URL- [^/]++/edmonton-winter.html



If we want to configure the same vanity URL for two different sites then specify the hostname along with port number as shown below in the vanity URL configuration.



Save all the configurations

Verifying the Vanity URL:
The vanity URL created in the above approaches can be verified by the following steps. Open http://localhost:4502/system/console/jcrresolver
Enter the Vanity URL in the text box and click Resolve

If the vanity URL is configured with Sling Resource Mappings then enter the full URL to resolve - http://localhost:4502/edmonton-winter.html



Dispatcher Rewrite Rules:
Setup virtual hosts for different URLs and specify the Rewrite Rules for redirect to the target URL in httpd.conf file.

<VirtualHost *>
ServerName www.example.com
DocumentRoot /dispatcher/cache/example
RewriteEngine on
RewriteRule ^/edmonton-winter.html$ /content/geometrixx-

outdoors/en/men/coats/edmonton-winter.html [NE,L,R=301] <Directory /dispatcher/cache/example>

<IfModule disp_apache2.c> SetHandler dispatcher-handler ModMimeUsePathInfo On

</IfModule>
Options FollowSymLinks AllowOverride None

</Directory> </VirtualHost>

<VirtualHost *>
ServerName www.example1.com
DocumentRoot /dispatcher/cache/example1
RewriteEngine on
RewriteRule ^/edmonton-winter.html$ /content/geometrixx-outdoors/en/men/coats.html

[NE,L,R=301]
<Directory /dispatcher/cache/example1>

<IfModule disp_apache2.c> SetHandler dispatcher-handler ModMimeUsePathInfo On

</IfModule>
Options FollowSymLinks AllowOverride None

</Directory> </VirtualHost>



By aem4beginner

NullPointerException: currentDesign.getDoctype(currentStyle).toRequest(request) - AEM

We were getting the NullpoiterException while accessing the pages in Adobe Experience Manager(AEM)

Caused by: java.lang.NullPointerException
at org.apache.jsp.apps.sample.design.components.pages.pageShell.pageShell_jsp._jspService(pageShell_jsp.java:227)
at org.apache.sling.scripting.jsp.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.apache.sling.scripting.jsp.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:502)
... 117 more

NullpointerException is thrown while getting the Doctype of the page design.

if (currentDesign != null) {
currentDesign.getDoctype(currentStyle).toRequest(request);
}

This issue was getting resolved after restarting the server.

After analysis the currentDesign and currentStyle objects are not null and getDoctype method is throwing NullpoiterException.

The currentStyle refers to the path (currentStyle.getPath())- /etc/designs/default.

By default /etc/designs/default/jcr:content path will not have cq:doctype property specified.

To resolve the issue we have added the cq:doctype - html_5 property to /etc/designs/default/jcr:content

If the property is already available then delete the same and add again.


By aem4beginner

Implementing Internationalization with i18n in Adobe CQ5

This post will explain how to implement Internationalization with i18n in Adobe CQ5

Configuring i18 keys:Create a sling:folder i18n inside apps or apps/<<application>> or inside the components folder based on the scope. e.g. /apps/i18n or apps/myapp/i18n or apps/myapp/global/components/mycomponent/i18n



Create a folder for each language inside 118n folder
Assign mixin to the language folders created in the previous step (e.g. en, ar etc) from crx console mix:language

For the language nodes (e.g. en, ar etc) add String property jcr: language, value = ISO language code (en, es etc)


Create nodes of type sling:MessageEntry for each field label

Add 2 properties sling:key = <keyname> and sling:message = <message>


Save all the changes

Using the i18n keys in JSP:
<%@page session="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@page import="java.util.Locale,java.util.ResourceBundle,com.day.cq.i18n.I18n"%>
<%@include file="/libs/foundation/global.jsp"%>
<cq:setContentBundle/>
<%
final Locale pageLocale = currentPage.getLanguage(false);
final ResourceBundle resourceBundle = slingRequest.getResourceBundle(pageLocale);
I18n i18n = new I18n(resourceBundle);
%>

<%= i18n.get("cartItem") %>


By aem4beginner

User name and password do not match error while accessing CRXDE

Sometimes we may receive User name and password do not match error while accessing the CRXDE and also Authentication Failed error while accessing the Adobe CQ5 configMgr.





We will be receiving this error if the anonymous user account is deleted accidentally.

How to fix
This can be fixed by restarting the repository, an anonymous user account will be re-created upon repository restart.


By aem4beginner

April 26, 2020
Estimated Post Reading Time ~

Logging in Operations Dashboard in AEM 6.X

This post will discuss logging via the Operations Dashboard in AEM 6.0 and beyond, and will also include a short tutorial to set it up for quick troubleshooting for developers and system operators alike.

Introduction
Have you ever wondered how some developers find the root cause of a lot of AEM problems faster than you can think of? Yes, you guessed it right. Reading the logs! This blog is going to discuss in brief an alternative way to read logs in AEM 6.0 and above. This method utilizes the Operations Dashboard. Please note that this is NOT a tutorial to set up regular logging in AEM. 

For that, you may want to read this, which is way more powerful. Instead, this method should be used to have a quick check from within the browser for minor errors and issues. This Logging method does not relate to the regular logging system in AEM, for this logging system stores all the messages in in-memory storage. 

So, whatever way you configure your regular AEM logging system is independent of the regular log files and vice-versa, which means, changing the log levels in one of these will never affect the other. Another important point to note is that by default, all the ERROR level messages are logged in the operations dashboard logging system. 

To see other types of logs messages here, like DEBUG, INFO, or WARN, you have to configure the dashboard differently. You can set it up to log messages from certain packages or your entire AEM system. All these can be done by clicking the GEAR icon in the logging page (libs/granite/operations/content/diagnosis.html) within the Operations dashboard.

Quick Setup
In your AEM console, go to Tools > Operations > Dashboard > Diagnosis > Log Messages. This is where you will see the logged messages that you choose.
Click the GEAR icon in the upper left corner of this page and you'll see the following screen.

A log level of WARN will capture all the ERROR and WARN level messages in the chosen package. If the root is chosen, all the packages will be considered.
Similarly, a log level of INFO will capture all the ERROR, WARN, and INFO level log messages.

And, a log level of DEBUG will capture all the levels from the respective package.

Note: You cannot set the system to capture only ERROR messages via a specified filter. All ERROR messages will be captured by default, as mentioned earlier.


By aem4beginner

Changing Default Favicon of AEM Admin Interface

To change the default favicon of the touch UI admin interface, you need to overlay the /libs/granite/ui/components/foundation/page/favicon/favicon.jsp. Just change this path in your overlayed file and remove the Adobe copyright comment text.

Config cfg = cmp.getConfig();
AttrBuilder attrs = new AttrBuilder(request, xssAPI);
attrs.add("rel", "shortcut icon");
attrs.addHref("href", cfg.get("href", "/libs/granite/core/content/login/favicon.ico"));
// https://en.wikipedia.org/wiki/Favicon#How_to_use
%><link <%= attrs.build() %>>


Change the favicon path highlighted in red above.

Refer the below screenshot to overlay the OOTB favicon.jsp-



By aem4beginner

Input Field validation

AEM6 uses Coral UI framework for touch UI rendering. So if you need to implement field validation, you should register a validator on that field supported by Coral UI. Refer the below example-

Sample code to implement mandatory validation on an Input field with trim function-

1. In your component field properties add two new properties- validation-trim (Set value to true) and trimMessage (Set value to the validation message). Look at the screenshot below-



2. Create a clientLibs Folder with category- "cq.authoring.dialog" and add a JS file having following code-

;(function ($, $document) {
"use strict";

$document.on("dialog-ready", function() {
//Register Trimmed Value Validator
$.validator.register({
selector: "[data-validation-trim]",
validate: function(el) {
var length = el.val().trim().length;
if (length == 0) {
var message = el.attr("data-trimMessage");
return message;
}
}
});
});})($, $(document));


Once you have added this JS to your page, you can call it in any number of fields. You just need to add two properties to the fields where you want validation as mentioned in Step 1 above.


By aem4beginner

Creating Configuration Factory Service

This post talks about creating Configuration Factory service using OSGI R6 annotations. In order to create this service, we need to create a Service Interface and Implementation class.

Let's create an interface to define the configurations
package com.aemquickstart.core.interfaces;

import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;

@ObjectClassDefinition(name = "AEM Quickstart Site Configs")
public @interface SiteConfigs {
 
  @AttributeDefinition(name="Site Id", description="Site ID")
     String getSiteId() default "aemquickstart";
  @AttributeDefinition(name="Site Name", description="Site Name")
     String getSiteName() default "AEM Quickstart";
}

Now create an interface
package com.aemquickstart.core.services;
public interface SiteConfigService {
 public String getSiteId();
 public String getSiteName();
}

Create an implementation class for above interface.
package com.aemquickstart.core.services.impl;

import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.metatype.annotations.Designate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aemquickstart.core.interfaces.SiteConfigs;
import com.aemquickstart.core.services.SiteConfigService;

@Component(service = SiteConfigService.class, immediate = true)
@Designate(ocd = SiteConfigs.class, factory = true)
public class SiteConfigServiceImpl implements SiteConfigService {
 private static final Logger log = LoggerFactory.getLogger(SiteConfigService.class);
 private SiteConfigs config;

 @Activate
 protected void activate(SiteConfigs config) {
  log.info("In activate");
  this.config = config;
 }

 @Override
 public String getSiteId() {
  return config.getSiteId();
 }

 @Override
 public String getSiteName() {
  return config.getSiteName();
 }

}

Build code and go to ConfigMgr to see the Configuration Factory Service







Now create a service to fetch the properties configured using Configuration Factory Service.

package com.aemquickstart.core.services;
import java.util.List;

public interface SiteConfigServiceConsumer {
  public List getConfigurationList() ;
}

Create an implementation class
package com.aemquickstart.core.services.impl;

import java.util.ArrayList;
import java.util.List;

import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aemquickstart.core.services.SiteConfigService;
import com.aemquickstart.core.services.SiteConfigServiceConsumer;

@Component(immediate = true, service = SiteConfigServiceConsumer.class, enabled = true)

public class SiteConfigServiceConsumerImpl implements SiteConfigServiceConsumer {
 private static final Logger LOGGER = LoggerFactory.getLogger(SiteConfigServiceConsumer.class);
 private List configurationList;

 @Reference(name = "configurationFactory", cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC)
 protected synchronized void bindConfigurationFactory(final SiteConfigService config) {
  LOGGER.info("bindConfigurationFactory: {}", config.getSiteId());
  if (configurationList == null) {
   configurationList = new ArrayList<>();
  }
  configurationList.add(config);
 }

 protected synchronized void unbindConfigurationFactory(final SiteConfigService config) {
  LOGGER.info("unbindConfigurationFactory: {}", config.getSiteId());
  configurationList.remove(config);
 }

 public List getConfigurationList() {
  return configurationList;
 }

 public void setConfigurationList(List configurationList) {
  this.configurationList = configurationList;
 }
}

Create a sling model to access this property values
package com.aemquickstart.core.models;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.inject.Inject;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aemquickstart.core.services.SiteConfigService;
import com.aemquickstart.core.services.SiteConfigServiceConsumer;

@Model(adaptables = SlingHttpServletRequest.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class Page {
 protected final Logger log = LoggerFactory.getLogger(this.getClass());

 @Inject
 SiteConfigServiceConsumer service;

 @PostConstruct
 private void initModel() {
  log.info("Page is loaded");
  List<SiteConfigService> configurationList;
  configurationList = service.getConfigurationList();
  log.info("Service: {}", configurationList);
  for (int i = 0; i < configurationList.size(); i++) {
   log.info("Site ID: {}", (configurationList.get(i)).getSiteId());
   log.info("Site Name: {}", (configurationList.get(i)).getSiteId());
  }
 }
}

SiteID and SiteName which we configured using Configuration Factory service can be fetched in this Sling model class. Update your business logic as per your requirement.

Create runmode for the OSGi config

xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0"
    xmlns:jcr="http://www.jcp.org/jcr/1.0" jcr:primaryType="sling:OsgiConfig"
    getSiteId="aemquickstart"
    getSiteName="AEM Quickstart" />


By aem4beginner

Changing a .content.xml file locally is not reflecting in CRX after maven build

If .content.xml file is changed locally and changes are not reflecting in crx then check maven-resources-plugin.

Add below plugin in pom.xml of UI module.(aem-sample/aem-content-ui/pom.xml).

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-content-resources</id>
<phase>process-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/vault-work</outputDirectory>
<resources>
<resource>
<directory>${basedir}/src/main/content</directory>
<filtering>true</filtering>
<excludes>
<exclude>**/.svn</exclude>
<exclude>**/.vlt</exclude>
<exclude>**/.vltignore</exclude>
<exclude>**/.DS_Store</exclude>
<exclude>/etc/designs/${project.parent.artifactId}/jcr:content(/.*)?</exclude>
</excludes>
</resource>
</resources>
</configuration>
</execution>
</plugin>

For maven-resources-plugin check that its copying your .content.xml to target folder and for content-package-maven-plugin check that correct filter values are set.

We can also verify by extracting the generated package and check if it has the changes or not or look at a vault-work directory in target and get to the directory in which you have changed the .content.xml, verify if it has changes. If your changes are there in vault-works then the maven-resources-plugin is working absolutely fine and the issue may be with the content-package-maven-plugin.


By aem4beginner

April 23, 2020
Estimated Post Reading Time ~

How to find the Binaries location on the file system

Statement: Identify the Binary Location on the file system

Environment: AEM 6.3
Solution:
1. Go to this path http://localhost:4502/crx/de/index.jsp#/content/dam/projects/we-retail/cover/jcr%3Acontent/metadata



2. And Navigate to this path in crxde search : /content/dam/projects/we-retail/cover/jcr:content/metadata



3. Check the value of dam:sha1 and that shows the binary location on file system Dam:sha1 =a81372af7d4d9ab856cad6e293ea48e653f0e278


4. Whereas first letter a813 indicates datastore location on the file system where - \crx-quickstart\repository\datastore\0a\81\13 and you can observe the asset located under with file type .file : 0a81135558804df12feb78bd994c0f4416aad830

5. Now change the file extension to jpg i.e 0a81135558804df12feb78bd994c0f4416aad830.jpg
6. Open in the Phot viewer or Photoshop.
7. Post seeing the image and revert the image back to the original file extension i.e remove the .jpg extension.


By aem4beginner