001 /*
002 * Copyright 2003-2008 the original author or authors.
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 * You are receiving this code free of charge, which represents many hours of
017 * effort from other individuals and corporations. As a responsible member
018 * of the community, you are asked (but not required) to donate any
019 * enhancements or improvements back to the community under a similar open
020 * source license. Thank you. -TMN
021 */
022 package groovyx.net.http;
023
024 /**
025 * Mapping of HTTP response codes to a constant 'success' or 'failure' value.
026 * @author <a href='mailto:tnichols@enernoc.com'>Tom Nichols</a>
027 */
028 public enum Status {
029 /** Any status code >= 100 and < 400 */
030 SUCCESS ( 100, 399 ),
031 /** Any status code >= 400 and < 1000 */
032 FAILURE ( 400, 999 );
033
034 private final int min, max;
035
036 @Override public String toString() {
037 return super.toString().toLowerCase();
038 }
039
040 /**
041 * Returns true if the numeric code matches the represented status (either
042 * <code>success</code> or <code>failure</code>). i.e.
043 * <pre>
044 * assert Status.SUCCESS.matches(200);
045 * assert Status.FAILURE.matches(404);
046 * </pre>
047 * @param code numeric HTTP code
048 * @return true if the numeric code represents this enums success or failure
049 * condition
050 */
051 public boolean matches( int code ) {
052 return min <= code && code <= max;
053 }
054
055 /**
056 * Find the Status value that matches the given status code.
057 * @param code HTTP response code
058 * @return a 'success' or 'failure' Status value
059 * @throws IllegalArgumentException if the given code is not a valid HTTP
060 * status code.
061 */
062 public static Status find( int code ) {
063 for ( Status s : Status.values() )
064 if ( s.matches( code ) ) return s;
065 throw new IllegalArgumentException( "Unknown status: " + code );
066 }
067
068 private Status( int min, int max ) {
069 this.min = min; this.max = max;
070 }
071 }