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    /**
027     * Validates a Response according to its HTTP status code
028     * (200, 301, 302, 404, etc).  Note: by default, Latka 
029     * will automatically follow redirects.  If you want to
030     * test for a 301 or 302 response, you will need to
031     * set followRedirects="false" on the Latka request. 
032     * 
033     * @author Morgan Delagrange
034     * @author dIon Gillard
035     * @version $Id: StatusCodeValidator.java 155424 2005-02-26 13:09:29Z dirkv $
036     */
037    public class StatusCodeValidator extends BaseValidator implements Validator {
038    
039      // --------------------------------------------------------------- Attributes
040    
041      protected static final MessageFormat MESSAGE = new MessageFormat("Expected status code \"{0,number,000}\". Found \"{1,number,000}\".");
042      protected int _statusCode = 200;
043    
044      // ------------------------------------------------------------- Constructors
045    
046      public StatusCodeValidator() {
047        this(null,200);
048      }
049    
050      public StatusCodeValidator(int code) {
051        this(null,code);
052      }
053    
054      public StatusCodeValidator(String label) {
055        this(label,200);
056      }
057    
058      public StatusCodeValidator(String label, int code) {
059        super(label);
060        _statusCode = code;
061      }
062    
063      // ------------------------------------------------------------------ Methods
064    
065      public void setStatusCode(int statusCode) {
066        _statusCode = statusCode;
067      }
068    
069      public void validate(Response response)
070        throws ValidationException {
071    
072        int responseStatusCode = response.getStatusCode();
073    
074        if (_statusCode != responseStatusCode) {
075           fail(MESSAGE.format(new Object[] { new Integer(_statusCode), new Integer(responseStatusCode) }).toString());
076        }
077      }
078    }