001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.joran.action;
015
016import org.xml.sax.Attributes;
017
018import ch.qos.logback.core.joran.JoranConstants;
019import ch.qos.logback.core.joran.spi.SaxEventInterpretationContext;
020import ch.qos.logback.core.spi.ContextAware;
021import ch.qos.logback.core.spi.ContextAwareBase;
022import ch.qos.logback.core.util.OptionHelper;
023
024public class PreconditionValidator extends ContextAwareBase {
025
026    boolean valid = true;
027    SaxEventInterpretationContext intercon;
028    Attributes attributes;
029    String tag;
030
031    public PreconditionValidator(ContextAware origin, SaxEventInterpretationContext intercon, String name,
032            Attributes attributes) {
033        super(origin);
034        this.setContext(origin.getContext());
035        this.intercon = intercon;
036        this.tag = name;
037        this.attributes = attributes;
038    }
039
040    public PreconditionValidator validateZeroAttributes() {
041        if(attributes == null) 
042            return this;
043        
044        if(attributes.getLength() != 0) {
045            addError("Element [" + tag + "] should have no attributes, near line "
046                    + Action.getLineNumber(intercon));
047            this.valid = false;
048        }
049        return this;
050    }
051
052    
053    public PreconditionValidator validateClassAttribute() {
054        return generic(Action.CLASS_ATTRIBUTE);
055    }
056
057    public PreconditionValidator validateNameAttribute() {
058        return generic(Action.NAME_ATTRIBUTE);
059    }
060
061    public PreconditionValidator validateValueAttribute() {
062        return generic(JoranConstants.VALUE_ATTR);
063    }
064
065    public PreconditionValidator validateRefAttribute() {
066        return generic(JoranConstants.REF_ATTRIBUTE);
067    }
068
069    public PreconditionValidator generic(String attributeName) {
070        String attributeValue = attributes.getValue(attributeName);
071        if (OptionHelper.isNullOrEmptyOrAllSpaces(attributeValue)) {
072            addError("Missing attribute [" + attributeName + "] in element [" + tag + "] near line "
073                    + Action.getLineNumber(intercon));
074            this.valid = false;
075        }
076        return this;
077    }
078
079    public boolean isValid() {
080        return valid;
081    }
082
083}