001: /*
002: * Copyright (C) Chaperon. All rights reserved.
003: * -------------------------------------------------------------------------
004: * This software is published under the terms of the Apache Software License
005: * version 1.1, a copy of which has been included with this distribution in
006: * the LICENSE file.
007: */
008:
009: package net.sourceforge.chaperon.model.pattern;
010:
011: import net.sourceforge.chaperon.model.Violations;
012:
013: /**
014: * This class describes a alternation of pattern.
015: *
016: * @author <a href="mailto:stephan@apache.org">Stephan Michels</a>
017: * @version CVS $Id: Alternation.java,v 1.4 2003/12/09 19:55:52 benedikta Exp $
018: */
019: public class Alternation extends PatternList {
020: /**
021: * Create a pattern for alternation of pattern.
022: */
023: public Alternation() {
024: }
025:
026: /**
027: * Create a clone of this pattern.
028: *
029: * @return Clone of this pattern.
030: *
031: * @throws CloneNotSupportedException If an exception occurs during the cloning.
032: */
033: public String toString() {
034: StringBuffer buffer = new StringBuffer();
035:
036: for (int i = 0; i < getPatternCount(); i++) {
037: if (i > 0)
038: buffer.append("|");
039:
040: buffer.append(getPattern(i).toString());
041: }
042:
043: if ((getMinOccurs() == 1) && (getMaxOccurs() == 1)) {
044: // nothing
045: } else if ((getMinOccurs() == 0) && (getMaxOccurs() == 1))
046: buffer.append("?");
047: else if ((getMinOccurs() == 0)
048: && (getMaxOccurs() == Integer.MAX_VALUE))
049: buffer.append("*");
050: else if ((getMinOccurs() == 1)
051: && (getMaxOccurs() == Integer.MAX_VALUE))
052: buffer.append("+");
053: else {
054: buffer.append("{");
055: buffer.append(String.valueOf(getMinOccurs()));
056: buffer.append(",");
057: buffer.append(String.valueOf(getMaxOccurs()));
058: buffer.append("}");
059: }
060:
061: return buffer.toString();
062: }
063:
064: /**
065: * Create a clone of this pattern.
066: *
067: * @return Clone of this pattern.
068: *
069: * @throws CloneNotSupportedException If an exception occurs during the cloning.
070: */
071: public Object clone() {
072: Alternation clone = new Alternation();
073:
074: clone.setMinOccurs(getMinOccurs());
075: clone.setMaxOccurs(getMaxOccurs());
076:
077: for (int i = 0; i < getPatternCount(); i++)
078: clone.addPattern(getPattern(i));
079:
080: return clone;
081: }
082:
083: /**
084: * Validates this pattern.
085: *
086: * @return Return a list of violations, if this pattern isn't valid.
087: */
088: public Violations validate() {
089: Violations violations = new Violations();
090:
091: if (getPatternCount() == 0)
092: violations.addViolation(
093: "Alternation doesn't contain any elements",
094: getLocation());
095:
096: for (int i = 0; i < getPatternCount(); i++)
097: violations.addViolations(getPattern(i).validate());
098:
099: return violations;
100: }
101: }
|