in slingshot/src/main/java/org/apache/sling/sample/slingshot/comments/impl/CommentsServiceImpl.java [69:117]
public void addComment(final Resource resource, final Comment c)
throws PersistenceException {
final String commentsPath = this.getCommentsResourcePath(resource);
final Map<String, Object> props = new HashMap<String, Object>();
props.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, RESOURCETYPE_COMMENTS);
final Resource ratingsResource = ResourceUtil.getOrCreateResource(resource.getResourceResolver(),
commentsPath, props, null, true);
final Map<String, Object> properties = new HashMap<String, Object>();
properties.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, CommentsUtil.RESOURCETYPE_COMMENT);
properties.put(CommentsUtil.PROPERTY_TITLE, c.getTitle());
properties.put(CommentsUtil.PROPERTY_TEXT, c.getText());
properties.put(CommentsUtil.PROPERTY_USER, c.getCreatedBy());
// we try it five times
PersistenceException exception = null;
Resource newResource = null;
for(int i=0; i<5; i++) {
try {
exception = null;
final String name = ResourceUtil.createUniqueChildName(ratingsResource, Util.filter(c.getTitle()));
newResource = resource.getResourceResolver().create(ratingsResource, name, properties);
resource.getResourceResolver().commit();
break;
} catch ( final PersistenceException pe) {
resource.getResourceResolver().revert();
resource.getResourceResolver().refresh();
exception = pe;
}
}
if ( exception != null ) {
throw exception;
}
// order node at the top (if jcr based)
final Node newNode = newResource.adaptTo(Node.class);
if ( newNode != null ) {
try {
final Node parent = newNode.getParent();
final Node firstNode = parent.getNodes().nextNode();
if ( !firstNode.getName().equals(newNode.getName()) ) {
parent.orderBefore(newNode.getName(), firstNode.getName());
newNode.getSession().save();
}
} catch ( final RepositoryException re) {
logger.error("Unable to order comment to the top", re);
}
}
}