Package Torello.HTML
Class HTTPCodes
- java.lang.Object
-
- Torello.HTML.HTTPCodes
-
public class HTTPCodes extends java.lang.Object
Keeps lists of the various HTTP Response Codes, made available asString
-arrays andIterator's
for tasks such as building better exception messages or printing for use as reference.
This is a direct-copy of the content located on Wikipedia's List of Status Codes.
Click to See HTTP Status Codes Page
From Wikipedia, the free encyclopedia, Copyright 2019 - Wikipedia Foundation.
See Current Version: @ the Wikipedia Search Page - Enter: "List of HTTP Status Codes"
The purpose of this class is to store all information about HTTP transfer codes. Generally, this class would be used if a web-crawler were built, and it became enlightening to store that "Result Codes" asURL's
are visited, and content is downloaded. This class makes it easy to convert "Exception Messages" to the exact HTTP-Code that was returned - as an integer. Parsing Java's HTTP Response Exceptions is not difficult, but it is a bit tedious the first time around, and this class saves all the trouble of figuring how to convertString
messages to exact integers.
Please look closely at the description for methodconvertMessage(Exception)
andgetCode(Exception)
Stateless Class:This class neither contains any program-state, nor can it be instantiated. The@StaticFunctional
Annotation may also be called 'The Spaghetti Report'.Static-Functional
classes are, essentially, C-Styled Files, without any constructors or non-static member fields. It is a concept very similar to the Java-Bean's@Stateless
Annotation.
- 1 Constructor(s), 1 declared private, zero-argument constructor
- 17 Method(s), 17 declared static
- 10 Field(s), 10 declared static, 9 declared final
- Fields excused from final modifier (with explanation):
Field 'descriptions' is not final. Reason: LAZY_LOADING
-
-
Field Summary
Fields Modifier and Type Field protected static Pattern
P1
-
Method Summary
HTTP-Exception to Status Code Modifier and Type Method static int
getCode(Exception e)
HTTP-Exception to Message-String Modifier and Type Method static String
convertMessage(Exception e)
static String
convertMessageVerbose(Exception e, URL theAccessedURL, int numTabIndentations)
Retrieve HTTP-Code Information Modifier and Type Method static Stream<Ret2<String,String>>
getAllDescriptions(int httpStatusCode)
static Stream<String>
getAllNames(int httpStatusCode)
static String
getCategoryDescription(int httpStatusCode)
static String
getCategoryName(int httpStatusCode)
static String
getDescription(int httpStatusCode)
static int
getIETF_RFCNumber(int httpStatusCode)
static String
getName(int httpStatusCode)
static boolean
isCode(int httpStatusCode)
Print HTTP-Code Internal-Lists Modifier and Type Method static void
printAll(Appendable a, boolean includeDescriptions, boolean includeCategories, boolean useUNIXColorCodes)
static void
printAllToTermainal(boolean includeDescriptions, boolean includeCategories, boolean useUNIXColorCodes)
Retrieve HTTP-Code Internal-Lists Modifier and Type Method static Iterator<Map.Entry<String,
String>>categoryIterator()
static PrimitiveIterator.OfInt
iterator()
Protected, Utiliity Modifier and Type Method protected static int
getCategoryNum(int httpStatusCode)
protected static void
loadDescriptions()
-
-
-
Method Detail
-
iterator
public static java.util.PrimitiveIterator.OfInt iterator()
Will return anint-Iterator
that iterates the contents of the internal HTTP Codesarray
.- Returns:
- A Java
Iterator
that iterates the knownHTTP Codes
. - Code:
- Exact Method Body:
return IntStream.of(codes).iterator();
-
categoryIterator
public static java.util.Iterator<java.util.Map.Entry<java.lang.String,java.lang.String>> categoryIterator ()
TheIterator
returned by this method will simply list each of the category names, and their descriptions, supported by this class.
View Categories:
The complete list ofHTTPCode
Categories (and their Descriptions) may be viewed here, via the link provided below:HTTP Code Categories with Descriptions
- Returns:
- An
Iterator
ofHTTP Code
category-names and a brief description. - Code:
- Exact Method Body:
LinkedHashMap<String, String> lhm = new LinkedHashMap<>(); for (int i=0; i < categoryNames.length; i++) lhm.put(categoryNames[i], categoryDescriptions[i]); return lhm.entrySet().iterator();
-
printAllToTermainal
public static void printAllToTermainal(boolean includeDescriptions, boolean includeCategories, boolean useUNIXColorCodes)
Convenience Method
Invokes:printAll(Appendable, boolean, boolean, boolean)
Provides:System.out
toAppendable
parameter
Catches:Appendable's IOException
-
printAll
public static void printAll(java.lang.Appendable a, boolean includeDescriptions, boolean includeCategories, boolean useUNIXColorCodes) throws java.io.IOException
This method will print allHTTP Codes
to the terminal. This method allows a user to specify ajava.lang.Appendable
to provide a means to specify where the output text shall be sent. Keep in mind that this standard java interface throwsIOException
if there is any I/O error while printing. Also, if requested, the textual-description of each HTTP-code will also be printed in addition to the code-number and name. If printing descriptions, a small string-data-array will be loaded into java memory.
View Printed Output:
The complete output printed by this method may be viewed with either of the log-print output-files listed below:- Parameters:
a
- This may be any of Java's myriad output-receiving classes, including:PrintStream, Writer, StringBuffer,
etc... Implement an instance ofinterface Appendable
to have this text sent to just about anywhere. This expects an implementation of Java'sjava.lang.Appendable
interface which allows for a wide range of options when logging intermediate messages.Class or Interface Instance Use & Purpose 'System.out'
Sends text to the standard-out terminal Torello.Java.StorageWriter
Sends text to System.out
, and saves it, internally.FileWriter, PrintWriter, StringWriter
General purpose java text-output classes FileOutputStream, PrintStream
More general-purpose java text-output classes
Checked IOException:
TheAppendable
interface requires that the Checked-ExceptionIOException
be caught when using itsappend(...)
methods.includeDescriptions
- If this isTRUE
, then the logic will load the 'descriptions' data-file from this libraries' JAR data-file, and a one or two sentence description will be printed in addition to the number-code and name of each HTTP response.includeCategories
- If this isTRUE
- the general category shall be printed next to the code.useUNIXColorCodes
- if this is set toTRUE
- then UNIX Color codes shall be sent to the terminal. Use this only when sitting in front of a UNIX terminal - as it will slightly skew non-UNIX text output. If using a 'StorageWriter' or similar 'Appendable', converting the colors to HTML<SPAN STYLE='color: ...'> ... </SPAN>
directives can accomplished using theShell.C.toHTML(...)
method.- Throws:
java.io.IOException
- The general purposeinterface java.lang.Appendable
throws anIOException
when printing information. If the appendable provided to this method fails, this exception shall propagate out.- See Also:
C.toHTML(String)
,C.toHTML(String, boolean, boolean, boolean)
,C.BGREEN
,C.BRED
,C.YELLOW
- Code:
- Exact Method Body:
if (includeDescriptions && (descriptions == null)) loadDescriptions(); String catName; final String GR = useUNIXColorCodes ? BGREEN : ""; final String RT = useUNIXColorCodes ? RESET : ""; final String CY = useUNIXColorCodes ? BCYAN : ""; final String RD = useUNIXColorCodes ? BRED : ""; final String YW = useUNIXColorCodes ? BYELLOW : ""; for (int i=0; i < codes.length; i++) a.append( CY + StringParse.zeroPad(codes[i]) + RT + '\t' + YW + names[i] + RT + '\n' + (includeDescriptions ? (GR + "\tDescription: " + RT + descriptions[i] + '\n') : "") + ((includeCategories && ((catName = getCategoryName(codes[i])) != null)) ? (GR + "\tCategory: " + RT + catName + '\n') : (RD + "\tUn-Listed Category") + RT) );
-
getCode
public static int getCode(java.lang.Exception e)
This analyses the message when there is an exception thrown that may have an "identifiable HTTP Response Code." If an identifiable response is code is found, that code is returned as an integer. If one is not found, then-1
shall be returned.- Parameters:
e
- This is expected to be an exception thrown by a call to an HTTP-transfer or scrape. Usually this happens as a result of calls to HTMLPage.getPageTokens(...)- Returns:
- The
HTTP Code
parsed out of the exception's message. - See Also:
isCode(int)
- Code:
- Exact Method Body:
// Some exceptions, apparently, have no message element. if (e.getMessage() == null) return -1; Matcher m = P1.matcher(e.getMessage()); int code = m.find() ? Integer.parseInt(m.group(1)) : -1; if (code > -1) if (HTTPCodes.isCode(code)) return code; return -1;
-
convertMessage
public static java.lang.String convertMessage(java.lang.Exception e)
This just "pretty-prints" the message when there is an exception thrown that has an "identifiable HTTP Response Code." If this method cannot find an "HTTP Status/Response Code," then this method will return null.- Parameters:
e
- This is expected to be an exception thrown by a call to an HTTP-transfer or scrape. Usually this happens as a result of calls toHTMLPage.getPageTokens(...)
- Returns:
- A java
String
that may be printed, and includesHTTP-code, HTTP-code-name
, and category information. If the exception from the parameter doesn't have a decipherable message, this function will return null. - See Also:
getCode(Exception)
,getName(int)
,getCategoryName(int)
- Code:
- Exact Method Body:
int code = getCode(e); if (code != -1) return "HTTP-" + code + ": [" + HTTPCodes.getName(code) + "], " + "Category: " + HTTPCodes.getCategoryName(code); return null;
-
convertMessageVerbose
public static java.lang.String convertMessageVerbose (java.lang.Exception e, java.net.URL theAccessedURL, int numTabIndentations)
Uses a verbose-output print-style.- Parameters:
e
- This is an exception thrown by an HTTP connection, orURL Connection
.theAccessedURL
- This is the URL accessed. It is only required as a parameter because this is "verbose" form of the method, and it is needed for printing-output. If you do use this method, this parameter may not be null.numTabIndentations
- The number of times to indent the message. This number is usually'1'
.- See Also:
convertMessage(Exception)
,EXCC.toString(Throwable, int)
,C.BGREEN
,C.toHTML(String)
- Code:
- Exact Method Body:
String message = HTTPCodes.convertMessage(e); if (numTabIndentations < 0) throw new IllegalArgumentException ("numTabIndentations may not be negative."); String indentations = ""; for (int i=0; i < numTabIndentations; i++) indentations += "\t"; if (message != null) return indentations + message + "\n" + indentations + "Skipping: "+ theAccessedURL.toString(); if ( (e instanceof FileNotFoundException) || (e instanceof UnknownHostException) || (e instanceof IOException) ) return indentations + "Java-Exception: " + e.getClass().getName() + "[" + e.getMessage() + "]\n" + indentations + "Skipping: " + theAccessedURL.toString(); return "\n" + indentations + BGREEN + "UN-COMMON HTTP CONNECTION OR TRANSFER EXCEPTION(S)! STACK TRACE HERE:\n" + RESET + EXCC.toString(e, 1) + BGREEN + indentations + "SKIPPING URL: " + RESET + theAccessedURL.toString();
-
loadDescriptions
protected static void loadDescriptions()
Loads description data from the JAR data-file, unless it has already been loaded.- See Also:
LFEC.readObjectFromFile_JAR(Class, String, boolean, Class)
- Code:
- Exact Method Body:
// Only visit the JAR-file (usually on disk), if the descriptions array still hasn't // been assigned. if (descriptions == null) descriptions = LFEC.readObjectFromFile_JAR (HTTPCodes.class, DESC_DATA_FILE, true, String[].class);
-
isCode
public static boolean isCode(int httpStatusCode)
Checks whether the provided code number is an actual code, according to the internal list of available codes.- Parameters:
httpStatusCode
- This should be the status code as an integer that is returned from anHTTP URL Connection
or transfer exception.- Returns:
TRUE
if the codes passed to this method is found in the code-lookup-table in this class, andFALSE
otherwise.- Code:
- Exact Method Body:
for (int i=0; i < codes.length; i++) if (codes[i] == httpStatusCode) return true; return false;
-
getName
public static java.lang.String getName(int httpStatusCode)
Returns the name of theHTTP Code
.
View Names & Categories:
The complete list ofHTTPCode's
and the categories to which they belong may be viewed here:HTTP Code Names & Categories
- Parameters:
httpStatusCode
- This should be the status code as an integer that is returned from anHTTP URL Connection
or transfer exception.- Returns:
- The HTTP 'code name' for a particular
HTTP Status Code
.
NOTE:If theHTTP Status Code
you have passed is not found in any table, then null will be returned.
There are a few codes that have more than one name/type, and more than one use. Microsoft, Google and other companies have defined proprietaryHTTP Codes
that are not standardized with IETF.
NOTE: This function will return the first code match that is found. If there are two different names/uses for the sameHHTP Code
- then this function will return the name of the standardized-code-use before it returns the name of a non-standardized/proprietary use. Read the list @ theURL
link from Wikipedia at the top of the comments for this class. - Code:
- Exact Method Body:
for (int i=0; i < codes.length; i++) if (codes[i] == httpStatusCode) return names[i]; return null;
-
getAllNames
public static java.util.stream.Stream<java.lang.String> getAllNames (int httpStatusCode)
This will return multiple status-code matches' names - if there are more than one name/description for the status code that you have requested. Generally, most codes are not overloaded, quite the contrary, however as of Wikipedia's 2019 status-code description page, a few companies have created proprietary codes. All matches' names are returned - as a String array.
View Names & Categories:
The complete list ofHTTPCode's
and the categories to which they belong may be viewed here:HTTP Code Names & Categories
- Parameters:
httpStatusCode
- This should be the status code as an integer that is returned from an HTTP URL connection or transfer exception.- Returns:
- The HTTP "code name" for a particular status code. There may be multiple "names"
for a particular
HTTP Code
. This information is returned as a JavaStream
ofclass String
. The value here is that aStream
can be easily converted to just about any data-type.Conversion-Target Stream-Method Invocation String[]
Stream.toArray(String[]::new);
List<String>
Stream.collect(Collectors.toList());
Vector<String>
Stream.collect(Collectors.toCollection(Vector::new));
TreeSet<String>
Stream.collect(Collectors.toCollection(TreeSet::new));
Iterator<String>
Stream.iterator();
NOTE: This method shall never return 'null' - even if the passed'httpStatusCode'
is not found. InsteadStream.empty()
would be returned. - Code:
- Exact Method Body:
// Use java Stream's to build lists - it is usually most efficient, despite how // complicated the java.util.stream.Stream class appears in the API Docs. Stream.Builder<String> b = Stream.builder(); for (int i=0; i < codes.length; i++) if (codes[i] == httpStatusCode) b.add(names[i]); return b.build();
-
getAllDescriptions
public static java.util.stream.Stream<Ret2<java.lang.String,java.lang.String>> getAllDescriptions (int httpStatusCode)
This will return multiple status-code matches' description - if there are more than one name/description for the status code that you have requested. Generally, most codes are not overloaded, quite the contrary, however as of Wikipedia's 2019 status-code description page, a few companies have created proprietary codes. All matches' descriptions are returned - as ajava.util.stream.Stream
ofRet2<String, String>
. TheRet2
data-structure allows a return value to contain both a code-name and code-description - as aString
pair.
Lazy Loading:
If the'descriptions'
data file has not been already loaded into java memory from disk (READ: from the library JAR-file), then calling this method will force this data to load. Since this feature is likely a rarely used feature, this string-data is kept on disk until absolutely needed.- Parameters:
httpStatusCode
- This should be the status code as an integer that is returned from anHTTP URL Connection
or transfer exception.- Returns:
- The HTTP "code name and description" pair for a particular
Status Code
. MostHTTP Code's
return aStream
that has only a single-entry. For a few codes, though, multiple definitions (name and description) will be returned.
TheRet2<String, String>
data-structure contains the following two strings:Ret2.a
shall contain the code's 'name' as aString
.Ret2.b
shall contain the code's 'description' as aString
.
AStream
can be easily converted to just about any data-type. Please see the list below for how to convert ajava.util.stream.Stream
to another data-type.Conversion-Target Stream-Method Invocation Ret2[]
Stream.toArray(Ret2<String, String>[]::new);
List<Ret2>
Stream.collect(Collectors.toList());
Vector<Ret2>
Stream.collect(Collectors.toCollection(Vector::new));
TreeSet<Ret2>
Stream.collect(Collectors.toCollection(TreeSet::new));
Iterator<Ret2>
Stream.iterator();
NOTE: This method shall never return 'null' - even if the passed'httpStatusCode'
is not found. InsteadStream.empty()
would be returned. - Code:
- Exact Method Body:
if (descriptions == null) loadDescriptions(); Stream.Builder<Ret2<String, String>> b = Stream.builder(); for (int i=0; i < codes.length; i++) if (codes[i] == httpStatusCode) b.add(new Ret2<String, String>(names[i], descriptions[i])); return b.build();
-
getDescription
public static java.lang.String getDescription(int httpStatusCode)
EachHTTP Status Code
contains a short text-description stored in this library'sJAR File
. Upon request, the data-file to memory.
View HTTP Code Descriptions:
To view the the descriptions that shall be returned by this method, see the link provided below:HTTP Codes & Descriptions
- Parameters:
httpStatusCode
- This should be the status code as an integer that is returned from anHTTP URL Connection
or transfer exception.- Returns:
- The HTTP "code description" for a particular status code.
NOTE: If theHTTP Status Code
you have passed is not found in any table, then null will be returned.
There are a few codes that have more than one description, and more than one use. Microsoft, Google and other companies have defined proprietaryHTTP Codes
that are not standardized with IETF.
NOTE: This function will return the description from the first code match that it find. If there are two different versions of the sameHTTP Code
, this function will return the description of the standardized-code-use before it returns the description from a non-standardized/proprietary one. Read the list @ theURL
link from Wikipedia at the top of the comments for this class. - See Also:
loadDescriptions()
- Code:
- Exact Method Body:
if (descriptions == null) loadDescriptions(); for (int i=0; i < codes.length; i++) if (codes[i] == httpStatusCode) return descriptions[i]; return null;
-
getIETF_RFCNumber
public static int getIETF_RFCNumber(int httpStatusCode)
The Internet Engineering Task Force provides RFC Numbers for most of theHTTP Codes
in this class. There is a shortint[] array
that stores the RFC Number.- Parameters:
httpStatusCode
- This should be the status code as an integer that is returned from anHTTP URL Connection
or transfer exception. Also, anyHTTP Status Code
that is proprietary, by definition of RFC, there will be no RFC found. Only agreed-upon and standardized codes have RFC's to return here.- Returns:
- If this particular
HTTP Status Code
has a documented RFC number, that number will be returned.
NOTE:If theHTTP Status Code
you have passed is not found in any table, then-1
will be returned.
ALSO:If'0'
is returned, it means that theStatus Code
was found, but it did not have an RFC number associated with it. - Code:
- Exact Method Body:
for (int i=0; i < codes.length; i++) if (codes[i] == httpStatusCode) return rfcs[i]; return -1;
-
getCategoryName
public static java.lang.String getCategoryName(int httpStatusCode)
Each Category ofHTTP Code
actually has a name. That name is just a shortString
stored in aString[] array
in this class.
View Names & Categories:
The complete list ofHTTPCode's
and the categories to which they belong may be viewed here:HTTP Code Names & Categories
View Categories:
The complete list ofHTTPCode
Categories (and their Descriptions) may be viewed here, via the link provided below:HTTP Code Categories with Descriptions
- Parameters:
httpStatusCode
- This should be the status code as an integer that is returned from anHTTP URL Connection
or transfer exception.- Returns:
- This will return the name of the first HTTP Status Code number that matches the
value of the
'httpStatusCode'
parameter as aString
. If the value in'httpStatusCode'
is not a valid code, null will be returned. The first match is always the one for which conventions have been standardized, rather than proprietary codes by corporations. - See Also:
getCategoryName(int)
- Code:
- Exact Method Body:
int categoryNum = getCategoryNum(httpStatusCode); return (categoryNum == -1) ? null : categoryNames[categoryNum];
-
getCategoryDescription
public static java.lang.String getCategoryDescription(int httpStatusCode)
This class provides a short description of each of the storedHTTP Codes Categories
in this class.
View Categories:
The complete list ofHTTPCode
Categories (and their Descriptions) may be viewed here, via the link provided below:HTTP Code Categories with Descriptions
- Parameters:
httpStatusCode
- This should be the status code as an integer that is returned from an HTTP URL connection or transfer exception.- Returns:
- This will return a description of the first
HTTP Status Code
number that matches the value of thehttpStatusCode
parameter, returned as aString
. If the value in'httpStatusCode'
is not a valid code, null will be returned. If there are more than one categories in which this code may be placed, the first found will be returned. The first match is always the one for which conventions have been standardized, rather than proprietary codes by corporations. - See Also:
getCategoryNum(int)
- Code:
- Exact Method Body:
int categoryNum = getCategoryNum(httpStatusCode); return (categoryNum == -1) ? null : categoryNames[categoryNum];
-
getCategoryNum
protected static int getCategoryNum(int httpStatusCode)
The "Category Number" is just an integer-index into theCategory String[] array
.- Parameters:
httpStatusCode
- AnyHTTP Status Code
contained by this class.- Returns:
- The
String[] array
index for the 'Category' of this'httpStatusCode'
- Code:
- Exact Method Body:
int codeArrPos = -1; // The arrays are parallel, this find the "array position" of the status code // (or returns -1, if it isn't a code) for (int i=0; i < codes.length; i++) if (codes[i] == httpStatusCode) { codeArrPos = i; break; } // If the status code wasn't found, then return -1 if (codeArrPos == -1) return -1; // Find which category to which this code belongs... The "starting-point array-position // array" (a mouthful) tells where each section starts (and ends... because end of one // section, is the start of the next) int categoryNum=0; while ( (categoryNum < categoryStartPoints.length) && (codeArrPos >= categoryStartPoints[categoryNum]) ) categoryNum++; // The minus is because the counter will have already incremented when the loop breaks! return categoryNum - 1;
-
-