PlotSquared/Core/src/main/java/com/plotsquared/core/util/StringMan.java

365 lines
12 KiB
Java
Raw Normal View History

/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
2020-04-15 21:26:54 +02:00
package com.plotsquared.core.util;
2015-07-05 17:44:10 +02:00
2020-07-22 21:06:23 +02:00
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.caption.Caption;
import org.checkerframework.checker.nullness.qual.NonNull;
2019-08-06 22:08:56 +02:00
2015-08-01 20:01:41 +02:00
import java.lang.reflect.Array;
import java.util.ArrayList;
2019-08-06 22:08:56 +02:00
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
2019-08-06 22:08:56 +02:00
import java.util.Map;
2015-07-05 17:44:10 +02:00
import java.util.Map.Entry;
2019-08-06 22:08:56 +02:00
import java.util.Set;
import java.util.regex.Pattern;
2015-07-05 17:44:10 +02:00
2015-09-13 06:04:31 +02:00
public class StringMan {
2016-03-23 18:16:05 +01:00
// Stolen from https://stackoverflow.com/a/366532/12620913 | Debug: https://regex101.com/r/DudJLb/1
private static final Pattern STRING_SPLIT_PATTERN = Pattern.compile("[^\\s\"]+|\"([^\"]*)\"");
2016-03-23 18:16:05 +01:00
public static String replaceFromMap(String string, Map<String, String> replacements) {
StringBuilder sb = new StringBuilder(string);
2015-07-17 12:48:13 +02:00
int size = string.length();
2016-03-23 18:16:05 +01:00
for (Entry<String, String> entry : replacements.entrySet()) {
2015-09-13 06:04:31 +02:00
if (size == 0) {
2015-07-17 12:48:13 +02:00
break;
}
2016-03-23 18:16:05 +01:00
String key = entry.getKey();
String value = entry.getValue();
2015-07-05 17:44:10 +02:00
int start = sb.indexOf(key, 0);
2015-09-13 06:04:31 +02:00
while (start > -1) {
2016-03-23 18:16:05 +01:00
int end = start + key.length();
int nextSearchStart = start + value.length();
2015-07-05 17:44:10 +02:00
sb.replace(start, end, value);
2015-07-17 12:48:13 +02:00
size -= end - start;
2015-07-05 17:44:10 +02:00
start = sb.indexOf(key, nextSearchStart);
}
}
return sb.toString();
}
2016-03-23 18:16:05 +01:00
2015-09-30 08:11:44 +02:00
public static int intersection(Set<String> options, String[] toCheck) {
int count = 0;
for (String check : toCheck) {
if (options.contains(check)) {
count++;
}
}
return count;
}
2016-03-23 18:16:05 +01:00
public static String getString(Object obj) {
2015-09-13 06:04:31 +02:00
if (obj == null) {
return "null";
}
if (obj instanceof String) {
2015-09-13 06:04:31 +02:00
return (String) obj;
}
Pull/2693 (#2694) * Commit WIP flag work. * More ported flag types, and additions to the flag API. * Make PlotFlag more generic to allow generic flag creation * Pull Captions methods into a Caption interface. * Port MusicFlag * Port flight flag * Port UntrustedVisitFlag * Port DenyExitFlag * Remove paper suggestion * Make ListFlag lists immutable * Update Flag containers. Add javadocs. Add missing methods. * Port description flag * Port greeting and farewell flags * Port weather flag * Move getExample implementation to BooleanFlag * Port reserved flags * Port all boolean flags. * Remove unused flag types * Invert liquid-flow flag * Find the real (legacy) flag name * Change NOITFY -> NOTIFY in Captions * Make IntegerFlag extendable * Port integer flags * Update Flag command to current API state * Begin remaking flag command * Create DoubleFlag + extract common parsing stuff * Supply arguments in flag parse exceptions * Implement missing flag subcommands * Update Flag command to current API state * Implement PriceFlag * Port deny-teleport * Port gamemode flags * Port BreakFlag * Port PlaceFlag * Port UseFlag * Remove old unused flag constants * Port blocked-cmds flag * Fix entity util * Port TimeFlag * Use CaptionUtility for formatting * Port keep flag * Fix imports * Reformat code * Remove unused classes * Fix MainUtil.java * Remove FlagCmd * Add flag info header and footer * Comment out flag related stuff in SchematicHandler * Remove FlagManager * Finalize Plot.java * Finalize PlotArea.java * Finalize PlotListener * Fix API issues * Fix a bunch of compile errors * Fix `/plot flag remove` * Fix initialization of GlobalFlagContainer * Apply API changes to events * Update SQLManager to new API * Invert default value for DenyExitFlag * Replace flag.getValue().toString() with flag.toString() * Make FlagContainer instance in Plot final * Fix various command issues * Clean up PlotSettings * Don't show internal flags in flag list * Fix `/plot flag add` * Remove the info inventory as it's 100% broken * Add plot info entries and fix up the default format * Fix default flag state in Captions * 781c200 part 2 * Fix odd grammar in captions * Fix odd grammar in captions v2 * Add create table statements for plot_flags * Remove old flag references in SQLManager * Use the new plot_flags table * Add tab completion to `/plot flag` * Improve parse error handling * Make flag permission check recognize parse exceptions * Initial progress towards flag conversion * Fix minor issues * Don't validate flags during flag conversion * Allow unrecognized flags to be parsed * Filter out internal flags from command sugguestions * Use the wrong caption when there's no plot description set * Limit command suggestions for boolean flags * Make blocktypelistflags accept blockcategories * Require categories to be prefixed with '#' and fix some minor display issues * Fix plot database conversion * Update PlotFlagEvent.java Updated return description * Fix command annotation wrapping * Add FLAG_UPDATE event for FlagContainer listeners * Make getParentContainer nullable * Document castUnsafe in FlagContainer * Document FlagContainer constructors * Add missing documentation to FlagContainer * Document FlagParseException * Fix wording in FlagContainer javadoc * Document InternalFlag * Document PlotFlag * Minor changes * Remove revisit comments Co-authored-by: Hannes Greule <SirYwell@users.noreply.github.com> Co-authored-by: NotMyFault <mc.cache@web.de> Co-authored-by: Matt <4009945+MattBDev@users.noreply.github.com>
2020-02-24 18:42:02 +01:00
if (obj instanceof Caption) {
2020-07-22 21:06:23 +02:00
return ((Caption) obj).getComponent(PlotSquared.platform());
Pull/2693 (#2694) * Commit WIP flag work. * More ported flag types, and additions to the flag API. * Make PlotFlag more generic to allow generic flag creation * Pull Captions methods into a Caption interface. * Port MusicFlag * Port flight flag * Port UntrustedVisitFlag * Port DenyExitFlag * Remove paper suggestion * Make ListFlag lists immutable * Update Flag containers. Add javadocs. Add missing methods. * Port description flag * Port greeting and farewell flags * Port weather flag * Move getExample implementation to BooleanFlag * Port reserved flags * Port all boolean flags. * Remove unused flag types * Invert liquid-flow flag * Find the real (legacy) flag name * Change NOITFY -> NOTIFY in Captions * Make IntegerFlag extendable * Port integer flags * Update Flag command to current API state * Begin remaking flag command * Create DoubleFlag + extract common parsing stuff * Supply arguments in flag parse exceptions * Implement missing flag subcommands * Update Flag command to current API state * Implement PriceFlag * Port deny-teleport * Port gamemode flags * Port BreakFlag * Port PlaceFlag * Port UseFlag * Remove old unused flag constants * Port blocked-cmds flag * Fix entity util * Port TimeFlag * Use CaptionUtility for formatting * Port keep flag * Fix imports * Reformat code * Remove unused classes * Fix MainUtil.java * Remove FlagCmd * Add flag info header and footer * Comment out flag related stuff in SchematicHandler * Remove FlagManager * Finalize Plot.java * Finalize PlotArea.java * Finalize PlotListener * Fix API issues * Fix a bunch of compile errors * Fix `/plot flag remove` * Fix initialization of GlobalFlagContainer * Apply API changes to events * Update SQLManager to new API * Invert default value for DenyExitFlag * Replace flag.getValue().toString() with flag.toString() * Make FlagContainer instance in Plot final * Fix various command issues * Clean up PlotSettings * Don't show internal flags in flag list * Fix `/plot flag add` * Remove the info inventory as it's 100% broken * Add plot info entries and fix up the default format * Fix default flag state in Captions * 781c200 part 2 * Fix odd grammar in captions * Fix odd grammar in captions v2 * Add create table statements for plot_flags * Remove old flag references in SQLManager * Use the new plot_flags table * Add tab completion to `/plot flag` * Improve parse error handling * Make flag permission check recognize parse exceptions * Initial progress towards flag conversion * Fix minor issues * Don't validate flags during flag conversion * Allow unrecognized flags to be parsed * Filter out internal flags from command sugguestions * Use the wrong caption when there's no plot description set * Limit command suggestions for boolean flags * Make blocktypelistflags accept blockcategories * Require categories to be prefixed with '#' and fix some minor display issues * Fix plot database conversion * Update PlotFlagEvent.java Updated return description * Fix command annotation wrapping * Add FLAG_UPDATE event for FlagContainer listeners * Make getParentContainer nullable * Document castUnsafe in FlagContainer * Document FlagContainer constructors * Add missing documentation to FlagContainer * Document FlagParseException * Fix wording in FlagContainer javadoc * Document InternalFlag * Document PlotFlag * Minor changes * Remove revisit comments Co-authored-by: Hannes Greule <SirYwell@users.noreply.github.com> Co-authored-by: NotMyFault <mc.cache@web.de> Co-authored-by: Matt <4009945+MattBDev@users.noreply.github.com>
2020-02-24 18:42:02 +01:00
}
2015-09-13 06:04:31 +02:00
if (obj.getClass().isArray()) {
StringBuilder result = new StringBuilder();
2015-08-01 20:01:41 +02:00
String prefix = "";
2016-03-23 18:16:05 +01:00
2015-09-13 06:04:31 +02:00
for (int i = 0; i < Array.getLength(obj); i++) {
result.append(prefix).append(getString(Array.get(obj, i)));
2015-08-01 20:01:41 +02:00
prefix = ",";
}
return "( " + result + " )";
2015-09-13 06:04:31 +02:00
} else if (obj instanceof Collection<?>) {
StringBuilder result = new StringBuilder();
2015-08-01 20:01:41 +02:00
String prefix = "";
2016-03-23 18:16:05 +01:00
for (Object element : (Collection<?>) obj) {
result.append(prefix).append(getString(element));
2015-08-01 20:01:41 +02:00
prefix = ",";
}
return "[ " + result + " ]";
2015-09-13 06:04:31 +02:00
} else {
2015-08-01 20:01:41 +02:00
return obj.toString();
}
}
2016-03-23 18:16:05 +01:00
public static String replaceFirst(char c, String s) {
2015-09-13 06:04:31 +02:00
if (s == null) {
return "";
}
if (s.isEmpty()) {
return s;
}
2015-07-27 06:30:50 +02:00
char[] chars = s.toCharArray();
2016-03-23 18:16:05 +01:00
char[] newChars = new char[chars.length];
2015-07-27 06:30:50 +02:00
int used = 0;
boolean found = false;
2016-03-23 18:16:05 +01:00
for (char cc : chars) {
2015-09-13 06:04:31 +02:00
if (!found && (c == cc)) {
2015-07-27 06:30:50 +02:00
found = true;
2015-09-13 06:04:31 +02:00
} else {
2015-07-27 06:30:50 +02:00
newChars[used++] = cc;
}
}
2015-09-13 06:04:31 +02:00
if (found) {
2015-07-27 06:30:50 +02:00
chars = new char[newChars.length - 1];
System.arraycopy(newChars, 0, chars, 0, chars.length);
return String.valueOf(chars);
}
return s;
}
2016-03-23 18:16:05 +01:00
public static String replaceAll(String string, Object... pairs) {
StringBuilder sb = new StringBuilder(string);
2015-09-13 06:04:31 +02:00
for (int i = 0; i < pairs.length; i += 2) {
2016-03-23 18:16:05 +01:00
String key = pairs[i] + "";
String value = pairs[i + 1] + "";
2015-07-17 12:48:13 +02:00
int start = sb.indexOf(key, 0);
2015-09-13 06:04:31 +02:00
while (start > -1) {
2016-03-23 18:16:05 +01:00
int end = start + key.length();
int nextSearchStart = start + value.length();
2015-07-17 12:48:13 +02:00
sb.replace(start, end, value);
start = sb.indexOf(key, nextSearchStart);
}
2015-07-16 16:44:27 +02:00
}
2015-07-17 12:48:13 +02:00
return sb.toString();
2015-07-16 16:44:27 +02:00
}
2016-03-23 18:16:05 +01:00
public static boolean isAlphanumeric(String str) {
2015-09-13 06:04:31 +02:00
for (int i = 0; i < str.length(); i++) {
2016-03-23 18:16:05 +01:00
char c = str.charAt(i);
2018-08-10 17:01:10 +02:00
if ((c < 0x30) || ((c >= 0x3a) && (c <= 0x40)) || ((c > 0x5a) && (c <= 0x60)) || (c
> 0x7a)) {
2015-09-13 06:04:31 +02:00
return false;
}
2015-07-26 20:38:08 +02:00
}
return true;
}
2016-03-23 18:16:05 +01:00
public static boolean isAlphanumericUnd(String str) {
2015-09-13 06:04:31 +02:00
for (int i = 0; i < str.length(); i++) {
2016-03-23 18:16:05 +01:00
char c = str.charAt(i);
2016-03-14 07:18:04 +01:00
if (c < 0x30 || (c >= 0x3a) && (c <= 0x40) || (c > 0x5a) && (c <= 0x60) || (c > 0x7a)) {
2015-09-13 06:04:31 +02:00
return false;
}
2015-08-26 06:21:48 +02:00
}
return true;
}
2016-03-23 18:16:05 +01:00
public static boolean isAlpha(String str) {
2015-09-13 06:04:31 +02:00
for (int i = 0; i < str.length(); i++) {
2016-03-23 18:16:05 +01:00
char c = str.charAt(i);
2015-09-13 06:04:31 +02:00
if ((c <= 0x40) || ((c > 0x5a) && (c <= 0x60)) || (c > 0x7a)) {
return false;
}
2015-07-26 20:38:08 +02:00
}
return true;
}
2016-03-23 18:16:05 +01:00
public static String join(Collection<?> collection, String delimiter) {
2015-07-26 20:38:08 +02:00
return join(collection.toArray(), delimiter);
}
2016-03-23 18:16:05 +01:00
public static String joinOrdered(Collection<?> collection, String delimiter) {
Object[] array = collection.toArray();
2019-08-06 22:08:56 +02:00
Arrays.sort(array, Comparator.comparingInt(Object::hashCode));
return join(array, delimiter);
}
2016-03-23 18:16:05 +01:00
public static String join(Collection<?> collection, char delimiter) {
2015-07-26 20:38:08 +02:00
return join(collection.toArray(), delimiter + "");
}
2016-03-23 18:16:05 +01:00
public static boolean isAsciiPrintable(char c) {
2015-07-26 20:38:08 +02:00
return (c >= ' ') && (c < '');
}
2016-03-23 18:16:05 +01:00
public static boolean isAsciiPrintable(String s) {
for (char c : s.toCharArray()) {
2015-09-13 06:04:31 +02:00
if (!isAsciiPrintable(c)) {
return false;
}
2015-07-26 20:38:08 +02:00
}
return true;
}
2016-03-23 18:16:05 +01:00
2015-09-13 06:04:31 +02:00
public static int getLevenshteinDistance(String s, String t) {
2015-07-26 20:38:08 +02:00
int n = s.length();
int m = t.length();
2015-09-13 06:04:31 +02:00
if (n == 0) {
2015-07-26 20:38:08 +02:00
return m;
2015-09-13 06:04:31 +02:00
} else if (m == 0) {
return n;
2015-07-26 20:38:08 +02:00
}
2015-09-13 06:04:31 +02:00
if (n > m) {
2016-03-23 18:16:05 +01:00
String tmp = s;
2015-07-26 20:38:08 +02:00
s = t;
t = tmp;
n = m;
m = t.length();
}
2019-08-06 22:08:56 +02:00
int[] p = new int[n + 1];
int[] d = new int[n + 1];
2015-07-26 20:38:08 +02:00
int i;
2015-09-13 06:04:31 +02:00
for (i = 0; i <= n; i++) {
2015-07-26 20:38:08 +02:00
p[i] = i;
}
2016-02-21 05:07:04 +01:00
for (int j = 1; j <= m; j++) {
char t_j = t.charAt(j - 1);
2015-07-26 20:38:08 +02:00
d[0] = j;
2016-03-23 18:16:05 +01:00
2015-09-13 06:04:31 +02:00
for (i = 1; i <= n; i++) {
2016-02-21 05:07:04 +01:00
int cost = s.charAt(i - 1) == t_j ? 0 : 1;
2015-09-11 12:09:22 +02:00
d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost);
2015-07-26 20:38:08 +02:00
}
2016-02-21 05:07:04 +01:00
int[] _d = p;
2015-07-26 20:38:08 +02:00
p = d;
d = _d;
}
return p[n];
}
2016-03-23 18:16:05 +01:00
public static String join(Object[] array, String delimiter) {
StringBuilder result = new StringBuilder();
2015-09-13 06:04:31 +02:00
for (int i = 0, j = array.length; i < j; i++) {
if (i > 0) {
2015-07-26 20:38:08 +02:00
result.append(delimiter);
}
result.append(array[i]);
}
return result.toString();
}
2016-03-23 18:16:05 +01:00
public static String join(int[] array, String delimiter) {
Integer[] wrapped = new Integer[array.length];
2015-09-13 06:04:31 +02:00
for (int i = 0; i < array.length; i++) {
2015-09-11 12:09:22 +02:00
wrapped[i] = array[i];
}
2015-07-27 15:10:14 +02:00
return join(wrapped, delimiter);
2015-07-27 08:20:24 +02:00
}
2016-03-23 18:16:05 +01:00
public static boolean isEqualToAny(String a, String... args) {
for (String arg : args) {
2015-09-13 06:04:31 +02:00
if (StringMan.isEqual(a, arg)) {
return true;
}
2015-07-27 15:10:14 +02:00
}
return false;
}
2016-03-23 18:16:05 +01:00
public static boolean isEqualIgnoreCaseToAny(@NonNull String a, String... args) {
2016-03-23 18:16:05 +01:00
for (String arg : args) {
2019-08-06 22:08:56 +02:00
if (a.equalsIgnoreCase(arg)) {
2015-09-13 06:04:31 +02:00
return true;
}
2015-07-27 15:10:14 +02:00
}
return false;
}
2016-03-23 18:16:05 +01:00
public static boolean isEqual(String a, String b) {
2019-04-01 17:39:28 +02:00
if ((a == null && b != null) || (a != null && b == null)) {
return false;
} else if (a == null /* implies that b is null */) {
return false;
}
return a.equals(b);
2015-07-21 19:08:51 +02:00
}
2016-03-23 18:16:05 +01:00
public static boolean isEqualIgnoreCase(String a, String b) {
2022-01-20 21:01:38 +01:00
return a.equals(b) || ((a != null) && (b != null) && (a.length() == b.length()) && a
.equalsIgnoreCase(b));
2015-07-27 15:10:14 +02:00
}
2016-03-23 18:16:05 +01:00
public static String repeat(String s, int n) {
StringBuilder sb = new StringBuilder();
2021-12-22 02:06:07 +01:00
sb.append(String.valueOf(s).repeat(Math.max(0, n)));
2015-07-26 20:38:08 +02:00
return sb.toString();
}
2016-03-29 21:47:59 +02:00
2018-08-10 17:01:10 +02:00
public static boolean contains(String name, char c) {
for (char current : name.toCharArray()) {
if (c == current) {
return true;
}
}
return false;
}
2016-06-28 12:21:50 +02:00
public <T> Collection<T> match(Collection<T> col, String startsWith) {
2016-03-29 21:47:59 +02:00
if (col == null) {
return null;
}
startsWith = startsWith.toLowerCase();
2021-05-01 18:33:02 +02:00
Iterator<?> iterator = col.iterator();
2016-03-29 21:47:59 +02:00
while (iterator.hasNext()) {
Object item = iterator.next();
if (item == null || !item.toString().toLowerCase().startsWith(startsWith)) {
iterator.remove();
}
}
return col;
}
/**
* @param message an input string
* @return a list of strings
2022-01-27 13:49:17 +01:00
* @since 6.4.0
*
* <table border="1">
* <caption>Converts multiple quoted and single strings into a list of strings</caption>
* <thead>
* <tr>
* <th>Input</th>
* <th>Output</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>title "sub title"</td>
* <td>["title", "sub title"]</td>
* </tr>
* <tr>
* <td>"a title" subtitle</td>
* <td>["a title", "subtitle"]</td>
* </tr>
* <tr>
* <td>"title" "subtitle"</td>
* <td>["title", "subtitle"]</td>
* </tr>
* <tr>
* <td>"PlotSquared is going well" the authors "and many contributors"</td>
* <td>["PlotSquared is going well", "the", "authors", "and many contributors"]</td>
* </tr>
* </tbody>
* </table>
*/
public static @NonNull List<String> splitMessage(@NonNull String message) {
var matcher = StringMan.STRING_SPLIT_PATTERN.matcher(message);
List<String> splitMessages = new ArrayList<>();
while (matcher.find()) {
splitMessages.add(matcher.group(matcher.groupCount() - 1).replaceAll("\"", ""));
}
return splitMessages;
}
2015-07-05 17:44:10 +02:00
}