
com.day.cq.contentsync.handler.HashableContentUpdateHandler Maven / Gradle / Ivy
package com.day.cq.contentsync.handler;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import com.day.cq.commons.jcr.JcrConstants;
import com.day.cq.contentsync.handler.util.RequestResponseFactory;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import com.google.common.io.ByteSource;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
public abstract class HashableContentUpdateHandler implements ContentUpdateHandler {
/**
* Mixin node type for hash value
*/
private final static String NT_CONTENT_SYNC_HASH = "cq:ContentSyncHash";
/**
* Hash property name
*/
public final static String HASH_PROPERTY = "md5";
@Deprecated
protected String getHash(RequestResponseFactory factory, HttpServletResponse response) throws RepositoryException {
throw new UnsupportedOperationException("getHash is no longer supported");
}
@Deprecated
protected String getHash(byte[] bytes) throws RepositoryException {
throw new UnsupportedOperationException("getHash is no longer supported");
}
protected boolean hashMatches(Session session, String cachePath, String hash) throws RepositoryException {
String hashPath = cachePath + "/" + JcrConstants.JCR_CONTENT + "/" + HASH_PROPERTY;
return session.propertyExists(hashPath) && session.getProperty(hashPath).getString().equals(hash);
}
protected void writeHash(Node node, String hash) throws RepositoryException {
node.addMixin(NT_CONTENT_SYNC_HASH);
node.setProperty(HASH_PROPERTY, hash);
}
protected InputStream writeHashAndGetStream(InputStream in, Node node) throws IOException, RepositoryException {
File tempDir = Files.createTempDir();
File tempFile = new File(tempDir, "stream");
try {
FileOutputStream out = new FileOutputStream(tempFile);
try {
ByteStreams.copy(in, out);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
ByteSource byteSource = Files.asByteSource(tempFile);
HashCode hashCode = getHashCode(byteSource);
writeHash(node, hashCode.toString());
return byteSource.openStream();
} finally {
FileUtils.deleteDirectory(tempDir);
}
}
protected HashCode getHashCode(ByteSource byteSource) throws IOException {
return ByteStreams.hash(byteSource, Hashing.sha256());
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy