PropertyEditor.java 2.65 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.wcm.msm.impl.actions;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class PropertyEditor {
    private final Logger log = LoggerFactory.getLogger(PropertyEditor.class);
    private final List<EditRule> rules = new ArrayList<EditRule>();

    PropertyEditor(String editMap) {
        StringTokenizer tk = new StringTokenizer(editMap, ",");
        while (tk.hasMoreTokens()) {
            this.rules.add(new EditRule(tk.nextToken().trim()));
        }
    }

    public String toString() {
        return this.getClass().getSimpleName() + ", rules=" + this.rules;
    }

    public Collection<EditRule> getRules() {
        return Collections.unmodifiableCollection(this.rules);
    }

    void editNode(Node n) throws RepositoryException {
        for (EditRule r : this.rules) {
            if (!n.hasProperty(r.propertyName)) continue;
            Property p = n.getProperty(r.propertyName);
            String orig = p.getString();
            Matcher m = r.pattern.matcher(orig);
            String repl = m.replaceAll(r.replacement);
            if (!repl.equals(orig)) {
                n.setProperty(r.propertyName, repl);
                this.log.debug("Property {} set to {} due to rule {}", new Object[]{p.getPath(), repl, r});
                continue;
            }
            this.log.debug("Property {} value '{}' unchanged by rule {}, not modified", new Object[]{p.getPath(), orig, r});
        }
    }

    static class EditRule {
        final String propertyName;
        final Pattern pattern;
        final String replacement;

        EditRule(String rule) {
            StringTokenizer tk = new StringTokenizer(rule, "#");
            if (tk.countTokens() != 3) {
                throw new IllegalArgumentException("Invalid rule string '" + rule + "'");
            }
            this.propertyName = tk.nextToken().trim();
            this.pattern = Pattern.compile(tk.nextToken());
            this.replacement = tk.nextToken();
        }

        public String toString() {
            return this.getClass().getSimpleName() + ", Property=" + this.propertyName + ", Pattern=" + this.pattern + ", Replacement=" + this.replacement;
        }
    }

}