Skip to content

Instantly share code, notes, and snippets.

@klcodanr
Created December 10, 2020 19:34
Show Gist options
  • Save klcodanr/9589375352c2c1f319ad3031cf402f8b to your computer and use it in GitHub Desktop.
Save klcodanr/9589375352c2c1f319ad3031cf402f8b to your computer and use it in GitHub Desktop.
Cleans up AEM versions
import org.apache.sling.api.resource.Resource;
import javax.jcr.*;
import javax.jcr.version.*;
start = System.currentTimeMillis();
limit = 5;
cleaned = 0;
versionManager = session.getWorkspace().getVersionManager();
void cleanupVersions(Resource history) {
String path = null;
try {
long deleteStart = System.currentTimeMillis();
path = history.getValueMap().get('crx.default','');
log.info("Handling version cleanup for: ${path}");
VersionHistory versionHistory = (VersionHistory) session.getNode(history.getPath())
VersionIterator versionIterator = versionHistory.getAllVersions();
List<String> versionNames = new ArrayList<>();
while (versionIterator.hasNext()) {
Version version = versionIterator.nextVersion();
if (!version.getName().equals("jcr:rootVersion")) {
versionNames.add(version.getName());
}
}
if(versionNames.size() > limit){
List<String> toCleanup = versionNames.subList(0, versionNames.size() - limit);
log.info("Cleaning up versions: ${toCleanup}");
for(String item : toCleanup) {
versionHistory.removeVersion(item);
log.info("Cleaned up: ${item}");
}
log.info("Cleanup complete for: ${path} in ${System.currentTimeMillis() - deleteStart}");
}
out.flush();
} catch (RepositoryException re){
log.error("Failed to cleanup version history for ${path}", re);
}
}
void findVersions(Resource resource){
//out.println("Finding versions under: ${resource.getPath()}");
if("nt:versionHistory".equals(resource.getResourceType())){
resourceResolver.refresh();
cleanupVersions(resource);
out.flush();
cleaned++;
} else {
for(Resource child : resource.getChildren()){
findVersions(child);
}
}
}
Resource versionStorage = resourceResolver.getResource('/jcr:system/jcr:versionStorage');
findVersions(versionStorage);
out.println("Cleanup complete in ${System.currentTimeMillis() - start}");
log.info("Cleanup complete in ${System.currentTimeMillis() - start}");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment