Sunday, 28 August 2016

AEM Code Snippets

// to get list of selectors in an array
String[] selectors = slingRequest.getRequestPathInfo().getSelectors();
// to get a page from a path
Page page = pageManager.getPage(path);
// to get any containing page for a resource
Page page = pageManager.getContainingPage(resourceResolver.getResource(path));
// to get a session in JSP
final SlingRepository repos = sling.getService(SlingRepository.class);
session = repos.loginAdministrative(null);

// to get query object and run a query
//build query using search in crx explorer or crxdelite
String stmt = "select * from cq:Page where jcr:path like '/content/training/%' and contains(*, '" + slingRequest.getParameter("q") + "') order by jcr:score desc";

Query query = currentNode.getSession().getWorkspace().getQueryManager().createQuery(stmt, Query.SQL);
QueryResult results = query.execute();

// Get node from path
Node n = session.getItem(path); // where session = JCR session
session.save();
session.logout();

// add a property to node
Node n = parent.addNode(…);
n.setProperty(“prop-name”,”value”);

Java Code

// creating a logger instance

private static final Logger LOGGER = LoggerFactory.getLogger(ReplicationLogger.class);
// Sending an Event

@Reference
EventAdmin eventAdmin
public void sendEventTo(){
org.osgi.service.event.Event event = new Event(EventTopic, <object>);
eventAdmin.sendEvent(event);
}
//to get page manager

final PageManager pm = resourceResolver.adaptTo(PageManager.class);

// to get repository

@Reference
SlingRepository repository;
// get session from repository

session = repository.loginAdministrative(null);

XSS Protection for AEM Servlets:

Add XSS protection in AEM servlets using Apache Sling XSSAPI to avoid any scripts tag injected into request. This avoid any penetration issues.

import org.apache.sling.xss.XSSAPI; 
import org.apache.sling.api.SlingHttpServletRequest; 

XSSAPI xssapi = slingHttpServletRequestObj.adaptTo(XSSAPI.class); 
  String encodedAttr = xssapi.encodeForHTMLAttr(someUnsafeValue);

Default XSS configuration in AEM is available at /libs/cq/xssprotection/config.xml

No comments :

Post a comment