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'sfor 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'sare 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 convertStringmessages 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@StaticFunctionalAnnotation may also be called 'The Spaghetti Report'.Static-Functionalclasses are, essentially, C-Styled Files, without any constructors or non-static member fields. It is a concept very similar to the Java-Bean's@StatelessAnnotation.
- 1 Constructor(s), 1 declared private, zero-argument constructor
- 18 Method(s), 18 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 PatternP1
-
Method Summary
HTTP-Exception to Status Code Modifier and Type Method static intgetCode(Exception e)HTTP-Exception to Message-String Modifier and Type Method static StringconvertMessage(Exception e)static StringconvertMessageVerbose(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 StringgetCategoryDescription(int httpStatusCode)static StringgetCategoryName(int httpStatusCode)static StringgetDescription(int httpStatusCode)static intgetIETF_RFCNumber(int httpStatusCode)static StringgetName(int httpStatusCode)static booleanisCode(int httpStatusCode)Print HTTP-Code Information Modifier and Type Method static StringcodeToString(int httpStatusCode, int maxLineLen)Print HTTP-Code Internal-Lists Modifier and Type Method static voidprintAll(Appendable a, boolean includeDescriptions, boolean includeCategories, boolean useUNIXColorCodes)static voidprintAllToTermainal(boolean includeDescriptions, boolean includeCategories, boolean useUNIXColorCodes)Retrieve HTTP-Code Internal-Lists Modifier and Type Method static Iterator<Map.Entry<String,
String>>categoryIterator()static PrimitiveIterator.OfIntiterator()Protected, Utiliity Modifier and Type Method protected static intgetCategoryNum(int httpStatusCode)protected static voidloadDescriptions()
-
-
-
Field Detail
-
P1
protected static final java.util.regex.Pattern P1
Ajava.util.regex.Patternthat matches the text"HTTP response code: (xxx)"This is the exactStringthat Java's underlying HTTP exceptions generate.- Code:
- Exact Field Declaration Expression:
protected static final Pattern P1 = Pattern.compile ("HTTP response code: (\\d\\d\\d)", Pattern.CASE_INSENSITIVE);
-
-
Method Detail
-
iterator
public static java.util.PrimitiveIterator.OfInt iterator()
Will return anint-Iteratorthat iterates the contents of the internal HTTP Codesarray.- Returns:
- A Java
Iteratorthat 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 ()TheIteratorreturned by this method will simply list each of the category names, and their descriptions, supported by this class.
View Categories:
The complete list ofHTTPCodeCategories (and their Descriptions) may be viewed here, via the link provided below:HTTP Code Categories with Descriptions- Returns:
- An
IteratorofHTTP Codecategory-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.outtoAppendableparameter
Catches:Appendable's IOException- Code:
- Exact Method Body:
try { printAll(System.out, includeDescriptions, includeCategories, useUNIXColorCodes); } catch (IOException e) { }
-
printAll
public static void printAll(java.lang.Appendable a, boolean includeDescriptions, boolean includeCategories, boolean useUNIXColorCodes) throws java.io.IOExceptionThis method will print allHTTP Codesto the terminal. This method allows a user to specify ajava.lang.Appendableto provide a means to specify where the output text shall be sent. Keep in mind that this standard java interface throwsIOExceptionif 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 Appendableto have this text sent to just about anywhere. This expects an implementation of Java'sjava.lang.Appendableinterface 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.StorageWriterSends text to System.out, and saves it, internally.FileWriter, PrintWriter, StringWriterGeneral purpose java text-output classes FileOutputStream, PrintStreamMore general-purpose java text-output classes
Checked IOException:
TheAppendableinterface requires that the Checked-ExceptionIOExceptionbe 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.Appendablethrows anIOExceptionwhen 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 + StrPrint.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-1shall 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 Codeparsed 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
Stringthat 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:
final 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 Connectionor transfer exception.- Returns:
TRUEif the codes passed to this method is found in the code-lookup-table in this class, andFALSEotherwise.- 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'sand 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 Connectionor transfer exception.- Returns:
- The HTTP 'code name' for a particular
HTTP Status Code.If theHTTP Status Codeyou 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 Codesthat are not standardized with IETF.
This function will return the description from the first Code-Match that it finds. 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 @ theURLlink 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'sand 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 JavaStreamofclass String. The value here is that aStreamcan 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();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.StreamofRet2<String, String>. TheRet2data-structure allows a return value to contain both a code-name and code-description - as aStringpair.
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 Connectionor transfer exception.- Returns:
- The HTTP "code name and description" pair for a particular
Status Code. MostHTTP Code'sreturn aStreamthat 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.ashall contain the code's 'name' as aString.Ret2.bshall contain the code's 'description' as aString.
AStreamcan be easily converted to just about any data-type. Please see the list below for how to convert ajava.util.stream.Streamto 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 Codecontains 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 Connectionor transfer exception.- Returns:
- The HTTP "code description" for a particular status code.
If the
HTTP Status Codeyou 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 Codesthat are not standardized with IETF.
This function will return the description from the first Code-Match that it finds. 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 @ theURLlink 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 Codesin this class. There is a shortint[] arraythat stores the RFC Number.- Parameters:
httpStatusCode- This should be the status code as an integer that is returned from anHTTP URL Connectionor transfer exception. Also, anyHTTP Status Codethat 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 Codehas a documented RFC number, that number will be returned.If theHTTP Status Codeyou have passed is not found in any table, then-1will be returned.
If'0'is returned, it means that theStatus Codewas 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 Codeactually has a name. That name is just a shortStringstored in aString[] arrayin this class.
View Names & Categories:
The complete list ofHTTPCode'sand the categories to which they belong may be viewed here:HTTP Code Names & Categories
View Categories:
The complete list ofHTTPCodeCategories (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 Connectionor 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 Categoriesin this class.
View Categories:
The complete list ofHTTPCodeCategories (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 Codenumber that matches the value of thehttpStatusCodeparameter, 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 : categoryDescriptions[categoryNum];
-
codeToString
public static java.lang.String codeToString(int httpStatusCode, int maxLineLen)This is a modified version of methodconvertMessage(Exception). The text output returned by this method includes more information. Please review the method body to see exactly what is generated and returned.- Parameters:
httpStatusCode- The Code to Convert to a thoughtfully worded message.maxLineLen- Lines of text within the returned String that would be longer than'maxLineLen'are wrapped, usingStrPrint.wrapToIndentationPlus(String, int, int, int).If a negative number is passed to this method, then no text wrapping is used.If a number between '0' and '24' is passed, this method shall throw anIllegalArgumentException.- Returns:
- A String-Representation of the HTTP Status-Code / Error-Code.
- Throws:
java.lang.IllegalArgumentException- If'maxLineLen'is passed a value between and'24'.- Code:
- Exact Method Body:
if (! HTTPCodes.isCode(httpStatusCode)) throw new IllegalArgumentException ("The integer passed to 'httpStatusCode' is not valid, or is an unknown Status-Code"); final boolean negative = maxLineLen < 0; if ((! negative) && (maxLineLen < 25)) throw new IllegalArgumentException( "You have passed [" + maxLineLen + "] to 'maxLineLen', but this value may not be " + "[0] and [24]" ); // final int LEN = "Category-Description: ".length(); final int LEN = 22; final int c = httpStatusCode; // makes it easier to read, that's all! final String descStr = HTTPCodes.getDescription(c); final String cDescStr = HTTPCodes.getCategoryDescription(c); final String desc = negative ? descStr : StrPrint.wrapToIndentationPlus(descStr, maxLineLen, maxLineLen, LEN); final String cDesc = negative ? cDescStr : StrPrint.wrapToIndentationPlus(cDescStr, maxLineLen, maxLineLen, LEN); return BCYAN + "HTTP-Code: " + RESET + c + '\n' + BCYAN + "Name: " + RESET + HTTPCodes.getName(c) + '\n' + BCYAN + "Description: " + RESET + desc + '\n' + BCYAN + "Category: " + RESET + HTTPCodes.getCategoryName(c) + '\n' + BCYAN + "Category-Description: " + RESET + cDesc + '\n';
-
getCategoryNum
protected static int getCategoryNum(int httpStatusCode)
The "Category Number" is just an integer-index into theCategory String[] array.- Parameters:
httpStatusCode- AnyHTTP Status Codecontained by this class.- Returns:
- The
String[] arrayindex 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;
-
-