You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

644 lines
26 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package de.tvo.tools;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.xmlbeans.impl.common.Levenshtein;
public class StringUtil {
public StringUtil() {
}
/*
* TODO Grundsätzlich könnten alle StringÜbergabe Parameter durch Object
* ersetzt werden. Das hätte den Grundsätzlichen Vorteil das keine Doppelten
* Funktionen notwendig wären sondern immer die Selbe Funktion aufgerufen
* wird, egal ob String oder nicht
*/
public static void main(String[] args) {
}
/**
* Function to return whether the source contains the search string or not.
*
* @param source Source to be searched
* @param search Searchstring
* @param ignoreCase Caseinsensitive or not
* @return true : Source contains search - False : Source does not contain search
*/
public static boolean searchToString(String source, String search, boolean ignoreCase) {
if (source != null && !source.isEmpty() && search != null && !search.isEmpty()) {
if (ignoreCase) {
return source.toLowerCase().contains(search.toLowerCase());
} else {
return source.contains(search);
}
} else {
return false;
}
}
public static int getPositionSearchString(String value, char search, int countSearchString) {
int position = -1;
int startPosition = 0;
int count = getCountLetter(value, search);
if (count >= countSearchString) {
for (int p = 0; p < countSearchString; p++) {
startPosition = value.indexOf(search+"", startPosition);
startPosition++;
}
position = startPosition;
}
return position;
}
public static int getCountLetter(String str, char letter) {
str = str.toLowerCase();
letter = Character.toLowerCase(letter);
int count = 0;
for (int i = 0; i < str.length(); i++) {
char currentLetter = str.charAt(i);
if (currentLetter == letter)
count++;
}
return count;
}
/**
* Cuts source by lenght
*
* @param source source to be cut
* @param length lenght to be cut
* @return
*/
public static String subStringMaxLength(String source, int length) {
source = safeTrimWithReplace(source);
if (source.length() > length) {
return source.substring(0, length);
}
return source;
}
/**
* Returns whether source is equal to search or not
*
* @param source Source to be searched
* @param search Searchstring
* @return true if equals, false if not comparable or not equals
*/
public static boolean safeEquals(String source, String search) {
if (source != null) {
return source.equals(search);
}
return false;
}
/**
* Returns whether trimmed source is equal to search or not
*
* @param source Source to be searched
* @param search Searchstring
* @return true if equals, false if not comparable or not equals
*/
public static boolean safeEqualsWithTrim(String source, String search) {
if (source != null) {
return source.trim().equals(safeTrimWithReplace(search));
}
return false;
}
// TODO fragwürdig Grundsätzlich identisch mit safeIsBlankObj, Obj
// funktioniert aber auch bei String
/**
* Returns whether the source is blank or not
*
* @param source Source to be searched
* @return true if blank or null, false not blank
*/
public static boolean safeIsBlank(String source) {
if (source != null) {
return source.trim().isEmpty();
}
return true;
}
// TODO fragwürdig Grundsätzlich identisch mit safeTrimObj, Obj funktioniert
// aber auch bei String
/**
* Function for a safe trim, nullsafe
*
* @param source Source to be trimmed
* @return trimmed String or null
*/
public static String safeTrim(String source) {
if (source != null) {
return source.trim();
}
return null;
}
/**
* Returns whether the source is blank or not
*
* @param source Source to be searched
* @return true if blank or null, false not blank
*/
public static boolean safeIsBlankObj(Object source) {
return source == null || "".equals(source.toString());
}
/**
* Function for a safe trim, nullsafe
*
* @param source Source to be trimmed
* @return trimmed String or null
*/
public static String safeTrimObj(Object source) {
if (source != null) {
return source.toString().trim();
} else {
return null;
}
}
/**
* Function for a safe trim, nullsafe, which replaces null with emptystring
*
* @param source Source to be trimmed
* @return trimmed String or empty String
*/
public static String safeTrimWithReplace(String source) {
if (source != null) {
return source.trim();
} else {
return "";
}
}
/**
* Replaces every occurance of search in source by replace. Any Regexpatterns will be escaped
*
* @param source Source to be searched
* @param search Searchstring
* @param replace Replacement of Searchstring
* @return String with replacement of search by replace or emptyString if null
*/
public static String replaceAllWithReplace(String source, String search, String replace) {
if (source == null || source.length() == 0) {
return new String("");
}
return source.replaceAll(Pattern.quote(search), replace);
}
/**
* Function that returns the Stacktrace as a String
*
* @param excep Thrown exception
* @return Stacktrace of exception or Emptrystring if null
*/
public static String getExceptionToStringWithReplace(Exception excep) {
if (excep == null)
return "";
StackTraceElement[] trace = excep.getStackTrace();
StringBuffer logBuffer = new StringBuffer();
logBuffer.append(excep + "\n");
for (int i = 0; i < trace.length; i++) {
logBuffer.append("\tat " + trace[i] + "\n");
}
return logBuffer.toString();
}
/**
* Old function that only keeps being here for transfering reason. Use fillString with Boolean!
*
* @param data The data that should be filled
* @param totaleLenght total length the String should get
* @param fillWith what is the filling character supposed to be
* @param isRight Is the data supposed to be right of the filling
* @return Filled Data
*/
static public String fillString(Object data, int totaleLenght, String fillWith, String rechtslinks) {
return fillString(data, totaleLenght, fillWith, rechtslinks, false);
}
/**
* Old function that only keeps being here for transfering reason. Use fillString with Boolean!
*
* @param data The data that should be filled
* @param totaleLenght total length the String should get
* @param fillWith what is the filling character supposed to be
* @param isRight Is the data supposed to be right of the filling
* @return Filled Data
*/
static public String fillString(Object data, int totaleLenght, String fillWith, String rechtslinks, boolean sendError) {
if (rechtslinks.equalsIgnoreCase("left")||rechtslinks.equalsIgnoreCase("links")) {
return fillString(data, totaleLenght, fillWith, false);
} else if (rechtslinks.equalsIgnoreCase("right")||rechtslinks.equalsIgnoreCase("rechts")) {
return fillString(data, totaleLenght, fillWith, true);
}
if (sendError) {
System.out.println("Ausrichtungsfehler: " + rechtslinks);
}
if (data != null) {
return data.toString();
}
return "";
}
/**
* Function to fill up a String with a given Character to either the right
* or the left
*
* @param data The data that should be filled
* @param totaleLenght total length the String should get
* @param fillWith what is the filling character supposed to be
* @param isRight Is the data supposed to be right of the filling
* @return Filled Data
*/
static public String fillString(Object data, int totaleLenght, String fillWith, boolean isRight) {
StringBuffer stringFueller = new StringBuffer();
if (data == null) {
data = "";
}
for (int i = 0; i < totaleLenght - data.toString().length(); ++i) {
stringFueller.append(fillWith);
}
return isRight ? stringFueller.toString() + data : data + stringFueller.toString();
}
static final private Pattern specialCharFinder = Pattern.compile("[a-zA-Z0-9]+");
/**
* Function to return wheter given String has invalid Characters or not
*
* @return true if there is no Special char, false if there is a special char
*/
static public boolean noSpecialChars(String checkString){
return specialCharFinder.matcher(checkString).matches();
}
public static String safeTrimObjWithReplace(Object text){
if (text != null) {
return text.toString().trim();
} else {
return "";
}
}
/**
* Check E-Mail Adresse with RFC Standard Pattern
* @param emails One E-Mail or E-Mails seperated with Semikolon
* @return True = valid; or False = not valid
*/
public static boolean checkEmailRFC(String emails) {
boolean result = false;
if (emails == null) {
return false;
}
//RFC E-Mail Adress Pattern
Pattern ptr = Pattern.compile("(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".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()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*))*)?;\\s*)");
if (emails.contains(";")) {
String[] s = emails.split(";");
for (int j = 0; j < s.length; j++) {
if (!ptr.matcher(s[j].trim()).matches()) {
return false;
} else {
result = true;
}
}
} else {
if (!ptr.matcher(emails.trim()).matches()) {
return false;
} else {
result = true;
}
}
return result;
}
/**
* Check Webadresse
* @param webadresse
* @return True = valid; or False = not valid
*/
public static boolean checkWebAdresse(String webadresse) {
String regex = "^(https?:\\/\\/)?([\\w.-]+(?:\\.[\\w\\.-]+)+)(:[0-9]{1,5})?(\\/[^\\s]*)?$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(webadresse);
return(matcher.matches());
}
public static List<String> checkIfTextContainsMails(String text) {
List<String> correctEmails = new ArrayList<>();
Matcher m = Pattern.compile("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+").matcher(text);
while (m.find()) {
correctEmails.add(m.group());
}
return correctEmails;
}
/**
* Tool to convert Umlauts into the english kind
* @param forconvert contains the string for convertion
* @return
*/
public static String convertUmlauts(final String forconvert){
if (forconvert != null && !forconvert.isEmpty()){
return forconvert.replace("ö", "oe").replace("ä", "ae").replace("ü", "ue").replace("Ö", "Oe").replace("Ä", "Ae").replace("Ü", "Ue").replace("ß", "ss");
}
return forconvert;
}
/**
* Replace umlaut's and some sonderzeichen's to HTML conform equivalents, e. g. 'Ö' gets '&Ouml;'
* @param source - the html source to be converted
* @return returns converted string or null if source was null
*/
public static String escapeHtml(String source) {
if (source == null) {
return null;
}
String s = source.replace("Ä", "&Auml;").replace("ä", "&auml;").replace("Ö", "&Ouml;").replace("ö", "&ouml;")
.replace("Ü", "&Uuml;").replace("ü", "&uuml;").replace("€", "&euro;").replace("ß", "&szlig;")
.replace("§", "&sect;");
return s;
}
/**
* Convert String to HTML (replace \n with <br /> and so on)
* Source: https://stackoverflow.com/a/42854032
* @param string
* @return
*/
public static String stringToHTMLString(String string) {
StringBuffer sb = new StringBuffer(string.length());
// true if last char was blank
boolean lastWasBlankChar = false;
int len = string.length();
char c;
for (int i = 0; i < len; i++) {
c = string.charAt(i);
if (c == ' ') {
// blank gets extra work,
// this solves the problem you get if you replace all
// blanks with &nbsp;, if you do that you loss
// word breaking
if (lastWasBlankChar) {
lastWasBlankChar = false;
sb.append("&nbsp;");
} else {
lastWasBlankChar = true;
sb.append(' ');
}
} else {
lastWasBlankChar = false;
//
// HTML Special Chars
if (c == '"')
sb.append("&quot;");
else if (c == '&')
sb.append("&amp;");
else if (c == '<')
sb.append("&lt;");
else if (c == '>')
sb.append("&gt;");
else if (c == '\n')
// Handle Newline
sb.append("<br/>");
else {
int ci = 0xffff & c;
if (ci < 160)
// nothing special only 7 Bit
sb.append(c);
else {
// Not 7 Bit use the unicode system
sb.append("&#");
sb.append(Integer.valueOf(ci).toString());
sb.append(';');
}
}
}
}
return sb.toString();
}
/**
* Uppercase the word and the 'ß' stays.<br>
* Normally when used toUppercase() it will change to 'SS'
*
* @param string
* @return
*/
public static String toUpperSpecialCharacter(String s) {
StringBuilder sb = new StringBuilder();
for(char c : s.toCharArray()) {
if (c != 'ß') {
c = Character.toUpperCase(c);
}
sb.append(c);
}
return sb.toString();
}
/**
* Sucht per Levenshtein den ähnlichsten String für searchString aus der searchList
* @param searchString - Zu suchender String
* @param searchList - List aus String
* @return den ähnlichsten String
*/
public static String findClosestMatch(final String searchString, final List<String> searchList) {
return searchList.stream()
.sorted((a, b) -> Levenshtein.distance(searchString, a) - Levenshtein.distance(searchString, b))
.findFirst()
.orElse(null);
}
/**
* Sucht per Levenshtein den ähnlichsten String für searchString aus der searchList ohne Beachtung von Groß- und Kleinschreibung
* @param searchString - Zu suchender String
* @param searchList - List aus String
* @return den ähnlichsten String
*/
public static String findClosestMatchIgnoreCase(final String searchString, final List<String> searchList) {
return searchList.stream()
.sorted((a, b) -> Levenshtein.distance(searchString.toLowerCase(), a.toLowerCase()) - Levenshtein.distance(searchString.toLowerCase(), b.toLowerCase()))
.findFirst()
.orElse(null);
}
/**
* Sucht per Levenshtein den ähnlichsten String zu einem der searchStrings aus der searchList ohne Beachtung von Groß- und Kleinschreibung
* @param searchString1 - Zu suchender String
* @param searchString2 - Zu suchender String
* @param searchList - List aus String
* @return den ähnlichsten String
*/
public static String findClosestMatchIgnoreCase(final String searchString1, final String searchString2, final List<String> searchList) {
String match1 = searchList.stream()
.sorted((a, b) -> Levenshtein.distance(searchString1.toLowerCase(), a.toLowerCase()) - Levenshtein.distance(searchString1.toLowerCase(), b.toLowerCase()))
.findFirst()
.orElse(null);
if (searchString2 == null || searchString2.trim().isEmpty()) {
return match1;
}
String match2 = searchList.stream()
.sorted((a, b) -> Levenshtein.distance(searchString2.toLowerCase(), a.toLowerCase()) - Levenshtein.distance(searchString2.toLowerCase(), b.toLowerCase()))
.findFirst()
.orElse(null);
int distance1 = Levenshtein.distance(searchString1.toLowerCase(), match1.toLowerCase());
int distance2 = Levenshtein.distance(searchString2.toLowerCase(), match2.toLowerCase());
if (distance1 <= distance2) {
return match1;
}
return match2;
}
/**
* @param converToCamelCase - to converted string
* @return String in Camel Case
*/
public static String getCamelCase(String converToCamelCase) {
if (converToCamelCase != null && !converToCamelCase.isEmpty()) {
StringBuilder newString = new StringBuilder(converToCamelCase.length());
for (final String StringWort : converToCamelCase.split("\\Q \\E")) {
if (newString.length() != 0) {
newString.append(' ');
}
switch (StringWort.length()) {
case 0:
break;
case 1:
newString.append(Character.toUpperCase(StringWort.charAt(0)));
break;
default:
newString.append(Character.toUpperCase(StringWort.charAt(0)));
newString.append(StringWort.substring(1).toLowerCase());
break;
}
}
converToCamelCase = newString.toString();
}
return converToCamelCase;
}
/**
* Check if the AS/400 can handle the string
* @param str
* @return if the string is valid in CP273
*/
public static boolean checkIfStringIsCP273(final String str) {
return Charset.forName("IBM01141").newEncoder().canEncode(str);
}
/**
* Removes all non CP273 chars from the string
* @param str
* @return str without of non CP273 chars
*/
public static String removeAllNonCP273Characters(final String str) {
CharsetEncoder cp273encoder = Charset.forName("IBM01141").newEncoder();
return str
.chars()
.mapToObj(i -> "" + (char) i)
.filter(i -> cp273encoder.canEncode(i))
.collect(Collectors.joining());
}
/**
* Replaces all non CP273 chars from the string
* @param str
* @return str with ASCii instead of non CP273 chars
*/
public static String replaceAllNonCP273CharactersWithAscii(final String str) {
CharsetEncoder cp273encoder = Charset.forName("IBM01141").newEncoder();
String result = "";
for (char ch : str.toCharArray()) {
if(cp273encoder.canEncode(ch)) {
result += ""+ch;
} else {
result += StringUtils.stripAccents(""+ch);
}
}
return result;
}
/**
* convertToUpperCaseExceptSharpS
* @param input
* @return
*/
public static String convertToUpperCaseExceptSharpS(String input) {
if (input == null) {
return null;
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char currentChar = input.charAt(i);
if (currentChar == 'ß') {
result.append(currentChar);
} else {
result.append(Character.toUpperCase(currentChar));
}
}
return result.toString();
}
/**
* replaceAllFromList
* @param text
* @return
*/
public static String replaceAllFromList(String text, boolean trim) {
String result = null;
// Search Replace List
List<SearchReplaceObj> searchReplaceList = new ArrayList<SearchReplaceObj>();
searchReplaceList.add(new SearchReplaceObj("", "-"));
if (trim) {
result = text.trim();
} else {
result = text;
}
for (SearchReplaceObj searchReplaceObj: searchReplaceList) {
result = StringUtil.replaceAllWithReplace(result, searchReplaceObj.getSearch(), searchReplaceObj.getReplace());
}
return result;
}
}