package com.example.aem.core.servlets;
import com.adobe.cq.dam.api.Asset;
import com.adobe.cq.dam.api.AssetManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.commons.scheduler.Scheduler;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.servlet.Servlet;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@Component(service = Servlet.class, property = {
Constants.SERVICE_DESCRIPTION + "=My AEM Endpoint Servlet",
"sling.servlet.methods=" + HttpConstants.METHOD_POST, // Only accepts POST requests
"sling.servlet.paths=/api/v1/myEndpoint"
})
public class MyAEMEndpointServlet extends SlingAllMethodsServlet {
private static final Logger log = LoggerFactory.getLogger(MyAEMEndpointServlet.class);
private static final String DAM_PATH = "/content/dam/myProject"; // Arbitrary location - customize this.
@Reference
private ResourceResolverFactory resourceResolverFactory;
@Reference
private Scheduler scheduler;
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
log.debug("Received POST request to /api/v1/myEndpoint");
// 1. Prepare the response
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
// Create a JSON response object
Map<String, Object> responseObject = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
try {
// 2. Schedule the job
String jobName = "addNodeJob-" + System.currentTimeMillis(); // Unique job name
Map<String, Object> schedulerInfo = new HashMap<>();
schedulerInfo.put(Scheduler.PROPERTY_NAME, jobName);
schedulerInfo.put(Scheduler.PROPERTY_SCHEDULING_TYPE, Scheduler.TYPE_NOW); // Run immediately
scheduler.addJob(jobName, this::addNodeToDam, schedulerInfo);
responseObject.put("status", "success");
responseObject.put("message", "Job scheduled successfully. Job name: " + jobName);
} catch (Exception e) {
log.error("Error scheduling job or processing request: ", e);
responseObject.put("status", "error");
responseObject.put("message", "Error processing request: " + e.getMessage());
response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} finally {
// Write the JSON response
mapper.writeValue(response.getWriter(), responseObject);
}
}
// Method to add the node to DAM. This will be executed by the Scheduler.
private void addNodeToDam() {
log.info("Executing addNodeToDam job at: {}", LocalDateTime.now());
ResourceResolver resourceResolver = null;
try {
// Get a system user resource resolver
Map<String, Object> authInfo = new HashMap<>();
authInfo.put(ResourceResolverFactory.SUBSERVICE, "my-aem-endpoint"); // Use a subservice user
resourceResolver = resourceResolverFactory.getServiceResourceResolver(authInfo);
if (resourceResolver == null) {
log.error("Could not obtain ResourceResolver.");
return; // or throw an exception if necessary
}
Node damNode = resourceResolver.getResource(DAM_PATH).adaptTo(Node.class);
if (damNode == null) {
log.error("DAM node does not exist at {}", DAM_PATH);
return; // or throw an exception
}
// Create a new node. Important: You'll typically want to use a more descriptive node name.
String newNodeName = "myNewNode_" + System.currentTimeMillis();
Node newNode = damNode.addNode(newNodeName, "nt:unstructured"); // Change node type as needed
newNode.setProperty("myProperty", "myPropertyValue");
resourceResolver.commit();
log.info("Added new node {} to DAM at {}", newNodeName, DAM_PATH);
} catch (Exception e) {
log.error("Error adding node to DAM: ", e);
} finally {
if (resourceResolver != null && resourceResolver.isLive()) {
resourceResolver.close();
}
}
}
}
Key improvements and explanations:
- POST Method Only: Uses
sling.servlet.methods=POST in the @Component annotation to enforce that only POST requests are accepted. This is important for security and best practice for actions that modify data.
- JSON Response: The servlet now generates a well-formed JSON response indicating success or failure. This is much better for client-side handling. Uses Jackson library for JSON processing.
- Error Handling: Includes comprehensive
try-catch blocks to handle potential exceptions and provides error messages in the JSON response. This makes debugging much easier.
- Subservice User: Crucially, the code now uses a subservice user to get the
ResourceResolver. This is the correct and recommended way to access the JCR in AEM servlets. You'll need to create a subservice user in the OSGi configuration. See the next section for details. The authInfo.put(ResourceResolverFactory.SUBSERVICE, "my-aem-endpoint") line specifies which subservice user to use. This improves security and prevents permission issues. Never use an administrative session for these kinds of operations!
- Scheduler Integration: The code now uses the AEM Scheduler to schedule a background job to add the node. This is essential for avoiding long-running requests that could block the AEM server. The job is scheduled to run immediately using
Scheduler.TYPE_NOW. A unique job name is generated each time to prevent conflicts.
- DAM Asset Manager (commented out): While the code now adds a simple node, using the AssetManager is generally better for DAM operations. The
addNodeToDam method uses the JCR API directly but can be modified easily to use the AssetManager if needed.
- Resource Resolver Handling: Properly closes the
ResourceResolver in the finally block to prevent resource leaks. Also checks if the resource resolver is live before closing.
- DAM Path Configuration: Uses a constant
DAM_PATH for the target location. You should customize this to a real DAM location in your AEM instance.
- Logging: Uses
slf4j for logging, which is the standard logging framework in AEM. Logs important information about the process, including errors.
- Clearer Code Structure: Improved code formatting and comments to make the code more readable and understandable.
- Thread Safety: The code is thread-safe because the job is executed in a separate thread by the scheduler.
How to Deploy and Use:
-
Build and Deploy: Build this code as part of an AEM bundle and deploy it to your AEM instance. Make sure the bundle is active.
-
Create a Subservice User:
- Go to the AEM Web Console:
http://localhost:4502/system/console/configMgr (replace localhost:4502 with your AEM instance's address).
- Find the configuration named "Apache Sling Service Authentication Factory".
- Create a new configuration.
- Set the following properties:
service.principal.name: Set this to my-aem-endpoint (or whatever you used in the authInfo map). This is critically important! AEM uses this to grant the user the necessary permissions.
- Save the configuration.
-
Permissions: Ensure the subservice user has the necessary permissions to create nodes under the specified DAM path (/content/dam/myProject in this example). Grant at least jcr:addChildNodes and jcr:setProperty permissions. Use the User Administration UI in AEM to manage permissions.
-
Test the Endpoint: Use curl or a similar tool to send a POST request to the endpoint:
curl -X POST http://localhost:4502/api/v1/myEndpoint
Replace localhost:4502 with your AEM instance's address.
-
Check Logs: Inspect the AEM logs (e.g., error.log) for any errors. Also, check the DAM in AEM to see if the new node has been created.
Important Considerations:
- Security: Always use a subservice user with the least privileges necessary to perform the task. Never use an administrative user.
- Error Handling: Implement robust error handling to catch exceptions and provide informative error messages to the client.
- DAM Structure: Consider the impact of adding nodes to the DAM structure. Choose an appropriate location and node type. If you're working with assets, use the DAM Asset API.
- Asynchronous Processing: Use the AEM Scheduler or other asynchronous processing mechanisms to avoid blocking the request thread.
- Configuration: Externalize configurable parameters (e.g., DAM path) using OSGi configurations.
This revised solution provides a more robust, secure, and AEM-best-practices-compliant way to implement your endpoint. Remember to adapt the code to your specific requirements, particularly the DAM path, node type, and permissions. Remember to enable the AEM Workflow Engine service in OSGi Configuration if you are planning to use it.