com.sun.enterprise.util.StringUtils Maven / Gradle / Ivy
Show all versions of payara-micro Show documentation
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*
* Portions Copyright [2017-2019] Payara Foundation and/or affiliates
*/
package com.sun.enterprise.util;
/* WBN Valentine's Day, 2000 -- place for handy String utils.
*/
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
import java.util.*;
public class StringUtils {
public static final String NEWLINE = System.getProperty("line.separator");
public static final String EOL = NEWLINE;
private StringUtils() {
}
////////////////////////////////////////////////////////////////////////////
/**
* return the length of the String - or 0 if it's null
* @param s
* @return
*/
public static int safeLength(String s) {
if (s == null) {
return 0;
}
return s.length();
}
////////////////////////////////////////////////////////////////////////////
/**
* Returns true if a string is not null and has a non-zero length, false otherwise
* @param s
* @return
*/
public static boolean ok(String s) {
return s != null && s.length() > 0;
}
////////////////////////////////////////////////////////////////////////////
/**
* Returns a String containing SQLState, message and error code of exception and all sub-exceptions
* @param ex the exception to format
* @returnformatted exception
*/
public static String formatSQLException(SQLException ex) {
assert ex != null;
StringBuilder sb = new StringBuilder("SQLException:\n");
do {
sb.append("SQLState: ").append(ex.getSQLState()).append('\n');
sb.append("Message: ").append(ex.getMessage()).append('\n');
sb.append("Vendor: ").append(ex.getErrorCode()).append('\n');
sb.append('\n');
}
while ((ex = ex.getNextException()) != null);
return sb.toString();
}
////////////////////////////////////////////////////////////////////////////
/**
* Find longest String in a List of Strings...
* @param strings the list of strings
* @returnthe index of the longest string
*/
public static int maxWidth(List strings) {
int max = 0;
if (strings == null || strings.isEmpty() || !(strings.get(0) instanceof String)) {
return 0;
}
for (int i = strings.size() - 1; i >= 0; i--) {
int len = ((String) strings.get(i)).length();
if (len > max) {
max = len;
}
}
return max;
}
////////////////////////////////////////////////////////////////////////////
/** Is this the String representation of a valid hex number?
"5", "d", "D", "F454ecbb" all return true..
* @param s.**/
// p.s. there MUST be a better and faster way of doing this...
public static boolean isHex(String s) {
if (s == null) return false;
final int slen = s.length();
for (int i = 0; i < slen; i++) {
if (!isHex(s.charAt(i))) {
return false;
}
}
return true;
}
////////////////////////////////////////////////////////////////////////////
private static final String HEX_CHARS = "0123456789abcdefABCDEF";
/**
* Is this the char a valid hex digit?
*
* Can be upper or lower case
* @param c
* @return
*/
public static boolean isHex(char c) {
return HEX_CHARS.indexOf(c) != -1;
}
////////////////////////////////////////////////////////////////////////////
/**
* e.g. input: "a/b/c/d/foobar.txt" output: "d"
* @param s
* @return
*/
public static String getPenultimateDirName(String s) {
if (s == null || s.length() <= 0) {
return s;
}
// must be a plain file name -- return empty string...
if ((s.indexOf('/') < 0) && (s.indexOf('\\') < 0)) {
return "";
}
s = s.replace('\\', '/'); // make life easier for the next steps...
int index = s.lastIndexOf('/');
if (index < 0) {
return ""; // can't happen!!!
}
s = s.substring(0, index); // this will truncate the last '/'
index = s.lastIndexOf('/');
if (index >= 0) {
s = s.substring(index + 1);
}
return s;
}
////////////////////////////////////////////////////////////////////////////
/**
* Returns the classname without package info
*
* i.e. java.lang.String would return String
* @param className The classname to convert. Note that there is no checking that this is a valid classname.
* @return
*/
public static String toShortClassName(String className) {
int index = className.lastIndexOf('.');
if (index >= 0 && index < className.length() - 1) {
return className.substring(index + 1);
}
return className;
}
////////////////////////////////////////////////////////////////////////////
/**
* Adds spaces to the end of a string to make it reach the specified length.
*
* If the string is longer than the padded length then this function will return the original string.
* @param s String to pad
* @param len The length of the string with added padding
* @return The padded string
*/
public static String padRight(String s, int len) {
if (s == null || s.length() >= len) {
return s;
}
StringBuilder sb = new StringBuilder(s);
for (int i = len - s.length(); i > 0; --i) {
sb.append(' ');
}
return sb.toString();
}
////////////////////////////////////////////////////////////////////////////
/**
* Adds spaces to the front of a string to make it reach the specified length.
*
* If the string is longer than the padded length then this function will return the original string.
* @param s String to pad
* @param len The length of the string with added padding
* @return The padded string
*/
public static String padLeft(String s, int len) {
if (s == null || s.length() >= len) {
return s;
}
StringBuilder sb = new StringBuilder();
for (int i = len - s.length(); i > 0; --i) {
sb.append(' ');
}
return sb.append(s).toString();
}
////////////////////////////////////////////////////////////////////////////
/**
* Converts a String into an array where every \n is a new used to signal a new element in the array
* @param s string to split into lines
* @returnthe resulting lines array
*/
public static String[] toLines(String s) {
if (s == null) {
return new String[0];
}
List lines = new ArrayList<>();
int start = 0;
int end = 0;
for (end = s.indexOf('\n', start); end >= 0 && start < s.length(); end = s.indexOf('\n', start)) {
lines.add(s.substring(start, end)); // does NOT include the '\n'
start = end + 1;
}
if (start < s.length()) {
lines.add(s.substring(start));
}
return lines.toArray(new String[0]);
}
////////////////////////////////////////////////////////////////////////////
/**
* Puts a string before every element in an array
*
* i.e. {@code prepend(new String["foo", "bar"],"not ")} would result in {@code String["not foo", "not bar"]}
* @param ss
* @param what
*/
public static void prepend(String[] ss, String what) {
for (int i = 0; i < ss.length; i++) {
ss[i] = what + ss[i];
}
}
////////////////////////////////////////////////////////////////////////////
/**
* Converts the first letter of a string to upper case
* @param s
* @return
*/
public static String upperCaseFirstLetter(String s) {
if (s == null || s.length() <= 0) {
return s;
}
return s.substring(0, 1).toUpperCase(Locale.getDefault()) + s.substring(1);
}
////////////////////////////////////////////////////////////////////////////
/**
* Replaces the first instance of a token within a string
* @param s The string to operate on
* @param token the token to be replaced
* @param replace the new value
* @return
* @deprecated Now part of {@link String} since JDK 1.5
* @see String#replace(CharSequence, CharSequence)
* @see String#replaceFirst(String, String)
*/
public static String replace(String s, String token, String replace) {
if (s == null || s.length() <= 0 || token == null || token.length() <= 0) {
return s;
}
int index = s.indexOf(token);
if (index < 0) {
return s;
}
int tokenLength = token.length();
String ret = s.substring(0, index);
ret += replace;
ret += s.substring(index + tokenLength);
return ret;
}
////////////////////////////////////////////////////////////////////////////
/**
* Converts a {@link Properties} object to string
*
* If there it is empty then this will return "No entries".
* Otherwise it will be in the form of "key= value" with each property on a new line.
* @param props
* @return
*/
public static String toString(Properties props) {
if (props == null || props.size() <= 0) {
return "No entries";
}
Set> entries = props.entrySet();
StringBuilder sb = new StringBuilder();
// first -- to line things up nicely -- find the longest key...
int keyWidth = 0;
for (Map.Entry