Package Torello.Java

Class LFEC


  • public class LFEC
    extends java.lang.Object
    LFEC: Load File Exception Catch - Documentation.

    The primary reason for this class is to prevent continuing, and ensure that as much relevant information is printed in the event of a lost or corrupted data-file. Generally, if a data-file does not load, it is best to halt the program immediately, and completely. Load File Exception Catch halts the program, prints exception information, and then just calls Java's System.exit(0); command.

    NOTE: The JAR implies that the "load resource as stream" function is being used in place of standard file i/o routines. Specifically, this loads from a Jar file!

    Java Line of Code:
    1
    BufferedReader br = new BufferedReader(new InputStreamReader(c.getResourceAsStream(f)));
    


    Example:
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    // It is required that the text-file "myDataFile.txt" is located in the same directory
    // as the ".java" and ".class" file as "this" (object) is.  This line will halt program execution if loading fails.
    String dataFileStr = LFEC.loadFile_JAR(this.class, "myDataFile.txt");
    
    // Print the contents of the data file to the terminal.
    System.out.println("Data File Contains:\n" + dataFileStr);
    
    
    // THIS EXAMPLE IS FOUND IN THE HiLiteMe class - How to load a data-file, and make sure error-information is printed.
    public class HiLiteMe
    ...
        // **************************************************************************************************************************
        // HiLite.ME parameter-tags stored internally.
        // **************************************************************************************************************************
        private static final Vector<Object>           dataFile              = (Vector<Object>) LFEC.readObjectFromFile_JAR
            (Torello.Data.DataFileLoader.class, "data06.vdat", true, Vector.class.getName());
        
        private static final TreeMap<String, String>  codeTypeDescriptions  = (TreeMap<String, String>) dataFile.elementAt(0);
        private static final Vector<String>           styleTypes            = (Vector<String>) dataFile.elementAt(1);
    
    
    
    // THIS EXAMPLE IS FOUND IN THE JavaDocAssis class - Loading an internal data-file, and ensuring success, or halting immediately
    // and printing a standardized error message.
    public class JavaDocAssist
    ...
        // Load the data-file.  It is simply, very-mundane sort of fashion, called "data05.vdat"
        private static final Vector<Object> v = (Vector<Object>) LFEC.readObjectFromFile_JAR
            (Torello.Data.DataFileLoader.class, "data05.vdat", true, Vector.class.getName());
    


    NOTE: It might be important to read the Java Doc's about the java.lang.Class.getResourceAsStream(String) method for retrieving data that was stored to a JAR file instead of a UNIX/BASH/MS-DOS system file. A copy of Oracle's Java 8 documentation is listed at the top of this class.

    Static (Functional) API: The methods in this class are all (100%) defined with the Java Key-Word / Key-Concept 'static'. Furthermore, there is no way to obtain an instance of this class, because there are no public (nor private) constructors. Java's Spring-Boot, MVC feature is *not* utilized because it flies directly in the face of the light-weight data-classes philosophy. This has many advantages over the rather ornate Component Annotations (@Component, @Service, @AutoWired, etc... 'Java Beans') syntax:

    • The methods here use the key-word 'static' which means (by implication) that there is no internal-state. Without any 'internal state' there is no need for constructors in the first place! (This is often the complaint by MVC Programmers).
    • A 'Static' (Functional-Programming) API expects to use fewer data-classes, and light-weight data-classes, making it easier to understand and to program.
    • The Vectorized HTML data-model allows more user-control over HTML parse, search, update & scrape. Also, memory management, memory leakage, and the Java Garbage Collector ought to be intelligible through the 'reuse' of the standard JDK class Vector for storing HTML Web-Page data.

    The power that object-oriented programming extends to a user is (mostly) limited to data-representation. Thinking of "Services" as "Objects" (Spring-MVC, 'Java Beans') is somewhat 'over-applying' the Object Oriented Programming Model. Like most classes in the Java-HTML JAR Library, this class backtracks to a more C-Styled Functional Programming Model (no Objects) - by re-using (quite profusely) the key-word static with all of its methods, and by sticking to Java's well-understood class Vector

    Internal-State: A user may click on this class' source code (see link below) to view any and all internally defined fields class. A cursory inspection of the code would prove that this class has precisely zero internally defined global fields (Spaghetti). All variables used by the methods in this class are local fields only, and therefore this class ought to be though of as 'state-less'.



    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class
      static class  LFEC.GCSSB
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method
      protected static void ERROR_EXIT​(String message)
      protected static void ERROR_EXIT​(Throwable t, String message)
      static String loadFile​(String f)
      static String loadFile_JAR​(Class<?> classLoaderClass, String f)
      static Vector<String> loadFileToVector​(String f, boolean includeNewLine)
      static Vector<String> loadFileToVector_JAR​(Class<?> classLoaderClass, String f, boolean includeNewLine)
      static <T> T readObjectFromFile​(String f, boolean zip, Class<T> returnClass)
      static <T> T readObjectFromFile_JAR​(Class<?> classLoaderClass, String f, boolean zip, Class<T> returnClass)
      • Methods inherited from class java.lang.Object

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

      • ERROR_EXIT

        protected static void ERROR_EXIT​(java.lang.Throwable t,
                                         java.lang.String message)
        This prints a message and a location and halts the current thread immediately. (Halts the program) The entire rational behind the class LFEC is to facilitate loading data-files, and forcing an immediate program halt if this operation fails. Generally, during development and debugging, failing to read from a data-file is serious enough to warrant stopping the software until the issue is fixed. "Hobbling along without reading the data-files" makes little sense.

        When the software is being released or distributed, the philosophy turns to loading mission critical data out of data-files in a java jar-file. If the jar-file is corrupted and those files are not present, generally this situation would also warrant halting the program execution immediately until the jar file is fixed.
        Parameters:
        t - An exception, error or other Throwable that generated a problem when attempting to read a data-file.
        message - This is an internally generated message explaining what has occurred.
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
         System.out.println(
             "There was an error loading a data-file, and program-execution is being halted immediately.\n" +
             "Problem Encountered With:\t" + message + "\n\n" +
             "Exception or Error Message:\n" + 
             "t.getMessage():\t\t\t" + t.getMessage() + "\n" +
             "t.getLocalizedMessage():\t" + t.getLocalizedMessage() + "\n" +
             EXCC.toString(t) + "\n\n" +
             "Exiting Program, Fatal Error Loading Critical Data File."
         );
        
         System.exit(0);
        
      • ERROR_EXIT

        protected static void ERROR_EXIT​(java.lang.String message)
        This prints a message and a location and halts the current thread immediately. (Halts the program) The entire rational behind the class LFEC is to facilitate loading data-files, and forcing an immediate program halt if this operation fails. Generally, during development and debugging, failing to read from a data-file is serious enough to warrant stopping the software until the issue is fixed. "Hobbling along without reading the data-files" makes little sense.

        When the software is being released or distributed, the philosophy turns to loading mission critical data out of data-files in a java jar-file. If the jar-file is corrupted and those files are not present, generally this situation would also warrant halting the program execution immediately until the jar file is fixed.
        Parameters:
        message - This is an internally generated message explaining what has occurred.
        Code:
        Exact Method Body:
        1
        2
        3
        4
        5
        6
        7
         System.out.println(
             "There was an error loading a data-file, and program-execution is being halted immediately.\n" +
             "Problem Encountered With:\n" + message + "\n\n" +
             "Exiting Program, Fatal Error Loading Critical Data File."
         );
        
         System.exit(0);
        
      • loadFile

        public static java.lang.String loadFile​(java.lang.String f)
        Loads a file directly into a java-String. If this file fails to load, it halts the run-time environment.
        Parameters:
        f - This is a java.lang.String that contains the filename.
        Returns:
        The returned String contains the entire contents of the file.
        See Also:
        FileRW.loadFileToString(String), ERROR_EXIT(Throwable, String)
        Code:
        Exact Method Body:
        1
        2
        3
        4
        5
        6
         try
             { return FileRW.loadFileToString(f);                    }
         catch (Throwable t)
             { ERROR_EXIT(t, "FileRW.loadFileToString(" + f + ")");  }
        
         return null; // Should not be possible to reach this statement
        
      • loadFile_JAR

        public static java.lang.String loadFile_JAR​
                    (java.lang.Class<?> classLoaderClass,
                     java.lang.String f)
        
        Loads a file directory to a string from a java jar-file. It halts the program, and prints a detailed message if any Error's or Exception's were thrown. The directory inside the jar-file where this file may be located identified by parameter class 'classLoaderClass'.
        Parameters:
        classLoaderClass - This contains the 'class' that will be used by Java's java.lang.Class.getResourceAsStream(...); method. Please see the comments at the top of this class-documentation page for a better explanation of how Java's class-loader uses a 'java.lang.Class<E>' object to find data-files (which java calls 'resources') inside of a jar-file. All that is really going on is that as classes are loaded by the class-loader from the file-system and from jar-files - the class-loader actually remembers which jar-file's and which directories inside the jar-files contained any/all class-definitions ('.class' files) that were loaded from jar files instead of the file-system.

        This parameter class 'c' points to a jar-file and directory combination that will contain the date-file named/identified by the next parameter String 'f'.

        NOTE: The symbols <?> appended to the (almost) 'raw-type' here, are only there to prevent the java-compiler from issuing warnings regarding the use of "Raw Types." This warning is, actually, only issued if the command-line option -Xlint:all option is used.
        f - This is a String that contains the filename of the data-file that needs to be loaded. It is a 'relative file-name' that is relative to the jar-file / directory pair location that the class loader identifies using the Class from parameter 'c'
        Returns:
        The returned string contains the entire contents of the file.
        See Also:
        ERROR_EXIT(Throwable, String)
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
         try {
             InputStream     is  = classLoaderClass.getResourceAsStream(f);
             BufferedReader  br  = new BufferedReader(new InputStreamReader(is));
             String          s   = "";
             StringBuffer    sb  = new StringBuffer();
        
             while ((s = br.readLine()) != null) sb.append(s + "\n");
        
             is.close();
             return sb.toString();
         }
         catch (Throwable t)
         {
             ERROR_EXIT(t,
                 "Error loading text-file [" + f + "] from jar-file.\n" +
                 "Class loader attempted to use information in class " +
                 "[" + classLoaderClass.getCanonicalName() + "], but failed."
             );
         }
         return null; // Should NOT be possible to reach this statement...
        
      • loadFileToVector

        public static java.util.Vector<java.lang.String> loadFileToVector​
                    (java.lang.String f,
                     boolean includeNewLine)
        
        This loads a file to a Vector of String's. It halts the program, and prints a detailed message if any errors or exceptions occur.
        Parameters:
        f - The name of the file to load
        includeNewLine - States whether the '\n' (new-line) character should be appended to each element of the returned Vector<String>.
        Returns:
        a Vector of String's, where each element in the Vector is a line retrieved from the text-file.
        See Also:
        ERROR_EXIT(Throwable, String)
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
         try
             { return FileRW.loadFileToVector(f, includeNewLine); }
         catch (Throwable t)
         {
             ERROR_EXIT(t, 
                 "Text-File Load Method Used Was:\n" +
                 "FileRW.loadFileToVector(" + f + ", " + includeNewLine + ");"
             );
         }
        
         return null; // Should NOT be possible to reach this statement...
        
      • loadFileToVector_JAR

        public static java.util.Vector<java.lang.String> loadFileToVector_JAR​
                    (java.lang.Class<?> classLoaderClass,
                     java.lang.String f,
                     boolean includeNewLine)
        
        This loads a file to a Vector of String's. It halts the program, and prints a detailed message if any Error's or Exception's occur. The directory inside the jar-file where this file may be located identified by parameter java.lang.Class<?> 'classLoaderClass'.
        Parameters:
        classLoaderClass - This contains the 'class' that will be used by Java's java.lang.Class.getResourceAsStream(...); method. Please see the comments at the top of this class-documentation page for a better explanation of how Java's class-loader uses a 'java.lang.Class<E>' object to find data-files (which java calls 'resources') inside of a jar-file. All that is really going on is that as classes are loaded by the class-loader from the file-system and from jar-files - the class-loader actually remembers which jar-file's and which directories inside the jar-files contained any/all class-definitions ('.class' files) that were loaded from jar files instead of the file-system.

        This parameter class 'c' points to a jar-file and directory combination that will contain the date-file named/identified by the next parameter String 'f'.

        NOTE: The symbols <?> appended to the (almost) 'raw-type' here, are only there to prevent the java-compiler from issuing warnings regarding the use of "Raw Types." This warning is, actually, only issued if the command-line option -Xlint:all option is used.
        f - This is a String that contains the filename of the data-file that needs to be loaded. It is a 'relative file-name' that is relative to the jar-file / directory pair location that the class loader identifies using the Class from parameter 'c'.
        includeNewLine - States whether the '\n' (newline) character should be appended to each element of the Vector.
        Returns:
        a Vector of String's, where each element in the Vector is a line retrieved from the text-file.
        See Also:
        ERROR_EXIT(Throwable, String)
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
         try {
             InputStream     is  = classLoaderClass.getResourceAsStream(f);
             BufferedReader  br  = new BufferedReader(new InputStreamReader(is));
             String          s   = "";
             Vector<String>  ret = new Vector<>();
        
             if (includeNewLine)     while ((s = br.readLine()) != null)     ret.addElement(s + '\n');
             else                    while ((s = br.readLine()) != null)     ret.addElement(s);
        
             is.close();
             return ret;
         }
         catch (Throwable t)
         {
             ERROR_EXIT(t,
                 "Error loading text-file [" + f + "] from jar-file.\n" +
                 "Parameter includeNewLine was: " + includeNewLine + "\n" +
                 "Class loader attempted to use information in class " +
                 "[" + classLoaderClass.getCanonicalName() + "], but failed."
             );
         }
        
         return null; // Should NOT be possible to reach this statement...
        
      • readObjectFromFile

        public static <T> T readObjectFromFile​(java.lang.String f,
                                               boolean zip,
                                               java.lang.Class<T> returnClass)
        This loads a java.lang.Object from a data-file.

        NOTE: This will load ONLY ONE java.lang.Object from the specified data-file located in a JAR file. If you wish to save multiple Object's to a data-file, the best way to achieve this is to put however many other data-Object's you wish to store into a Serializable instance of a class java.util.Collection<E> (a "top-level" container) and then save that container to a serialized-Object file.

        Retrieving, for instance, data-Object's out of a java.util.Vector<Object> that had been saved to a file (inside a JAR-file) via the interface java.io.Serializable will require re-casting the Object's that were inserted into the Collection (again, for-example, a java Vector<E>. The modicum of effort needed to re-cast Object's to their proper class is quite worth-it because data-reads and data-writes using JAR's remain very simple.

        GENERICS-ERASURE: Because Java's Generic Classes (where the type-parameter 'E', as in java.util.Vector<E>, is used) are not maintained at run-time, the compiler issues warnings when casting a Raw-Type to it's 'specified-type' whether or not a check is actually needed. Unfortunately, this is not possible when reading / de-serializing an Object since the instanceof operator cannot be used. It is, therefore, necessary to use the @SuppressWarnings("unchecked") Annotation to read & de-serialize Java Generics from disk, as below:

        Example:
        1
        2
        3
        4
        5
        6
        // Use the following Java 'Annotation' (Suppress Warnings)
        // This will allow the programmer to cast the "Raw-Type" Vector, to a Vector<String>
        
        @SuppressWarnings("unchecked")
        private static final Vector<String> data = (Vector<String>) LFEC.readObjectFromFile_JAR
            (DataFileLoader.class, "dataFile.sdat", true, Vector.class);
        
        Parameters:
        f - The name of the file containing a serialized java.lang.Object to load
        zip - This should be TRUE if, when serialized, the Object was compressed too, and FALSE if compression was not used.
        returnClass - This java.lang.Class<E> should be used to indicate what the type of the java.lang.Object that has been written to the file named by input-parameter String f. When the object is read from disk and de-serialized, the type of the instance shall be checked against this class.

        FOR EXAMPLE: If a Vector containing String's were last written to data-file 'f', then invoking this method to retrieve that Vector<String> would require passing 'Vector.class' to this parameter.

        IMPORTANT This method will halt program execution if after reading an instance from the data-file, the resulting class-name obtained from the instance that was read produces as class-name that is not equal to or, rather, does not inherit from the class passed to 'returnClass'. The logic, or purpose, to this check is to add a layer of data-file integrity check to this class LFEC (Load-File-Exception-Catch).
        Returns:
        A de-serialized java.lang.Object present in the data-file passed by-name through file-name parameter 'f', and cast to the type denoted by parameter returnClass.
        See Also:
        FileRW.readObjectFromFile(String, boolean), ERROR_EXIT(Throwable, String)
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
         try {
             Object ret = FileRW.readObjectFromFile(f, zip);
        
             if (! returnClass.isInstance(ret))
                 ERROR_EXIT(
                     "Serialized Object from file: " + f + "\n" +
                     "Using expected (" + (zip ? "zip-compression" : "no-compression") + ")\n" +
                     "Didn't have an object with class-name: [" + returnClass + "]\n" +
                     "but rather with class-name: [" + ret.getClass().getName() + "]"
                 );
        
             return returnClass.cast(ret);
         }
         catch (Exception e)
         {
             ERROR_EXIT(
                 "Exception reading Serialized Object from file: " + f + "\n" +
                 "With intended read class-name of: " + returnClass + "\n" +
                 "Using expected (" + (zip ? "zip-compression" : "no-compression") + ")\n" +
                 "Experienced an Exception:\n" + EXCC.toString(e)
             );
         }
        
         return null; // Should NOT be possible to reach this statement...
        
      • readObjectFromFile_JAR

        public static <T> T readObjectFromFile_JAR​
                    (java.lang.Class<?> classLoaderClass,
                     java.lang.String f,
                     boolean zip,
                     java.lang.Class<T> returnClass)
        
        This loads a java.lang.Object from a data-file located in a JAR File.

        NOTE: This will load ONLY ONE java.lang.Object from the specified data-file located in a JAR file. If you wish to save multiple Object's to a data-file, the best way to achieve this is to put however many other data-Object's you wish to store into a Serializable instance of a class java.util.Collection<E> (a "top-level" container) and then save that container to a serialized-Object file.

        Retrieving, for instance, data-Object's out of a java.util.Vector<Object> that had been saved to a file (inside a JAR-file) via the interface java.io.Serializable will require re-casting the Object's that were inserted into the Collection (again, for-example, a java Vector<E>. The modicum of effort needed to re-cast Object's to their proper class is quite worth-it because data-reads and data-writes using JAR's remain very simple.

        GENERICS-ERASURE: Because Java's Generic Classes (where the type-parameter 'E', as in java.util.Vector<E>, is used) are not maintained at run-time, the compiler issues warnings when casting a Raw-Type to it's 'specified-type' whether or not a check is actually needed. Unfortunately, this is not possible when reading / de-serializing an Object since the instanceof operator cannot be used. It is, therefore, necessary to use the @SuppressWarnings("unchecked") Annotation to read & de-serialize Java Generics from disk, as below:

        Example:
        1
        2
        3
        4
        5
        6
        // Use the following Java 'Annotation' (Suppress Warnings)
        // This will allow the programmer to cast the "Raw-Type" Vector, to a Vector<String>
        
        @SuppressWarnings("unchecked")
        private static final Vector<String> data = (Vector<String>) LFEC.readObjectFromFile_JAR
            (DataFileLoader.class, "dataFile.sdat", true, Vector.class);
        
        Parameters:
        classLoaderClass - This contains the 'class' that will be used by Java's java.lang.Class.getResourceAsStream(...); method. Please see the comments at the top of this class-documentation page for a better explanation of how Java's class-loader uses a 'java.lang.Class<E>' object to find data-files (which java calls 'resources') inside of a jar-file. All that is really going on is that as classes are loaded by the class-loader from the file-system and from jar-files - the class-loader actually remembers which jar-file's and which directories inside the jar-files contained any/all class-definitions ('.class' files) that were loaded from jar files instead of the file-system.

        This parameter class 'c' points to a jar-file and directory combination that will contain the date-file named/identified by the next parameter String 'f'.

        NOTE: The symbols <?> appended to the (almost) 'raw-type' here, are only there to prevent the java-compiler from issuing warnings regarding the use of "Raw Types." This warning is, actually, only issued if the command-line option -Xlint:all option is used.
        f - The name of the file containing a serialized java.lang.Object to load
        zip - This should be TRUE if, when serialized, the Object was compressed too, and FALSE if compression was not used.
        returnClass - This java.lang.Class<E> should be used to indicate what the type of the java.lang.Object that has been written to the file named by input-parameter String f. When the object is read from disk and de-serialized, the type of the instance shall be checked against this class.

        FOR EXAMPLE: If a Vector containing String's were last written to data-file 'f', then invoking this method to retrieve that Vector<String> would require passing 'Vector.class' to this parameter.

        IMPORTANT This method will halt program execution if after reading an instance from the data-file, the resulting class-name obtained from the instance that was read produces as class-name that is not equal to or, rather, does not inherit from the class passed to 'returnClass'. The logic, or purpose, to this check is to add a layer of data-file integrity check to this class LFEC (Load-File-Exception-Catch).
        Returns:
        a de-serialized java.lang.Object present in the data-file passed by-name through file-name parameter 'f', and cast to the type denoted by parameter returnClass.
        See Also:
        ERROR_EXIT(Throwable, String)
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
         try
         {
             InputStream         is  = classLoaderClass.getResourceAsStream(f);
             ObjectInputStream   ois = zip
                                         ? new ObjectInputStream(new GZIPInputStream(is))
                                         : new ObjectInputStream(is);
             Object              ret = ois.readObject();
        
             is.close();
        
             if (! returnClass.isInstance(ret))
                 ERROR_EXIT(
                     "Serialized Object from jar-file loading-using class: " + classLoaderClass.getCanonicalName() + "\n" +
                     "Looking for data-file named: " + f + "\n" +
                     "Using expected (" + (zip ? "zip-compression" : "no-compression") + ")\n" +
                     "Didn't have an object with class-name: [" + returnClass + "]\n" +
                     "but rather with class-name: [" + ret.getClass().getName() + "]"
                 );
        
             return returnClass.cast(ret);
         }
         catch (Exception ex)
         {
             ERROR_EXIT(
                 "Exception reading Serialized Object from jar-file, loading-using class: " + classLoaderClass.getCanonicalName() + "\n" +
                 "Looking for data-file named: " + f + "\n" +
                 "And attempting to retrieve an object having class-name: " + returnClass + "\n" +
                 "Using expected (" + (zip ? "zip-compression" : "no-compression") + ")\n" +
                 "Experienced an Exception:\n" + EXCC.toString(ex)
             );
        
             return null; // Should NOT be possible to reach this statement...
         }