Package Torello.HTML

Class HTTPCodes


  • public class HTTPCodes
    extends java.lang.Object
    Keeps lists of the various HTTP Response Codes, made available as String-arrays and Iterator'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" as URL'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 convert String messages to exact integers.

    Please look closely at the description for method convertMessage(Exception) and getCode(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()
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • P1

        🡇     🗕  🗗  🗖
        protected static final java.util.regex.Pattern P1
        A java.util.regex.Pattern that matches the text "HTTP response code: (xxx)" This is the exact String that Java's underlying HTTP exceptions generate.
    • Method Detail

      • iterator

        🡅  🡇     🗕  🗗  🗖
        public static java.util.PrimitiveIterator.OfInt iterator()
        Will return an int-Iterator that iterates the contents of the internal HTTP Codes array.
        Returns:
        A Java Iterator that iterates the known HTTP 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
                    ()
        
        The Iterator returned by this method will simply list each of the category names, and their descriptions, supported by this class.

        View Categories:
        The complete list of HTTPCode Categories (and their Descriptions) may be viewed here, via the link provided below:

        HTTP Code Categories with Descriptions
        Returns:
        An Iterator of HTTP 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();
        
      • printAll

        🡅  🡇     🗕  🗗  🗖
        public static void printAll​(java.lang.Appendable a,
                                    boolean includeDescriptions,
                                    boolean includeCategories,
                                    boolean useUNIXColorCodes)
                             throws java.io.IOException
        This method will print all HTTP Codes to the terminal. This method allows a user to specify a java.lang.Appendable to provide a means to specify where the output text shall be sent. Keep in mind that this standard java interface throws IOException 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 of interface Appendable to have this text sent to just about anywhere. This expects an implementation of Java's java.lang.Appendable interface which allows for a wide range of options when logging intermediate messages.
        Class or Interface InstanceUse & 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:
        The Appendable interface requires that the Checked-Exception IOException be caught when using its append(...) methods.
        includeDescriptions - If this is TRUE, 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 is TRUE - the general category shall be printed next to the code.
        useUNIXColorCodes - if this is set to TRUE - 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 the Shell.C.toHTML(...) method.
        Throws:
        java.io.IOException - The general purpose interface java.lang.Appendable throws an IOException 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 to HTMLPage.getPageTokens(...)
        Returns:
        A java String that may be printed, and includes HTTP-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, or URL 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 an HTTP URL Connection or transfer exception.
        Returns:
        TRUE if the codes passed to this method is found in the code-lookup-table in this class, and FALSE 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 the HTTP Code.

        View Names & Categories:
        The complete list of HTTPCode'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 HTTP Status Code.

        NOTE:If the HTTP 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 proprietary HTTP 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 same HHTP 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 @ the URL 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 of HTTPCode'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 Java Stream of class String. The value here is that a Stream 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. Instead Stream.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 a java.util.stream.Stream of Ret2<String, String>. The Ret2 data-structure allows a return value to contain both a code-name and code-description - as a String 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 an HTTP URL Connection or transfer exception.
        Returns:
        The HTTP "code name and description" pair for a particular Status Code. Most HTTP Code's return a Stream that has only a single-entry. For a few codes, though, multiple definitions (name and description) will be returned.

        The Ret2<String, String> data-structure contains the following two strings:

        • Ret2.a shall contain the code's 'name' as a String.
        • Ret2.b shall contain the code's 'description' as a String.


        A Stream can be easily converted to just about any data-type. Please see the list below for how to convert a java.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. Instead Stream.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)
        Each HTTP Status Code contains a short text-description stored in this library's JAR 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 an HTTP URL Connection or transfer exception.
        Returns:
        The HTTP "code description" for a particular status code.

        NOTE: If the HTTP 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 proprietary HTTP 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 same HTTP 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 @ the URL 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 the HTTP Codes in this class. There is a short int[] array that stores the RFC Number.
        Parameters:
        httpStatusCode - This should be the status code as an integer that is returned from an HTTP URL Connection or transfer exception. Also, any HTTP 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 the HTTP Status Code you have passed is not found in any table, then -1 will be returned.

        ALSO:If '0' is returned, it means that the Status 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 of HTTP Code actually has a name. That name is just a short String stored in a String[] array in this class.

        View Names & Categories:
        The complete list of HTTPCode's and the categories to which they belong may be viewed here:

        HTTP Code Names & Categories

        View Categories:
        The complete list of HTTPCode 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 the name of the first HTTP Status Code number that matches the value of the 'httpStatusCode' parameter as a String. 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 stored HTTP Codes Categories in this class.

        View Categories:
        The complete list of HTTPCode 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 the httpStatusCode parameter, returned as a String. 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 the Category String[] array.
        Parameters:
        httpStatusCode - Any HTTP 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;