AutoSave.java 2.51 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.replication.impl.content.durbo;

import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AutoSave {
    private final Logger log = LoggerFactory.getLogger(AutoSave.class);
    private int numModified;
    private int lastSave;
    private int threshold;
    private int debugFailEach;
    private int debugSaveCount;

    public AutoSave(int threshold) {
        this.threshold = threshold;
    }

    public AutoSave copy() {
        AutoSave ret = new AutoSave(this.threshold);
        ret.numModified = this.numModified;
        ret.lastSave = this.lastSave;
        ret.debugFailEach = this.debugFailEach;
        return ret;
    }

    public void setDebugFailEach(int debugFailEach) {
        this.debugFailEach = debugFailEach;
    }

    public boolean needsSave() {
        return this.threshold > 0 && this.numModified - this.lastSave >= this.threshold;
    }

    public void save(Session session) throws RepositoryException {
        if (this.threshold == Integer.MAX_VALUE) {
            this.log.debug("Save disabled.");
            return;
        }
        int diff = this.numModified - this.lastSave;
        this.log.info("Threshold of {} reached. saving approx {} transient changes.", new Object[]{this.threshold, diff});
        if (session != null) {
            if (this.debugFailEach > 0 && this.debugSaveCount > 0 && this.debugSaveCount % this.debugFailEach == 0) {
                String msg = String.format("Debugging provoked failure after %s saves.", this.debugSaveCount);
                this.log.error(msg);
                throw new RepositoryException(msg);
            }
            try {
                session.save();
                ++this.debugSaveCount;
            }
            catch (RepositoryException e) {
                this.log.error("error during auto save - retrying after refresh...");
                session.refresh(true);
                session.save();
                ++this.debugSaveCount;
            }
        }
        this.lastSave = this.numModified;
    }

    public int getThreshold() {
        return this.threshold;
    }

    public boolean modified(int num) {
        this.numModified += num;
        return this.needsSave();
    }

    public String toString() {
        return String.valueOf(this.threshold);
    }
}