Drop StringUtils and Utilities

This commit is contained in:
FooIbar authored and tarsin committed 2023-06-22 10:01:41 +08:00
1 parent 09cd08bfaa
commit 3f484a49e8
9 files changed
+36 -355

No files matched your search

@@ -16,7 +16,6 @@
package com.hippo.ehviewer.client.data
import android.os.Parcelable
import android.text.TextUtils
import androidx.annotation.IntDef
import com.hippo.ehviewer.client.EhUrl
import com.hippo.ehviewer.client.EhUtils
@@ -25,7 +24,6 @@ import com.hippo.ehviewer.network.UrlBuilder
import com.hippo.ehviewer.ui.legacy.AdvanceSearchTable
import com.hippo.ehviewer.util.encodeUTF8
import com.hippo.ehviewer.yorozuya.NumberUtils
import com.hippo.ehviewer.yorozuya.StringUtils
import kotlinx.parcelize.Parcelize
import java.io.UnsupportedEncodingException
import java.net.URLDecoder
@@ -116,7 +114,7 @@ data class ListUrlBuilder(
if (q.category != this.category) {
return false
}
if (!StringUtils.equals(q.keyword, mKeyword)) {
if (q.keyword != mKeyword) {
return false
}
if (q.advanceSearch != advanceSearch) {
@@ -138,10 +136,10 @@ data class ListUrlBuilder(
// TODO page
fun setQuery(query: String?) {
reset()
if (TextUtils.isEmpty(query)) {
if (query.isNullOrEmpty()) {
return
}
val queries = StringUtils.split(query, '&')
val queries = query.split('&')
var category = 0
var keyword: String? = null
var enableAdvanceSearch = false
@@ -296,7 +294,7 @@ data class ListUrlBuilder(
}
// Search key
// the settings of ub:UrlBuilder may be overwritten by following Advance search
StringUtils.split(mKeyword, '|')?.forEachIndexed { idx, kwd ->
mKeyword?.split('|')?.forEachIndexed { idx, kwd ->
val keyword = kwd.trim { it <= ' ' }
when (idx) {
0 -> keyword.takeIf { it.isNotEmpty() }
@@ -36,7 +36,6 @@ import com.hippo.ehviewer.client.exception.PiningException
import com.hippo.ehviewer.client.getThumbKey
import com.hippo.ehviewer.util.ExceptionUtils
import com.hippo.ehviewer.yorozuya.NumberUtils
import com.hippo.ehviewer.yorozuya.StringUtils
import com.hippo.ehviewer.yorozuya.trimAnd
import com.hippo.ehviewer.yorozuya.unescapeXml
import org.jsoup.Jsoup
@@ -156,7 +155,7 @@ object GalleryDetailParser {
val gdn = gm.getElementById("gdn")
if (null != gdn) {
gd.disowned = gdn.attr("style").contains("opacity:0.5")
gd.uploader = StringUtils.trim(gdn.text())
gd.uploader = gdn.text().trim()
} else {
gd.uploader = ""
}
@@ -176,7 +175,7 @@ object GalleryDetailParser {
val ratingCount = gm.getElementById("rating_count")
if (null != ratingCount) {
gd.ratingCount = NumberUtils.parseIntSafely(
StringUtils.trim(ratingCount.text()),
ratingCount.text().trim(),
0,
)
} else {
@@ -186,7 +185,7 @@ object GalleryDetailParser {
// Rating
val ratingLabel = gm.getElementById("rating_label")
if (null != ratingLabel) {
val ratingStr = StringUtils.trim(ratingLabel.text())
val ratingStr = ratingLabel.text().trim()
if ("Not Yet Rated" == ratingStr) {
gd.rating = -1.0f
} else {
@@ -205,12 +204,12 @@ object GalleryDetailParser {
val gdf = gm.getElementById("gdf")
gd.isFavorited = false
if (gdf != null) {
val favoriteName = StringUtils.trim(gdf.text())
val favoriteName = gdf.text().trim()
if (favoriteName == "Add to Favorites") {
gd.favoriteName = null
} else {
gd.isFavorited = true
gd.favoriteName = StringUtils.trim(gdf.text())
gd.favoriteName = gdf.text().trim()
PATTERN_FAVORITE_SLOT.find(body)?.run {
gd.favoriteSlot = ((groupValues[1].toIntOrNull() ?: 2) - 2) / 19
}
@@ -233,7 +232,7 @@ object GalleryDetailParser {
if (result != null) {
gi.gid = result.gid
gi.token = result.token
gi.title = StringUtils.trim(element.text())
gi.title = element.text().trim()
gi.posted = dates[index]
gd.newerVersions.add(gi)
}
@@ -246,8 +245,8 @@ object GalleryDetailParser {
if (es.size < 2) {
return
}
val key = StringUtils.trim(es[0].text())
val value = StringUtils.trim(es[1].ownText())
val key = es[0].text().trim()
val value = es[1].ownText().trim()
if (key.startsWith("Posted")) {
gd.posted = value
} else if (key.startsWith("Parent")) {
@@ -354,12 +353,12 @@ object GalleryDetailParser {
when (e.text()) {
"Vote+" -> {
comment.voteUpAble = true
comment.voteUpEd = StringUtils.trim(e.attr("style")).isNotEmpty()
comment.voteUpEd = e.attr("style").trim().isNotEmpty()
}
"Vote-" -> {
comment.voteDownAble = true
comment.voteDownEd = StringUtils.trim(e.attr("style")).isNotEmpty()
comment.voteDownEd = e.attr("style").trim().isNotEmpty()
}
"Edit" -> comment.editable = true
@@ -369,7 +368,7 @@ object GalleryDetailParser {
// Vote state
val c7 = element.getElementsByClass("c7").first()
if (null != c7) {
comment.voteState = StringUtils.trim(c7.text())
comment.voteState = c7.text().trim()
}
// Score
val c5 = element.getElementsByClass("c5").first()
@@ -377,7 +376,7 @@ object GalleryDetailParser {
val es = c5.children()
if (!es.isEmpty()) {
comment.score = NumberUtils.parseIntSafely(
StringUtils.trim(es[0].text()),
es[0].text().trim(),
0,
)
}
@@ -16,7 +16,7 @@
package com.hippo.ehviewer.client.parser
import com.hippo.ehviewer.client.exception.ParseException
import com.hippo.ehviewer.yorozuya.StringUtils
import com.hippo.ehviewer.yorozuya.unescapeXml
import org.json.JSONException
import org.json.JSONObject
import java.util.regex.Matcher
@@ -38,22 +38,21 @@ object GalleryPageApiParser {
val i3 = jo.getString("i3")
m = PATTERN_IMAGE_URL.matcher(i3)
val imageUrl = if (m.find()) {
StringUtils.unescapeXml(StringUtils.trim(m.group(1)))
m.group(1)!!.trim().unescapeXml()
} else {
null
}
val i6 = jo.getString("i6")
m = PATTERN_SKIP_HATH_KEY.matcher(i6)
val skipHathKey = if (m.find()) {
StringUtils.unescapeXml(StringUtils.trim(m.group(1)))
m.group(1)!!.trim().unescapeXml()
} else {
null
}
val i7 = jo.getString("i7")
m = PATTERN_ORIGIN_IMAGE_URL.matcher(i7)
val originImageUrl = if (m.find()) {
StringUtils.unescapeXml(m.group(1)) + "fullimg.php" +
StringUtils.unescapeXml(m.group(2))
m.group(1)!!.unescapeXml() + "fullimg.php" + m.group(2)!!.unescapeXml()
} else {
null
}
@@ -16,7 +16,7 @@
package com.hippo.ehviewer.client.parser
import com.hippo.ehviewer.client.exception.ParseException
import com.hippo.ehviewer.yorozuya.StringUtils
import com.hippo.ehviewer.yorozuya.unescapeXml
import java.util.regex.Pattern
object GalleryPageParser {
@@ -31,20 +31,19 @@ object GalleryPageParser {
fun parse(body: String): Result {
var m = PATTERN_IMAGE_URL.matcher(body)
val imageUrl = if (m.find()) {
StringUtils.unescapeXml(StringUtils.trim(m.group(1)))
m.group(1)!!.trim().unescapeXml()
} else {
null
}
m = PATTERN_SKIP_HATH_KEY.matcher(body)
val skipHathKey = if (m.find()) {
StringUtils.unescapeXml(StringUtils.trim(m.group(1)))
m.group(1)!!.trim().unescapeXml()
} else {
null
}
m = PATTERN_ORIGIN_IMAGE_URL.matcher(body)
val originImageUrl = if (m.find()) {
StringUtils.unescapeXml(m.group(1)) + "fullimg.php" +
StringUtils.unescapeXml(m.group(2))
m.group(1)!!.unescapeXml() + "fullimg.php" + m.group(2)!!.unescapeXml()
} else {
null
}
@@ -16,7 +16,7 @@
package com.hippo.ehviewer.client.parser
import com.hippo.ehviewer.yorozuya.NumberUtils
import com.hippo.ehviewer.yorozuya.StringUtils
import com.hippo.ehviewer.yorozuya.unescapeXml
import java.time.Instant
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
@@ -32,7 +32,7 @@ object ParserUtils {
}
fun trim(str: String?): String {
return str?.let { StringUtils.unescapeXml(it).trim() } ?: ""
return str?.unescapeXml()?.trim() ?: ""
}
fun parseInt(str: String?, defValue: Int): Int {
@@ -89,7 +89,6 @@ import com.hippo.ehviewer.util.getParcelableCompat
import com.hippo.ehviewer.util.toBBCode
import com.hippo.ehviewer.yorozuya.AnimationUtils
import com.hippo.ehviewer.yorozuya.SimpleAnimatorListener
import com.hippo.ehviewer.yorozuya.StringUtils
import com.hippo.ehviewer.yorozuya.collect.IntList
import eu.kanade.tachiyomi.util.lang.launchIO
import eu.kanade.tachiyomi.util.lang.withUIContext
@@ -357,21 +356,21 @@ class GalleryCommentsScene : BaseToolbarScene(), View.OnClickListener, OnRefresh
}
@SuppressLint("InflateParams")
fun showVoteStatusDialog(context: Context, voteStatus: String?) {
val temp = StringUtils.split(voteStatus, ',')
fun showVoteStatusDialog(context: Context, voteStatus: String) {
val temp = voteStatus.split(',')
val length = temp.size
val userArray = arrayOfNulls<String>(length)
val voteArray = arrayOfNulls<String>(length)
for (i in 0 until length) {
val str = StringUtils.trim(temp[i])
val str = temp[i].trim()
val index = str.lastIndexOf(' ')
if (index < 0) {
Log.d(TAG, "Something wrong happened about vote state")
userArray[i] = str
voteArray[i] = ""
} else {
userArray[i] = StringUtils.trim(str.substring(0, index))
voteArray[i] = StringUtils.trim(str.substring(index + 1))
userArray[i] = str.substring(0, index).trim()
voteArray[i] = str.substring(index + 1).trim()
}
}
val builder = BaseDialogBuilder(context)
@@ -442,7 +441,7 @@ class GalleryCommentsScene : BaseToolbarScene(), View.OnClickListener, OnRefresh
} else if (id == R.id.vote_down) {
voteComment(comment.id, -1)
} else if (id == R.id.check_vote_status) {
showVoteStatusDialog(context, comment.voteState)
showVoteStatusDialog(context, comment.voteState!!)
} else if (id == R.id.edit_comment) {
prepareEditComment(comment.id, text)
if (!mInAnimation && binding.editPanel.visibility != View.VISIBLE) {
@@ -539,7 +538,7 @@ class GalleryCommentsScene : BaseToolbarScene(), View.OnClickListener, OnRefresh
hypot(halfW.toDouble(), halfH.toDouble()).toFloat(),
).setDuration(300L)
animator.addListener(object : SimpleAnimatorListener() {
override fun onAnimationEnd(a: Animator) {
override fun onAnimationEnd(animation: Animator) {
mInAnimation = false
}
})
@@ -570,7 +569,7 @@ class GalleryCommentsScene : BaseToolbarScene(), View.OnClickListener, OnRefresh
0.0f,
).setDuration(300L)
animator.addListener(object : SimpleAnimatorListener() {
override fun onAnimationEnd(a: Animator) {
override fun onAnimationEnd(animation: Animator) {
if (Looper.myLooper() != Looper.getMainLooper()) {
// Some devices may run this block in non-UI thread.
// It might be a bug of Android OS.
@@ -80,7 +80,7 @@ object FileUtils {
fun sanitizeFilename(rawFilename: String): String {
// Remove forbidden_filename_characters
var filename = rawFilename
filename = StringUtils.remove(filename, FORBIDDEN_FILENAME_CHARACTERS)
filename = filename.filterNot { FORBIDDEN_FILENAME_CHARACTERS.contains(it) }
// Ensure utf-8 byte count <= 255
var byteCount = 0
@@ -107,7 +107,7 @@ object FileUtils {
}
// Trim
return StringUtils.trim(filename)
return filename.trim()
}
/**
@@ -1,272 +0,0 @@
/*
* Copyright 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.yorozuya;
import android.text.TextUtils;
import org.jsoup.parser.Parser;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public final class StringUtils {
public static final String[] EMPTY_STRING_ARRAY = new String[0];
public static final char[] WHITE_SPACE_ARRAY = {
'\u0009', // TAB
'\u0020', // SPACE
'\u00A0', // NO-BREAK SPACE
'\u3000', // IDEOGRAPHIC SPACE
};
private StringUtils() {
}
/**
* Unescape xml. It do not work perfectly.
*/
public static String unescapeXml(String str) {
return Parser.unescapeEntities(str, true);
}
/**
* <p>Replaces all occurrences of a String within another String.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *) = null
* StringUtils.replace("", *, *) = ""
* StringUtils.replace("any", null, *) = "any"
* StringUtils.replace("any", *, null) = "any"
* StringUtils.replace("any", "", *) = "any"
* StringUtils.replace("aba", "a", null) = "aba"
* StringUtils.replace("aba", "a", "") = "b"
* StringUtils.replace("aba", "a", "z") = "zbz"
* </pre>
*
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace it with, may be null
* @return the text with any replacements processed,
* {@code null} if null String input
* @see #replace(String text, String searchString, String replacement, int max)
*/
public static String replace(final String text, final String searchString, final String replacement) {
return replace(text, searchString, replacement, -1);
}
/**
* <p>Replaces a String with another String inside a larger String,
* for the first {@code max} values of the search String.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *, *) = null
* StringUtils.replace("", *, *, *) = ""
* StringUtils.replace("any", null, *, *) = "any"
* StringUtils.replace("any", *, null, *) = "any"
* StringUtils.replace("any", "", *, *) = "any"
* StringUtils.replace("any", *, *, 0) = "any"
* StringUtils.replace("abaa", "a", null, -1) = "abaa"
* StringUtils.replace("abaa", "a", "", -1) = "b"
* StringUtils.replace("abaa", "a", "z", 0) = "abaa"
* StringUtils.replace("abaa", "a", "z", 1) = "zbaa"
* StringUtils.replace("abaa", "a", "z", 2) = "zbza"
* StringUtils.replace("abaa", "a", "z", -1) = "zbzz"
* </pre>
*
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace it with, may be null
* @param max maximum number of values to replace, or {@code -1} if no maximum
* @return the text with any replacements processed,
* {@code null} if null String input
*/
public static String replace(final String text, final String searchString, final String replacement, int max) {
if (TextUtils.isEmpty(text) || TextUtils.isEmpty(searchString) || replacement == null || max == 0) {
return text;
}
int start = 0;
int end = text.indexOf(searchString, start);
if (end < 0) {
return text;
}
final int replLength = searchString.length();
int increase = replacement.length() - replLength;
increase = increase < 0 ? 0 : increase;
increase *= max < 0 ? 16 : max > 64 ? 64 : max;
final StringBuilder buf = new StringBuilder(text.length() + increase);
while (end >= 0) {
buf.append(text.substring(start, end)).append(replacement);
start = end + replLength;
if (--max == 0) {
break;
}
end = text.indexOf(searchString, start);
}
buf.append(text.substring(start));
return buf.toString();
}
/**
* <p>Splits the provided text into an array, separator specified.
* This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.split(null, *) = null
* StringUtils.split("", *) = []
* StringUtils.split("a.b.c", '.') = ["a", "b", "c"]
* StringUtils.split("a..b.c", '.') = ["a", "b", "c"]
* StringUtils.split("a:b:c", '.') = ["a:b:c"]
* StringUtils.split("a b c", ' ') = ["a", "b", "c"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChar the character used as the delimiter
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.0
*/
// Get from org.apache.commons.lang3.StringUtils
public static String[] split(final String str, final char separatorChar) {
return splitWorker(str, separatorChar, false);
}
/**
* Performs the logic for the {@code split} and
* {@code splitPreserveAllTokens} methods that do not return a
* maximum array length.
*
* @param str the String to parse, may be {@code null}
* @param separatorChar the separate character
* @param preserveAllTokens if {@code true}, adjacent separators are
* treated as empty token separators; if {@code false}, adjacent
* separators are treated as one separator.
* @return an array of parsed Strings, {@code null} if null String input
*/
// Get from org.apache.commons.lang3.StringUtils
private static String[] splitWorker(final String str, final char separatorChar, final boolean preserveAllTokens) {
// Performance tuned for 2.0 (JDK1.4)
if (str == null) {
return null;
}
final int len = str.length();
if (len == 0) {
return EMPTY_STRING_ARRAY;
}
final List<String> list = new ArrayList<>();
int i = 0, start = 0;
boolean match = false;
boolean lastMatch = false;
while (i < len) {
if (str.charAt(i) == separatorChar) {
if (match || preserveAllTokens) {
list.add(str.substring(start, i));
match = false;
lastMatch = true;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
if (match || preserveAllTokens && lastMatch) {
list.add(str.substring(start, i));
}
return list.toArray(new String[list.size()]);
}
public static String avoidNull(String value) {
return avoidNull(value, "");
}
public static String avoidNull(String value, String defaultValue) {
return value == null ? defaultValue : value;
}
public static int length(String str) {
return null == str ? 0 : str.length();
}
/**
* All null or empty, or all not
*/
public static boolean equals(String str1, String str2) {
return (TextUtils.isEmpty(str1) && TextUtils.isEmpty(str2)) ||
(!TextUtils.isEmpty(str1) && !TextUtils.isEmpty(str2) && str1.equals(str2));
}
/**
* Works like {@link String#trim()}, but more white space is excluded.
* The white space characters is {@link #WHITE_SPACE_ARRAY}.
*
* @see {@link #trim(String, char[])}
*/
public static String trim(String str) {
return trim(str, WHITE_SPACE_ARRAY);
}
/**
* Works like {@link String#trim()}, but custom characters is excluded.
*
* @see {@link #trim(String)}
*/
public static String trim(String str, char[] excluded) {
if (null == str) {
return null;
}
int start = 0, last = str.length() - 1;
int end = last;
while ((start <= end) && (Arrays.binarySearch(excluded, str.charAt(start)) >= 0)) {
start++;
}
while ((end >= start) && (Arrays.binarySearch(excluded, str.charAt(end)) >= 0)) {
end--;
}
if (start == 0 && end == last) {
return str;
}
return str.substring(start, end + 1);
}
public static String remove(String str, char[] removed) {
if (TextUtils.isEmpty(str) || null == removed || 0 == removed.length) {
return str;
}
final char[] chars = str.toCharArray();
int pos = 0;
for (int i = 0; i < chars.length; i++) {
if (!Utilities.contain(removed, chars[i])) {
chars[pos++] = chars[i];
}
}
return new String(chars, 0, pos);
}
}
@@ -1,41 +0,0 @@
/*
* Copyright 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.yorozuya;
import androidx.annotation.Nullable;
public final class Utilities {
/**
* Whether the array contain the element
*
* @param array the array
* @param ch the element
* @return true for the array contain the element
*/
public static boolean contain(@Nullable char[] array, char ch) {
if (null == array) {
return false;
}
for (char c : array) {
if (c == ch) {
return true;
}
}
return false;
}
}