Package Torello.Java
Class StrSource
- java.lang.Object
-
- Torello.Java.StrSource
-
public class StrSource extends java.lang.Object
Hi-Lited Source-Code:- View Here: Torello/Java/StrSource.java
- Open New Browser-Tab: Torello/Java/StrSource.java
File Size: 40,876 Bytes Line Count: 911 '\n' Characters Found
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
- 33 Method(s), 33 declared static
- 8 Field(s), 8 declared static, 8 declared final
-
-
Field Summary
Fields Modifier and Type Field static PatternGENERIC_PARAMSstatic ReadOnlySet<Character>JS_ESCAPE_CHARSstatic PatternPACKAGE_NAMEstatic ReadOnlySet<Character>REGEX_ESCAPE_CHARSstatic ReadOnlyList<String>reservedKeywords
-
Method Summary
Various Methods Modifier and Type Method static StringcaretBeneath(String str, int strPos)static StringreplaceNBSP(String s)static StringreplaceZWSP(String s)String-Escape Methods Modifier and Type Method static StringescStrForJavaScript(String str)static StringescStrForRegEx(String str)HTML: HTML-Tag Attribute-Names Modifier and Type Method static booleanisAttributeName(String attributeName)static booleanisAttributeNamePart(char c)static booleanisAttributeNameStart(char c)HTML: Retrieve Common HTML Attribue-Values Modifier and Type Method static Stringgrep_HREF_tag(String s)static Stringgrep_IMG_SRC_tag(String s)CSS: Class Names Modifier and Type Method static booleanisCSSClassName(String cssClassName)static booleanisCSSClassNamePart(char c)static booleanisCSSClassNameStart(char c)CSS: Property Names Modifier and Type Method static booleanisCSSPropertyName(String cssPropertyName)static booleanisCSSPropertyNamePart(char c)static booleanisCSSPropertyNameStart(char c)Java: Types, Names, Identifiers & Literals Modifier and Type Method static StringextractTypeName(String srcFileName, boolean throwOnBadTypeName)static booleanisJavaTypeStr(String s)static booleanisValidJavaIdentifier(String identifier)static StringnoPathNoExt(String javaFileName)static StringnumToStringJava(int i)static StringnumToStringJava(long l)static StringtypeToJavaIdentifier(String typeStr)Java: Generic Types & Extends Clauses Modifier and Type Method static String[]parseGenericType(String genericTypeParamOrDefinition)static StringremoveExtendsClause(String decl)static StringremoveGeneric(String typeAsStr)Code-Generators: Source-Code Emitters Modifier and Type Method static StringfourRowsStars(String title, byte indentation, byte maxLineLength)static StringtoJavaDoc(String desc, int numSpacesIndentation, int maxLineLength)static StringtoJavaDoc2(String desc, int numSpacesIndentation, int maxLineLength)Code-Generators: Source Code Indentation, and Whitespace Modifier and Type Method static <PRINTABLE>
Function<PRINTABLE,
String>getTabbedPrinter(String passedBaseStr, Iterable<PRINTABLE> iterable, Function<? super PRINTABLE,String> passedGetStr, byte spacesPerTab)static StringindentNonBlank(String srcCode, byte numSpaces)static StringindentNonBlankAndTrim(String srcCode, byte numSpaces)static StringrightTrimAll(String srcCode)
-
-
-
Field Detail
-
REGEX_ESCAPE_CHARS
public static final ReadOnlySet<java.lang.Character> REGEX_ESCAPE_CHARS
These are 'control' characters (Reg Ex Code), so they must be escaped if the are to be treated as their ASCII-equivalent values.- Code:
- Exact Field Declaration Expression:
public static final ReadOnlySet<Character> REGEX_ESCAPE_CHARS = new ReadOnlyHashSet<>(REGEX_ESCAPE_CHARS_ARR, null);
-
JS_ESCAPE_CHARS
public static final ReadOnlySet<java.lang.Character> JS_ESCAPE_CHARS
When converting aStringfor a Java-ScriptString, these are the characters that must be escaped.- Code:
- Exact Field Declaration Expression:
public static final ReadOnlySet<Character> JS_ESCAPE_CHARS = new ReadOnlyHashSet<>(JS_ESCAPE_CHARS_ARR, null);
-
reservedKeywords
public static final ReadOnlyList<java.lang.String> reservedKeywords
The list of reserved Java Key-Words. This list was written by ChatGPT on February 1st, 2024.- Code:
- Exact Field Declaration Expression:
public static final ReadOnlyList<String> reservedKeywords = new ReadOnlyArrayList<>( "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "permirs", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while" );
-
GENERIC_PARAMS
public static final java.util.regex.Pattern GENERIC_PARAMS
This will match the definition for a java'Generic'class or interface- Code:
- Exact Field Declaration Expression:
public static final Pattern GENERIC_PARAMS = Pattern.compile("^.+?<([\\.\\s\\w\\<>,\\?]+)>$");
-
PACKAGE_NAME
public static final java.util.regex.Pattern PACKAGE_NAME
This shall match a Java PackageString- Code:
- Exact Field Declaration Expression:
public static final Pattern PACKAGE_NAME = Pattern.compile("([A-Za-z_]\\w*\\.)+");
-
-
Method Detail
-
caretBeneath
public static java.lang.String caretBeneath(java.lang.String str, int strPos)
This will print a caret-symbol on a line of text underneath the inputStringparameter'str'. Preceeding the caret-symbol will be exactlystrPos - 1space characters. This look of the output-Stringis similar to some of the error messages generated by a Java Compiler.
The caret-symbol'^'will bee pointing to the character at indexstrPos.
Example:
// Notice the (accidental, on-purpose) use of the '@'' character instead of an 'a' // To make this easy, lets compute the exact location of this erroneous character. String s = "This string has an inv@lid character."; int pos = s.indexOf("@"); // This will print out a line of text containing the string, with a caret pointing // at the '@' symbol. System.out.println(StringParse.caretBeneath(s, pos)); // PRINTS: // This string has an inv@lid character. // ^
- Parameters:
str- This may be any input-Stringthat is less than 100 characters.strPos- This must be a number between 0 and the length- Returns:
- The same input-
Stringwith a second line appended underneath (using a newline) having a caret ('^') directly underneath the character atstrPos. - Throws:
java.lang.IllegalArgumentException- If the inputStringis longer than100 characters.StringFormatException- If the inputStringcontains any new-line'\n'or tab'\t'characters.java.lang.StringIndexOutOfBoundsException- If the value pased tostrPosis negative or greater than the length of the input-String.- See Also:
StringParse.nChars(char, int)- Code:
- Exact Method Body:
if (str.length() > 100) throw new IllegalArgumentException( "The length of the input-string must be less than 100. str has length: " + str.length() ); if (StrCmpr.containsOR(str, "\n", "\t")) throw new StringFormatException ("The input-string may not contain new-line or tab characters."); if (strPos >= str.length()) throw new StringIndexOutOfBoundsException( "The value you have passed to 'strPos' [" + strPos + "] is greater than the length " + "the input-string [" + str.length() + "]" ); if (strPos < 0) throw new StringIndexOutOfBoundsException ("You have passed a negative value to strPos [" + strPos + "]"); return str + "\n" + StringParse.nChars(' ', strPos) + '^';
-
replaceNBSP
public static java.lang.String replaceNBSP(java.lang.String s)
There are actually people out there who are willing to put character'160'into a file or document, instead of a simple' 'element. How rude. Any instances of this character shall be replaced with the standard space characterASCII #32.- Parameters:
s- AnyStringwill pass. GenerallyString'sthat were converted from HTML pages will containchar #160as it is occasionally translated from the HTML escape sequence - Returns:
- A String where any instance of white-space character
#160have been replaced with character#32 - Code:
- Exact Method Body:
return s.replace((char) 160, ' ');
-
replaceZWSP
public static java.lang.String replaceZWSP(java.lang.String s)
Even lower than#160, apparently is the"Zero Width Space"(character#8203. This is actually inserted by the JavaDoc Tool (bySun / Oracle) into JavaDoc generated HTML Pages. Here, it shall be replaced by character#32- the space-character.
A.K.A.:"".
Can you see the character, above? No? That's zero width space for you! If you ever sitting and wondering why aStringseems to be something else than what it looks like - you might have a zero-width space in yourString. If so, it will take a while to find the bug.- Parameters:
s- AnyStringwill pass. GenerallyString'sthat were converted from JavaDoc HTML pages will containchar #8203.- Returns:
- A String where any instance of white-space character
#8203have been replaced with character#32 - Code:
- Exact Method Body:
return s.replace((char) 8203, ' ');
-
escStrForJavaScript
public static java.lang.String escStrForJavaScript(java.lang.String str)
Copied from Stackoverflow.com - and all the "BRILLIANT ENGINEERS"!
Really, I wish I had a reputation!!! So awful...
Question: String.replaceAll single backslahes with double backslashes
I'm trying to convert the String \something\ into the String \\something\\ using replaceAll, but I keep getting all kinds of errors. I thought this was the solution:
theString.replaceAll("\\", "\\\\");
But this gives the below exception:
java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
The String#replaceAll() interprets the argument as a regular expression. The \ is an escape character in both String and regex. You need to double-escape it for regex:
string.replaceAll("\\\\", "\\\\\\\\");
But you don't necessarily need regex for this, simply because you want an exact character-by-character replacement and you don't need patterns here. So String#replace() should suffice:
string.replace("\\", "\\\\");
Update: as per the comments, you appear to want to use the string in JavaScript context. You'd perhaps better use StringEscapeUtils#escapeEcmaScript() instead to cover more characters- Parameters:
str- This may be any String in java. It is intended to be inserted into a Java-Script file between an open and close quotation marks.- Returns:
- The String that is returned will have certain characters escaped, so that it may be
wrapped in quotation marks and easily inserted into any java-script ".js" text-file.
Escaped-Text:char '\'will be escaped to:"\\"char '/'will be escaped to:"\/", this is required in Java-Script, but not Java!char '"'will be escaped to:"\""
NOTE:
There is no easy, nor clear, way to express what is being replaced and/or escaped in a simple list. You may run this method on anyStringand view for yourself what changes.
The primary goal of the method is to allow *any* Java String of *any* length to be converted, wrapped inside of an open and closed quotation-mark set, and printed into a Java-Script".js" file.
Escaping "escape characters" which does come up some-what often in HTML text/string processing is near-impossible to explain clearly! Review the stack-overflow "incantation" for possible help.Important Note: My Google User-Name is banned for 30 years on StackOverflow.com. That site is true evil. - Code:
- Exact Method Body:
return StrReplace.r(str, JS_ESCAPE_CHARS_ARR, '\\');
-
escStrForRegEx
public static java.lang.String escStrForRegEx(java.lang.String str)
This method should only be used for a preciseStringmatch using a regular-expression. This method shall 'escape' all characters that the JVM Regular Expression Matcher inpackage java.util.regex.*would expect be escaped. If the input parameter'str'contains any regular-expression code, then this method would FAIL as it would escape regular-expression code into unusable text.- Parameters:
str- This should be anyStringfor which the user would like to find an exact match, as-is.- Returns:
- A regular-expression ready
String - Code:
- Exact Method Body:
return StrReplace.r(str, REGEX_ESCAPE_CHARS_ARR, '\\');
-
isAttributeName
public static boolean isAttributeName(java.lang.String attributeName)
Checks if a Java-Stringconstitutes a valid HTML Attibute-Name. Note that this method, in no way consults any "complete list" of all know HTML-Attributes. Instead, it simply analyzes whether the name is conguent with the Attribute-Name Validator Reg-ex.- Parameters:
attributeName- Any Java-String- Returns:
TRUEif and ony if'attributeName'is a valid HTML Atribute-Name, according to the agreed upon Attribute-Name Regular-Expression Validator.- Code:
- Exact Method Body:
if (attributeName.length() == 0) return false; if (! isAttributeNameStart(attributeName.charAt(0))) return false; for (int i=1; i < attributeName.length(); i++) { final char c = attributeName.charAt(i); if ((c >= 'A') && (c <= 'Z')) continue; if ((c >= 'a') && (c <= 'z')) continue; if ((c >= '0') && (c <= '9')) continue; if ((c == '-') || (c == '_')) continue; return false; } return true;
-
isAttributeNameStart
public static boolean isAttributeNameStart(char c)
Checks whether parameter'c'is one of the agreed-upon standard characters that are allowed to begin HTML Attribute-Names.- Parameters:
c- Any Javachar-primitive- Returns:
TRUEif and ony if'c'is a character that would be allowed to begin an HTML Attribute-Name- Code:
- Exact Method Body:
if ((c >= 'A') && (c <= 'Z')) return true; if ((c >= 'a') && (c <= 'z')) return true; return false;
-
isAttributeNamePart
public static boolean isAttributeNamePart(char c)
Checks whether parameter'c'is one of the agreed-upon standard characters that are permitted within HTML Attribute-Names, after the first character of the name.- Parameters:
c- Any Javachar-primitive- Returns:
TRUEif and ony if'c'is a character that would be allowed within a valid HTML Attribute-Name.- Code:
- Exact Method Body:
if ((c >= 'A') && (c <= 'Z')) return true; if ((c >= 'a') && (c <= 'z')) return true; if ((c >= '0') && (c <= '9')) return true; if ((c == '-') || (c == '_')) return true; return false;
-
grep_HREF_tag
public static java.lang.String grep_HREF_tag(java.lang.String s)
If parameterString scontains any tag within-which there is a valid"HREF", this will return the contents of theHREFAttribute/InnerTag.- Parameters:
s- This is usually some variant of an HTML element/tagString. This method was the first one written for HTML in this scrape package, and is just kept here for legacy reasons. Theclass HTML.TagNodehas a number of options for extracting the'HREF'attribute from an HTML element.- Returns:
- The attribute-value of an
HREF=...attribute inside (usually an<A>'Anchor') HTML tag. This will return 'null' if there is noHREF="..."attribute-value pair is found or identified. - Throws:
java.lang.IllegalArgumentException- If there is no end-quote found for theHREF="..."sub-string.- Code:
- Exact Method Body:
return TagsGREP.grepIMG(s);
-
grep_IMG_SRC_tag
public static java.lang.String grep_IMG_SRC_tag(java.lang.String s)
If parameterString scontains an HTML"IMG"tag, this will return the contents of the"SRC=..."attribute tag-field.- Parameters:
s- This is usually some variant of an HTML element/tagString. This method was the first one written for HTML in this scrape package, and is just kept here for legacy reasons. Theclass HTML.TagNodehas a number of options for extracting the'SRC'attribute from an HTML element.- Returns:
- The attribute-value of a
SRC=...attribute inside (usually an<IMG>'Image') HTML tag. 'null' is returned if:- There is no HTML
'IMG'token found in theString - There is no
SRC='...'attribute-value pair found.
- There is no HTML
- Code:
- Exact Method Body:
return TagsGREP.grepHREF(s);
-
isCSSClassName
public static boolean isCSSClassName(java.lang.String cssClassName)
Checks if a Java-Stringconstitutes a valid CSS Class-Name. This method does not consult any "complete list" of all known CSS classes but instead analyzes whether the name adheres to standard CSS class naming conventions.Chat-GPT Note: Chat-GPT wrote all three of these (including th JavaDoc). Chat-GPT makes programming more fun.- Parameters:
cssClassName- Any Java-String- Returns:
TRUEif and only ifcssClassNameis a valid CSS Class-Name according to the agreed-upon CSS naming rules.- Code:
- Exact Method Body:
if (cssClassName.length() == 0) return false; if (!isCSSClassNameStart(cssClassName.charAt(0))) return false; for (int i = 1; i < cssClassName.length(); i++) if (!isCSSClassNamePart(cssClassName.charAt(i))) return false; return true;
-
isCSSClassNameStart
public static boolean isCSSClassNameStart(char c)
Checks whether parameter'c'is a valid character to begin a CSS Class-Name.Chat-GPT Note: Chat-GPT wrote all three of these (including the JavaDoc). Chat-GPT makes programming more fun.- Parameters:
c- Any Javachar-primitive- Returns:
TRUEif and only ifcis a character that can begin a CSS Class-Name.- Code:
- Exact Method Body:
if ((c >= 'A') && (c <= 'Z')) return true; if ((c >= 'a') && (c <= 'z')) return true; if (c == '-') return true; if (c == '_') return true; return false;
-
isCSSClassNamePart
public static boolean isCSSClassNamePart(char c)
Checks whether parameter'c'is a valid character within a CSS Class-Name.Chat-GPT Note: Chat-GPT wrote all three of these (including the JavaDoc). Chat-GPT makes programming more fun.- Parameters:
c- Any Javachar-primitive- Returns:
TRUEif and only ifcis a character that can be part of a CSS Class-Name.- Code:
- Exact Method Body:
if ((c >= 'A') && (c <= 'Z')) return true; if ((c >= 'a') && (c <= 'z')) return true; if ((c >= '0') && (c <= '9')) return true; if (c == '-') return true; if (c == '_') return true; return false;
-
isCSSPropertyName
public static boolean isCSSPropertyName(java.lang.String cssPropertyName)
Checks if a Java-Stringconstitutes a valid CSS Property-Name. Note that this method, in no way consults any "complete list" of all known CSS-Properties. Instead, it simply analyzes whether the name is conguent with the CSS-Property Validator Reg-ex.- Parameters:
cssPropertyName- Any Java-String- Returns:
TRUEif and ony if'attributeName'is a valid HTML Atribute-Name, according to the agreed upon CSS-Property Regular-Expression Validator.- Code:
- Exact Method Body:
if (cssPropertyName.length() == 0) return false; if (! isCSSPropertyNameStart(cssPropertyName.charAt(0))) return false; for (int i=1; i < cssPropertyName.length(); i++) { final char c = cssPropertyName.charAt(i); if ((c >= 'A') && (c <= 'Z')) continue; if ((c >= 'a') && (c <= 'z')) continue; if ((c >= '0') && (c <= '9')) continue; if ((c == '-') || (c == '_')) continue; return false; } return true;
-
isCSSPropertyNameStart
public static boolean isCSSPropertyNameStart(char c)
Checks whether parameter'c'is one of the agreed-upon standard characters that are allowed to begin CSS Property-Names.- Parameters:
c- Any Javachar-primitive- Returns:
TRUEif and ony if'c'is a character that would be allowed to begin a CSS Property-Name- Code:
- Exact Method Body:
if ((c >= 'A') && (c <= 'Z')) return true; if ((c >= 'a') && (c <= 'z')) return true; if ((c == '-') || (c == '_')) return true; return false;
-
isCSSPropertyNamePart
public static boolean isCSSPropertyNamePart(char c)
Checks whether parameter'c'is one of the agreed-upon standard characters that are permitted within CSS Property-Names, after the first character of the name.- Parameters:
c- Any Javachar-primitive- Returns:
TRUEif and ony if'c'is a character that would be allowed within a valid CSS Property-Name.- Code:
- Exact Method Body:
if ((c >= 'A') && (c <= 'Z')) return true; if ((c >= 'a') && (c <= 'z')) return true; if ((c >= '0') && (c <= '9')) return true; if ((c == '-') || (c == '_')) return true; return false;
-
extractTypeName
public static java.lang.String extractTypeName (java.lang.String srcFileName, boolean throwOnBadTypeName)
Extracts the Class-Name / Type-Name from the File-Name of a'.java'or'.class'File.Method Input: Method Output: "com/sun/source/tree/Tree.java""Tree""Vector.java""Vector""java/util/Vector.class""Vector""com/sun/source/tree/My-Favorite-Class.java"Either throws, or returns null, because "My-Favorite-Class" is not a valid Java-Identifer - Parameters:
srcFileName- This is expected to be the file-name of a'.java'or'.class'File.throwOnBadTypeName- When this is passedTRUE, this method throws an exception if the Computed Type-Name is not a valid Java Identifier.- Returns:
- the name of the type represented by this Java or Class File.
If the name of the returned type would be invalid, this method will either:- throws
JavaIdentifierException, if parameterthrowOnBadTypeNamewere passedTRUE. - returns
null, otherwise.
- throws
- Throws:
java.lang.IllegalArgumentException- If the file-name ends neither with the text'.java'nor with'.class'.JavaIdentifierException- Throws if-and-only-if BOTH the returnedStringwould not constitute a valid Java-Identifier, AND the inputbooleanparameterthrowOnBadTypeNameis passedTRUE.- Code:
- Exact Method Body:
return ExtractTypeName.extract(srcFileName, throwOnBadTypeName);
-
isJavaTypeStr
public static boolean isJavaTypeStr(java.lang.String s)
Checks whether an inputStringis a valid Type Identifier. Type Identifiers are the names of Java Classes, Interfaces, Enumerated-Types, Annotations and Records. The two methodsCharacter.isJavaIdentifier.start(char)andCharacters.isJavaIdentifer.part(char)are utilized here to produce this method's return value. Below is a table of several output-results (table's second column) that would be returned by the specified inputsString's(first column).Function Input Return Value String true Map.Entry true Vector true Vector<String> false Map.Entry<String, Integer> false String.indexOf(1) false String.indexOf true MyOuterClass.MyInnerClass03 true MyOuterClass.03MyInnerClass false
The only real check being performed is whether theStringis a valid 'Java Identifier' - or, if a period'.'is present - that it is a list of Java Identifier's which are all separated by a single period character. This is done to ensure thatString'swhich reference Java Inner Classes, Interfaces, Enumerations, etc. also produce aTRUEreturn value.- Parameters:
s- Any JavaString.- Returns:
TRUEif and only if the Java Compiler could interpret's'as a valid reference to a Java Type. In computer-programming, the worldTypecan have a lot of meanings, but here, the word should be interpreted as a Java Class, Interface, Enumeration (an'enum'), Annotation or Record.Note:'s'may include the period'.'since inner classes, enum's and interfaces are also valid Java Type's. Two consecutive period-characters, or a period at the beginning or ending of's'will result in this method returningFALSE.- Code:
- Exact Method Body:
return IsJavaTypeStr.is(s);
-
isValidJavaIdentifier
public static boolean isValidJavaIdentifier(java.lang.String identifier)
Checks whether an inputStringwould be allowed as a Java Identifier - for instance, whether the input would make a valid Field-Name, Variable-Name, Class-Name or Method-Name.NOTE: This class returnsFALSEif it is passed 'null'. It does not throw aNullPointerException.
Chat-GPT Note: ChatGPT, 3.5 wrote this whole thing, including the in-line comments. I had to write the Java-Doc Comments, but I guess I could have asked it to do that too.- Parameters:
identifier- Any JavaString- Returns:
TRUEif-and-only-if parameter'identifier'is a valid Java Identifier.- Code:
- Exact Method Body:
// Check if the string is not null or empty if (identifier == null || identifier.isEmpty()) return false; // Check if the first character is a letter, underscore, or dollar sign if (! Character.isJavaIdentifierStart(identifier.charAt(0))) return false; // Check the remaining characters for (int i = 1; i < identifier.length(); i++) if (!Character.isJavaIdentifierPart(identifier.charAt(i))) return false; // Check if the identifier is a reserved keyword if (reservedKeywords.contains(identifier)) return false; // The string is a valid Java identifier return true;
-
noPathNoExt
public static java.lang.String noPathNoExt(java.lang.String javaFileName)
Simply removes the trailiing'.java'from the end of an input File-Name Parameter. Also removes any leading directory information from the inputString.- Parameters:
javaFileName- This is expected to be a legitamite '.java' Source-Code File-Name, as ajava.lang.String.- Returns:
- Returns a
Stringin which leading directory information has been truncated, and the last five characters have been removed.
Due to the highly repetitive nature of using this methpo within a loop, this method's body does not perform any kind of error checking on its input.
If a nullStringis passed as input, this method will throw aNullPointerException. If your best friend's address is passed as input, this method will return aStringin which the last 5 characters of text of that address have been removed.
And if that address had a forward or backward slash ('/'or'\'), everything prior to the last slash present within that input-mess would be truncated. - Throws:
java.lang.IndexOutOfBoundsException- If, after truncating any leading directory information, the resultingStringis less than 5 characters, then this exception throws.- Code:
- Exact Method Body:
for (int i=(javaFileName.length()-1); i > 0; i--) { final char c = javaFileName.charAt(i); if ((c == '/') || (c == '\\')) { javaFileName = javaFileName.substring(i + 1); break; } } return javaFileName.substring(0, javaFileName.length() - 5);
-
numToStringJava
public static java.lang.String numToStringJava(int i)
Converts a Javaintinto a numeric literalString(java.lang.String. The returnedStringuses underscores to separate each power of 103 ("thousands place"). This is a somewhat "lesser known" or esoteric Java-Syntax feature, but extremely useful when necessary.
Example:
int num = 123000000; String formatted = StrSource.numToStringJava(num); // The following line will print: 123_000_000 System.out.println(formatted); // Demonstrates negative value formatting, Prints: -65_536 System.out.println(StrSource.numToStringJava(-65536));
This type of method can be extremely in code generators. when larger integers need to be emitted (as text) into generated.javasource files.
ChatGPT originally wrote the code for this method and noted that the implementation used here is functionally identical to (but more efficient than) the following one-liner:
String.format("%,d", num).replace(',', '_');
Optimizations & Chat-GPT:
You can view the@LinkJavaSourceexternal class linked from this page. With some refinement, Chat-GPT actually produced three different variants of the same method. I have retained the other two in a package private Helper-Class. While not directly callable from external code, you can inspect or copy them by clicking theExternal Javabutton above this method (next to the curved, up-arrow at the top of this Javadoc entry).
A benchmark routine (also written by ChatGPT) compares all three variants. Results are shown in the table below. (This table was generated by the code linked under the External Java button above.)Method Variants Execution Time (seconds) fmtReplace 4.765 s builderInsert 1.061 s charBuffer 0.764 s - Parameters:
i- Any Java Integer- Returns:
- The value of
'i'as aString, but separated by the underscore character'_'in between each spacing of three orders of magnitude. - Code:
- Exact Method Body:
return IntegralToJavaLiteral.charBuffer(i);
-
numToStringJava
public static java.lang.String numToStringJava(long l)
Identical tonumToStringJava(int), but accepts along.- Parameters:
l- Any Java Long- Returns:
- The value of
'l'as aString, but separated by the underscore character'_'in between each spacing of three orders of magnitude. - See Also:
numToStringJava(int)- Code:
- Exact Method Body:
return IntegralToJavaLiteral.charBufferLong(l);
-
typeToJavaIdentifier
public static java.lang.String typeToJavaIdentifier (java.lang.String typeStr)
This will remove any generic-parameter information from a Java type-Stringand then remove all package-information or outer-classString's. What is left is a single Java IdentifierStringthat, as long as the proper scope has been provided, identifies a Java Type (Class, Interface, Enum, Record, Annotation).Output Input "Integer""java.lang.Integer""Vector""java.util.Vector<E>""Entry""java.util.Map.Entry<String, Integer>""Entry""Map.Entry<String, Intger>""Entry""Entry<String, Integer>""Entry""Entry""String[]""String[]""String[]""java.lang.String[]""Vector""Vector<String[]>""Vector[]""Vector<String>[]"Point of Interest: "The World Series""The World Series""Quoth the Raven""Quoth the Raven<java.lang.Integer>"Finally: "String...""String...""String...""java.lang.String...""Vector...""Vector<E>...""Vector...""java.util.Vector<E>..."- Parameters:
typeStr- This is a type as aString. These are usually retrieved from Java Parser, in the Java Doc Upgrader package. This method does not provide an exhaustive check for all variants of format and naming erros of a Java Type. Some validity checks are performed regarding the use of non-Java type characters.Note: All the exceptions thrown by the methodremoveGeneric(String)will also be thrown here, if'typeStr'is not not properly formatted.- Returns:
- a Simplified version of the type that leaves out the scope, but provides a simple Java Identifier, instead. Throws exceptions if not properly formatted. If any array-bracket characters are passed, they is preserved, unless the arrays in this type are part of the generic-type parameters; please see the examples above.
- Throws:
StringFormatException- Please see the explanation provided inremoveGeneric(String)under 'Throws'.- See Also:
removeGeneric(String)- Code:
- Exact Method Body:
return TypeToJavaIdentifier.convert(typeStr);
-
parseGenericType
public static java.lang.String[] parseGenericType (java.lang.String genericTypeParamOrDefinition)
Parses aStringsuch asT extends TreeMap<Integer, List<String>>. It is strictly used, to only parse the generic-definition lists that are at the top of generic classes and interfaces.Sample Input StringOutput String[] array"HashMap<E extends Comparable, F extends Comparable>"{ "E extends Comparable", "F extends Comparable" }"Ret6<A, B, C, D, E, F>"{ "A", "B", "C", "D", "E", "F" }"AbstractHNLI<?, Vector<Vector<? extends HTMLNode>>>"{ "?", "Vector<Vector<? extends HTMLNode>>" }"VarList<Vector<HashMap<String, String>>, FileNode>"{ "Vector<HashMap<String, String>>", "FileNode" }"AbstractHashCodeHLC<NUMBER extends java.lang.Number>"{ "Number extends java.lang.Number" }- Parameters:
genericTypeParamOrDefinition- This should beStringretrieved from inside the less-than ('<') and greater-than ('>') symbols. For example, forSortedList<A extends Comparable, B>, theStringpassed to this method should be"A extends Comparable, B"- Returns:
- This should break down this
CSV(comma separated value) list into individualString's. - Throws:
NoMatchException- if the inputStringparameter does not match the generics regular-expressionGENERIC_PARAMS.StringFormatException- If the inputStringcould not be parsed.- Code:
- Exact Method Body:
return ParseGenericType.parse(genericTypeParamOrDefinition);
-
removeExtendsClause
public static java.lang.String removeExtendsClause(java.lang.String decl)
Removes the'extends'part of a Java GenericTO DO: This will fail for a class such as:public class MyClass<T extends Vector<String>, where the extends clause also has a generic in it. Java HTML does not define such classes, but they are possible, and this needs to be fixed, as soon as they let me!- Parameters:
decl- Any Type Declaration that includes has the word {'extends'}, followed by type-parameter information.- Returns:
- The same
Stringwithout the clause. - Code:
- Exact Method Body:
Matcher m = exClause.matcher(decl); while (m.find()) { decl = m.replaceFirst(m.group(1)); m.reset(decl); } return decl;
-
removeGeneric
public static java.lang.String removeGeneric(java.lang.String typeAsStr)
This will remove the generic type-parameters expression from a Java Type Declaration or Reference. In simple terms, this removes the'<K, V>'from aStringsuch asMap.Entry<K, V>.Returned StringInput String"Vector""Vector<E>""AbstractHNLI""AbstractHNLI<E extends HTMLNode, F>""Torello.HTML.TagNode""Torello.HTML.TagNode""ClassA.InnerClassB.InnerClassC""ClassA<X>.InnerClassB<Y>.InnerClassC""String[]""String[]""java.lang.String[]""java.lang.String[]""Vector""Vector<String[]>""java.util.Vector""java.util.Vector<String[]>"Point of Interest: "I watched the World Series" "I watched the World Series" "Vector""Vector<Quoth the Raven>"Throws an Exception "HNLI<E> <""> <Quoth the Raven>"- Parameters:
typeAsStr- The "Reference Type" or "Declaration Type".- Returns:
- The same
String, having everything between the outer-most, matching'<'and'>'symbols.Note: The returnedStringwill not contain any leading or trailing white-space. It is trimmed before being returned. - Throws:
StringFormatException- An exhaustive check on everything that could be wrong with a type-Stringis an impossibility (if you include checking for valid types). This exception is only thrown if the'<'and'>'symbols inside the input-Stringdo not match-up.
In order to avoid throwing this exception, there must be an equal number of opening and closing symbols.
There is also a check to ensure that the charcters in thisStringare valid.- Code:
- Exact Method Body:
return RemoveGeneric.remove(typeAsStr);
-
toJavaDoc
public static java.lang.String toJavaDoc(java.lang.String desc, int numSpacesIndentation, int maxLineLength)
It is best to read, exactly, how this method operates by reviewing the code in the "Method Body" below. This method converts a text description into a Java-Doc Comment.- Parameters:
desc- A descriptive String that is to be used as a Java-Doc commentnumSpacesIndentation- Number of spaces of indentation to be pre-pended to each linemaxLineLength- Maximum number of characters on any given line.- Returns:
- A Java-Doc String, prepended by
" * "and the number of requested spaces. - Code:
- Exact Method Body:
final String INDENT = StringParse.nChars(' ', numSpacesIndentation); desc = desc.replace('\n', ' ').trim(); // For: numSpacesIndentation = 4, maxLineLength = 100 // // 88 ==> maxLineLength - INDENT.length() - " /** ".length() - " */".length() // 88 ==> 100 - 4 - 5 - 3 if (desc.length() <= (maxLineLength - numSpacesIndentation - 8)) return INDENT + "/** " + desc + " */\n"; // ONE THING: I need to come back to this at a later date and re-investigate why I have // needed to add the '-1'. I haven't looked at StrPrint.wrap in 7 months... I am in the // middle of something else right now (Torello.Browser). Thusly, though it looks normal // and official, the extra '-1' at the end of this makes no sense to me... But the testing // shows that -4 was correct, and -3 was failing... I DON'T HAVE TIME / INCLINATION right // now ! // // 92 ==> 100 - INDENT.length() - " * ".length() - 1 // 92 ==> maxLineLength - numSpacesIndentation - 3 - 1 desc = StrPrint .wrap(desc, maxLineLength - numSpacesIndentation - 4) .replace("\n", '\n' + INDENT + " * "); return INDENT + "/**\n" + INDENT + " * " + desc + '\n' + INDENT + " */\n";
-
toJavaDoc2
public static java.lang.String toJavaDoc2(java.lang.String desc, int numSpacesIndentation, int maxLineLength)
It is best to read, exactly, how this method operates by reviewing the code in the "Method Body" below. This method converts a text description into a Java-Doc Comment.- Parameters:
desc- A descriptive String that is to be used as a Java-Doc commentnumSpacesIndentation- Number of spaces of indentation to be pre-pended to each linemaxLineLength- Maximum number of characters on any given line.- Returns:
- A Java-Doc String, prepended by
" * "and the number of requested spaces. - Code:
- Exact Method Body:
final String INDENT = StringParse.nChars(' ', numSpacesIndentation); desc = desc.replace('\n', ' ').trim(); return INDENT + " * " + StrPrint .wrap(desc, maxLineLength - numSpacesIndentation - 4) .replace("\n", '\n' + INDENT + " * ") + '\n';
-
getTabbedPrinter
public static <PRINTABLE> java.util.function.Function<PRINTABLE,java.lang.String> getTabbedPrinter (java.lang.String passedBaseStr, java.lang.Iterable<PRINTABLE> iterable, java.util.function.Function<? super PRINTABLE,java.lang.String> passedGetStr, byte spacesPerTab)
Returns a function that will print the contents of the iterable, with just enough right hand space to produce output that begins on a column number that is a multiple of'spacesPerTab'.
The following example use of this function has been lifted out of the code generator used to generated the classes for packagesBrowserAPIandJavaScriptAPI(which contain browser automation, Chrome DevTools Protocol classes - all which is produced by a code generator, rather than being manually entered by hand). The actual Java Code that is emitted by this Code Generation Snippet is used inside of the constructors for the sub-types & events within the CDP "Domain Classes."
Example:
// Append the Enumerated String Values Check to the Generated Code sb.append(H03_EnumValsCheck.check(fields)); final Function<PPR, String> spacer = StrSource.getTabbedPrinter( "this.", fields, (PPR field) -> C_Names.CHECKPPRNAME(field), (byte) 4 ); for (final PPR field : fields) sb.append(spacer.apply(field) + "= " + C_Names.CHECKPPRNAME(field) + ";\n");
The code emitted by this generator would look like as below. This snippet was copied out of the constructor for classNetwork.BlockedSetCookieWithReason. The exact code generated by this method is stuff that assigns the values to this class' fields. If you click on the link to that class, and then review that class' source code, you will see (as you should hopefully expect), that its constructor assigns values to it's fields. Generally, code like that is much nicer to read when those assignment statements line up on a tab-delimited basis.
Example:
/** Constructor */ public BlockedSetCookieWithReason (boolean[] isPresent, String[] blockedReasons, String cookieLine, Network.Cookie cookie) { super(singleton, Domains.Network, "BlockedSetCookieWithReason", 3); // THIS CODE RIGHT HERE IS EMITTED / PRODUCED BY THE CODE GENERATOR SNIPPET, ABOVE // // NOTICE THAT THE THE EQUALS-SIGNS ARE "LEFT ALIGNED" (BECAUSE OF RIGHT-SPACE-PADDING) // FUTHERMORE, THEY ARE ALIGNED ON A COLUMN THAT IS A MULTIPLE OF 4 ('spacesPerTab' is 4) this.blockedReasons = blockedReasons; this.cookieLine = cookieLine; this.cookie = cookie; ... }
One final point of interest is that if each of the strings returned by'getStr'has an identical length (or if'iterator'only returns a single instance ofPRINTABLE), then the printer function that is returned by this class will not align the output to a column that is a multiple of'spacesPerTab'.When each of the strings that are produced by applying the function to the iterable's output have equal length, the printer that is generated by this method shall only append a single space character to the right side of its output. This is because the only purpose of aligning a set of strings to a column tha is a multiple of width of a tab is because the generated code looks better when it is aligned that way.
If each of the strings has an identical lenght, the output will be automatically aligned using only a single space!- Type Parameters:
PRINTABLE- This Type Variable must be capable of generating a JavaString. This method expects that the'getStr'parameter accept an instance of whatever type that'PRINTABLE'is, and produce aString-representation of that object instance.
Certainly, in many cases the function passed to the'getStr'parameter would actually be nothing more thanSomeType::toString. However, there might be situations where a particular field inside of a class is returned. Perhaps a user might want to merely wrap quotes around the output of the standardtoString()method.
See such examples below:SomeType::toString(PRINTABLE's toString method)(SomeType st) -> st.someField(a field inside of class PRINTABLE)(SomeType st) -> "\"" + st.toString() + "\""
- Parameters:
passedBaseStr- TheStringpassed here is required to build the printer, even though it's contents are repeated and inserted into each manifestation of the generated output. It is needed because it's length must be known in order to actually produce output which allocates space that falls on a multiple of 4 spaces from the left margin.If this string contains any emojis, non-printable characters, or characters that do not actually have a 1-to-1 mapping with their length, then the function returned by this method will not work properly. This method bases the indentation using aString.length()and a maximum string length.null may be passed to this parameter, and if it is, then the empty string ("") is the value ultimately assinged and used in its place.
// The internal method to which this method dispatches utilizes this final String baseStr = (passedBaseStr != null) ? passedBaseStr : "";
iterable- Any Java List, Collection or Iterable whose iterator is capable of producing instances of Type ParameterPRINTABLE.
ThisIterableprovides itsIteratorand then calculates what the maximum generatedString.length()which may be produced by the'getStr'function.passedGetStr- Any Java Function, Lambda-Expression or Method-Reference may be passed here, so long as it is one which accepts an instance of Type-ParameterPRINTABLE, and produces ajava.lang.String
If any of the strings returned by'getStr'contain a newline character or a length longer than 100, then this method will throw aStringFormatExceptionnull may be passed to this parameter, and if it is, then the standardObject.toString()method is the value ultimately assinged and used in its place. See the code snippet, below.
// The internal method to which this method dispatches utilizes this final Function<? super PRINTABLE, String> getStr = (passedGetStr != null) ? passedGetStr : (PRINTABLE p) -> ((p == null) ? null : p.toString());
spacesPerTab- The number of spaces a TAB character to should represent.- Returns:
- A Java Function that can print output which is right aligned to a column number that
is a multiple of 4.
It is important to note that the function which is returned will only work properly if it is used in conjunction with the strings that were initially returned by the passed iterable. The lambda which is returned by this method has the maximum string length that was produced by the output of
'getStr', and makes its space padding calculations according to that maximum length.
If aPRINTABLEinstances that generated an "even longer string" were accidentally passed to the returned lambda'sapply()method, then that invocation would actually throw an exception! - Throws:
NException- if'spacesPerTab'is less than 2 or greter than 10StringFormatExcetion- Throws if:'passedBaseStr'is longer than 100 characters'passedBaseStr'contains a newline character'getStr'returns a string longer than 100 characters'getStr'returns a string that contains a newline character- When using the lambda, if
'getStr'returns a string that is longer than the computed maximum string-length
EmptyListException- If theIterablewhich is generated by'iterable'does not actually returns any instances ofPRINTABLE. (If the iterable is empty).java.lang.NullPointerException- Throws if:'iterable'is passed null- Any of the values returned by
'getStr'are null
- Code:
- Exact Method Body:
return TabbedIndentation.getFunction(passedBaseStr, iterable, passedGetStr, spacesPerTab);
-
fourRowsStars
public static java.lang.String fourRowsStars(java.lang.String title, byte indentation, byte maxLineLength)
Produces a "Comment String" text which contains four rows of stars, and a title string.- Parameters:
title- Title text to insert between the rows of starsindentation- Amount of indentation spaces to addmaxLineLength- Total expected / required line length of this comment- Returns:
- A Java source string which may be inserted into
'.java'files. - Throws:
java.lang.NullPointerException- if title is nullStringFormatException- if title won't fit within'maxLineLength'java.lang.IllegalArgumentException- Throws if:'indentation'is negative'maxLineLength'is negative'indentation'is greater than or equal to'maxLineLength''title'will not fit within the alloted line length
- See Also:
StringParse.nChars(char, int)- Code:
- Exact Method Body:
return FourRowsStars.get(title, indentation, maxLineLength);
-
rightTrimAll
public static java.lang.String rightTrimAll(java.lang.String srcCode)
Performs the standard "Right Trim Whitespace" on each line of text contained by the inputString. Converts the inputStringto achar[] cArr, and then performs an in-place shift operation before rebuilding a new string from the array.- Parameters:
srcCode- Any text-file or snippet containing any programming language- Returns:
- A new
- Code:
- Exact Method Body:
return RightTrimAll2.run(srcCode);
-
indentNonBlank
public static java.lang.String indentNonBlank(java.lang.String srcCode, byte numSpaces)
Indents each line of input text'srcCode', by the number of spaces'numSpaces'. Does not do any indentation on lines which only contain whitespace.- Parameters:
srcCode- Any text-file or snippet containing any programming languagenumSpaces- Number of space characters to pre-pend to each non-blank line- Returns:
- The same text, with the requested indentation.
- Throws:
java.lang.IllegalArgumentException- if'numSpaces'is less than 1.- Code:
- Exact Method Body:
return IndentNonBlankLines.run(srcCode, numSpaces, false);
-
indentNonBlankAndTrim
public static java.lang.String indentNonBlankAndTrim (java.lang.String srcCode, byte numSpaces)
Indents each, non-blank, line of input text'srcCode', by the number of spaces'numSpaces'.This method also performs a white-spacetrim()on each line which only contains whitespace.- Parameters:
srcCode- Any text-file or snippet containing any programming languagenumSpaces- Number of space characters to pre-pend to each non-blank line- Returns:
- The same text, with the requested indentation.
- Throws:
java.lang.IllegalArgumentException- if'numSpaces'is less than 1.- Code:
- Exact Method Body:
return IndentNonBlankLines.run(srcCode, numSpaces, true);
-
-