TestServlet.java
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.ValueFactory;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SlingServlet(paths = "/bin/test", extensions = "txt")
public class TestServlet extends SlingSafeMethodsServlet {
private static final Logger LOG = LoggerFactory.getLogger(TestServlet.class);
@Reference
private ResourceResolverFactory resolverFactory;
private static final String PARENT = "/content/usergenerated/content";
public void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
ResourceResolver resourceResolver = null;
try {
resourceResolver = resolverFactory.getAdministrativeResourceResolver(null);
Session session = resourceResolver.adaptTo(Session.class);
reverseReplicateBinary(session, PARENT, "page123",
new ByteArrayInputStream("this is sample".getBytes()));
response.getWriter().println("session saved");
} catch (LoginException e) {
LOG.error("Can't get resolver", e);
} catch (RepositoryException e) {
LOG.error("Can't get resolver", e);
} finally {
if (resourceResolver != null) {
resourceResolver.close();
}
}
}
private void reverseReplicateBinary(Session session, String parentPath, String name, InputStream is)
throws RepositoryException {
ValueFactory valueFactory = session.getValueFactory();
Node parent = session.getNode(parentPath); Node page = JcrUtils.getOrCreateUniqueByPath(parent, name, "cq:Page");
Node jcrContent = page.addNode(Property.JCR_CONTENT, "cq:PageContent");
Node file = jcrContent.addNode("file", "nt:file");
Node resource = file.addNode(Property.JCR_CONTENT, "nt:resource");
resource.setProperty(Property.JCR_DATA, valueFactory.createBinary(is));
session.save(); jcrContent.setProperty("cq:lastModified", Calendar.getInstance());
jcrContent.setProperty("cq:lastModifiedBy", session.getUserID());
jcrContent.setProperty("cq:distribute", false);
session.save();
}
}
This java class doesn't reverse replicate the content. It just saves the content in current instance. In order to reverse replicate the content we can use replication API.
ReplyDelete