001 /*
002 * Copyright 1999-2002,2004 The Apache Software Foundation.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017 package org.apache.commons.latka.validators;
018
019 import org.apache.commons.latka.Validator;
020 import org.apache.commons.latka.ValidationException;
021
022 import org.apache.commons.latka.http.Response;
023
024 import java.text.MessageFormat;
025 /**
026 * FIXME: Docs
027 *
028 * @author Morgan Delagrange
029 * @author dIon Gillard
030 * @version $Id: ByteLengthValidator.java 155424 2005-02-26 13:09:29Z dirkv $
031 */
032 public class ByteLengthValidator extends BaseValidator implements Validator {
033
034 // --------------------------------------------------------------- Attributes
035
036 protected int _minLength = 0;
037 protected int _maxLength = -1;
038
039 protected static final MessageFormat MAX_MESSAGE = new MessageFormat("Expected at most {0,number,integer} bytes. Found {1,number,integer}.");
040 protected static final MessageFormat MIN_MESSAGE = new MessageFormat("Expected at least {0,number,integer} bytes. Found {1,number,integer}.");
041
042 // ------------------------------------------------------------- Constructors
043
044 public ByteLengthValidator() {
045 this(null,0,-1);
046 }
047
048 public ByteLengthValidator(String label) {
049 this(label,0,-1);
050 }
051
052 public ByteLengthValidator(int min, int max) {
053 this(null,min,max);
054 }
055
056 public ByteLengthValidator(String label, int min, int max) {
057 super(label);
058 _minLength = min;
059 _maxLength = max;
060 }
061
062 // ------------------------------------------------------------------ Methods
063
064 public void setMinLength(int length) {
065 _minLength = length;
066 }
067
068 public void setMaxLength(int length) {
069 _maxLength = length;
070 }
071
072 public void validate(Response response)
073 throws ValidationException {
074
075 int byteLength = response.getByteLength();
076
077 if (_maxLength > -1) {
078 if (byteLength > _maxLength) {
079 fail(MAX_MESSAGE.format(new Object[] { new Integer(_maxLength), new Integer(byteLength) }).toString());
080 }
081 }
082
083 if (byteLength < _minLength) {
084 fail(MIN_MESSAGE.format(new Object[] { new Integer(_minLength), new Integer(byteLength) }).toString());
085 }
086 }
087
088 }