Show StringTools.java syntax highlighted
/*
* org.riverock.common - Supporting classes, interfaces, and utilities
*
* Copyright (C) 2006, Riverock Software, All Rights Reserved.
*
* Riverock - The Open-source Java Development Community
* http://www.riverock.org
*
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.riverock.common.tools;
import java.util.List;
import java.util.Locale;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
/**
* Public tools for work with strings.
*
* $Id: StringTools.java 1309 2007-08-16 10:10:59Z serg_main $
*/
public class StringTools {
private static Logger log = Logger.getLogger(StringTools.class);
/**
* Converts a string array to a string.
* Autor: Apache group, License: Apache2
* @param values the string array to convert.
* @return a string representing the values in the string array.
*/
public static String arrayToString(String[] values) {
StringBuilder buffer = new StringBuilder();
if (values == null) {
buffer.append("null");
} else {
buffer.append("{");
for (int i = 0; i < values.length; i++) {
buffer.append(values[i]);
if (i < values.length - 1) {
buffer.append(",");
}
}
buffer.append("}");
}
return buffer.toString();
}
public static String getUserName(String firstName, String middleName, String lastName) {
if (log.isDebugEnabled()) {
log.debug("firstName: " + firstName+ ", middleName: " +middleName+ ", lastName: " + lastName );
}
StringBuilder s = new StringBuilder();
if (StringUtils.isNotBlank(firstName)) {
s.append(firstName);
if (StringUtils.isNotBlank(middleName) || StringUtils.isNotBlank(lastName)) {
s.append(" ");
}
}
if (StringUtils.isNotBlank(middleName)) {
s.append(middleName);
if (StringUtils.isNotBlank(lastName)) {
s.append(" ");
}
}
if (StringUtils.isNotBlank(lastName)) {
s.append(lastName);
}
String result = s.toString();
if (StringUtils.isBlank(result)) {
return null;
}
else {
return result;
}
}
/**
* ïðåîáðàçóåò ñòðîêó âèäà 'SITE_LIST_SITE' -> 'SiteListSite'
* @param f String
* @return ðåçóëüòèðóþùàÿ ñòðîêà
*/
public static String capitalizeString( final String f) {
if (f.indexOf('_')==-1) {
if (f.length()==1)
return f.toUpperCase();
return StringTools.capitalizeFirstChar(f);
}
String s_ = f;
StringBuilder r = new StringBuilder();
int pos;
while ((pos = s_.indexOf('_')) != -1) {
if (pos != s_.length()) {
r.append(StringTools.capitalizeFirstChar(s_.substring(0, pos)));
s_ = s_.substring(pos + 1, s_.length());
}
}
return r.append(StringTools.capitalizeFirstChar(s_)).toString();
}
public static String capitalizeFirstChar( final String s ) {
if (s==null)
return null;
if (s.length()==0)
return "";
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
public static Locale normalizeLocale( Locale locale ) {
if (locale==null) {
return null;
}
return new Locale(
locale.getLanguage()!=null?locale.getLanguage().toLowerCase():"",
locale.getCountry()!=null?locale.getCountry().toLowerCase():"",
locale.getVariant()!=null?locale.getVariant().toLowerCase():""
);
}
/**
* Build Locale from string.
* @param locale with locale
* @return java.util.Locale
*/
public static Locale getLocale( final String locale ) {
if (locale==null) {
return null;
}
String string = locale.replace( '-', '_' );
int idx = string.indexOf('_');
if (idx == -1)
return new Locale(string.toLowerCase(), "");
String lang = string.substring(0, idx).toLowerCase();
int idx1 = string.indexOf('_', idx+1);
if (idx1==-1)
return new Locale(lang, string.substring(idx+1).toLowerCase() );
return new Locale(
lang, string.substring(idx+1, idx1).toLowerCase( ), string.substring(idx1+1).toLowerCase() );
}
public static String getMultypleString( final String str, final int multyple)
{
if (str==null || multyple==0)
return "";
StringBuilder s = new StringBuilder();
for (int i=0; i<multyple; i++)
s.append( str );
return s.toString();
}
public static String prepareToParsingSimple( final String s) {
if (s==null)
return null;
return "<para>" + StringTools.replaceStringArray(
s,
new String[][]
{
{"\n", "</para>\n<para>"},
}
) + "</para>";
}
public static String prepareToParsing( final String s) {
if (s==null)
return null;
return "<para>" + StringTools.replaceStringArray(
s,
new String[][]
{{"&", "&"},
{"<", "<"},
{">", ">"},
{"\t", "    "},
{"\n", "</para>\n<para>"},
{" ", "  "}
}
) + "</para>";
}
public static String toPlainHTML( final String s) {
if (s==null)
return null;
return StringTools.replaceStringArray(
s,
new String[][]
{{"&", "&"},
{"<", "<"},
{">", ">"},
{"\t", "    "},
{"\n", "<br>\n"},
{" ", "  "}
}
);
}
/**
* Ïðîâåðÿåò ÿâëÿåòñÿ îáúåêò òèïà String gecnsv (null) èëè ñòðîêà ïóñòàÿ è åñëè âåðíî, òî âîçâðàùàåò
* ñòðîêó ïî óìîë÷àíèþ
* @param s - String. Ñòðîêà äëÿ ïðîâåðêè
* @param def - String. Ñòðîêà, âîçâðàùàåìàÿ, åñëè ïðîâåðî÷íàÿ ñòðîêà == null èëè ïóñòàÿ
* @return - String. Íîâàÿ ñòðîêà
*/
public static String replaceEmpty( final String s, final String def) {
if (StringUtils.isEmpty(s))
return def;
else
return s;
}
/**
* Ôîðìàòèðóåò âõîäíîé ìàññèâ áàéò â ñòîëáöû ïî 76 ñèìâîëîâ. Ïðèìåíÿåòñÿ äëÿ base64 êîäèðîâàíèÿ
* @param bytes - byte[]. Âõîäíîé ìàññèâ áàéò
* @return - byte[]. Âûõîäíîé ìàññèâ áàéò, îòôîðìàòèðîâàííûé â ñòîëáöû ïî 76 áàéò.
*/
public static byte[] formatArray( final byte bytes[]) {
int newLength = bytes.length + bytes.length / 57;
if (log.isDebugEnabled())
log.debug("Old length: " + bytes.length + "\nNew length: " + newLength);
byte bf[] = new byte[newLength];
int charCount = 0;
for (int i = 0; i < bytes.length; i++)
{
//log.debug("charCount: "+charCount+" i: "+i);
bf[charCount++] = bytes[i];
// Add newline every 76 output chars (that's 57 input chars)
if ((i != 0) && (i % 57 == 0))
{
if (log.isDebugEnabled())
log.debug(" " + i + " " + charCount);
bf[charCount++] = (byte) '\n';
}
}
return bf;
}
public static byte[] getBytesUTF( final String s) {
if (s==null)
return new byte[0];
try {
return s.getBytes("utf-8");
}
catch (java.io.UnsupportedEncodingException e) {
log.warn("String.getBytes(\"utf-8\") not supported");
return new byte[0];
}
}
public static int getStartUTF( final String s, final int maxByte) {
return getStartUTF(getBytesUTF(s), maxByte);
}
public static int getStartUTF( final byte[] b, final int maxByte) {
return getStartUTF(b, maxByte, 0);
}
public static int getStartUTF( final byte[] b, final int maxByte, final int offset) {
if (b.length <= offset)
return -1;
if (b.length < maxByte)
return b.length;
int idx = Math.min(b.length, maxByte + offset);
for (int i = idx - 1; i > offset; i--)
{
int j = (b[i] < 0?0x100 + b[i]:b[i]);
if (j < 0x80)
{
return i + 1;
}
}
return -1;
}
public static int lengthUTF(String s) {
return getBytesUTF(s).length;
}
/**
* Çàìåíÿåò îäèí ôðàãìåíò ñòðîêè äðóãèì âî âñåé ñòðîêå. Ñòðîêè äëÿ ïîèñêà è çàìåíû ïåðåäàþòñÿ
* â âèäå 2-óõ ìåðíîãî ìàññèâà.
*
* @param str_ - String. Ñòðîêà â êîòîðîé ïðîèçâîäèòñÿ çàìåíà
* @param repl - String[][]. Ìàññèâ ñòðîê äëÿ ïîèñêà è çàìåíû.
* repl[][0] - ñòðîêà äëÿ ïîèñêà
* repl[][1] - ñòðîêà äëÿ çàìåíû
* @return - String. Íîâàÿ ñòðîêà
*/
public static String replaceStringArray( final String str_, final String repl[][]) {
String qqq = str_;
for (final String[] newVar : repl) {
qqq = StringUtils.replace(qqq, newVar[0], newVar[1]);
}
return qqq;
}
/**
* Ïðåîáðàçóåò ñòðîêó èç îäíîé êîäèðîâêè â äðóãóþ
* @param s - String. Ñòðîêà äëÿ ïðåîáðàçîâàíèÿ
* @param fromCharset - String. Èñõîäíàÿ êîäèðîâêà ñòðîêè
* @param toCharset - String. Ðåçóëüòèðóþùàÿ êîäèðîâêà ñòðîêè
* @return - String.
* @throws java.io.UnsupportedEncodingException
*/
public static String convertString( final String s, final String fromCharset, final String toCharset)
throws java.io.UnsupportedEncodingException {
if (s == null)
return null;
return new String(s.getBytes(fromCharset), toCharset);
}
/**
* Äîïîëíÿåò ñòðîêó ñèìâîëàìè cïðàâà èëè ñëåâà. Â çàâèñèìîñòè îò ôëàãà isLeft äîïîëíåíèå
* äåëàåòñÿ ñëåâà (true) èëè ñïðàâà (false)
* @param s - String. Ñòðîêà äëÿ äîïîëíåíèÿ
* @param ch - char. Ñèìâîë, èñïîëüçóåìûé äëÿ äîïîëíåíèÿ.
* @param countAddChar - êîëè÷åñòâî ñèìâîëîâ äëÿ äîáàâëåíèÿ.
* @param isLeft - boolean. Äîïîëíåíèå ñëåâà èëè ñïðàâà
* @return - String.
*/
public static String addString( final String s, final char ch, final int countAddChar, final boolean isLeft) {
if (s == null)
return null;
if (countAddChar==0)
return s;
StringBuilder temp = new StringBuilder();
for (int i=0; i<countAddChar; i++)
temp.append(ch);
if (isLeft)
temp.append(s);
else
temp.insert(0, s);
return temp.toString();
}
/**
* Äîïîëíÿåò ñòðîêó ñèìâîëàìè äî óêàçàííîãî êîëè÷åñòâà.  çàâèñèìîñòè îò ôëàãà isLeft äîïîëíåíèå
* äåëàåòñÿ ñëåâà (true) èëè ñïðàâà (false)
* @param s - String. Ñòðîêà äëÿ äîïîëíåíèÿ
* @param ch - char. Ñèìâîë, èñïîëüçóåìûé äëÿ äîïîëíåíèÿ.
* @param countCharInString - String. ðåçóëüòèðóþùàÿ äëèíà ñòðîêè.
* @param isLeft - boolean. Äîïîëíåíèå ñëåâà èëè ñïðàâà
* @return - String.
*/
public static String appendString( final String s, final char ch, final int countCharInString, final boolean isLeft) {
if (s == null)
return null;
if (s.length() > countCharInString)
return s.substring(0, countCharInString - 1);
StringBuilder temp = new StringBuilder();
for (int i = 0; i < (countCharInString - s.length()); i++)
temp.append(ch);
if (isLeft)
temp.append(s);
else
temp.insert(0, s);
return temp.toString();
}
/**
* Óêîðà÷èâàåò ñòðîêó äî óêàçàííîãî êîëè÷åñòâà ñèìâîëîâ
* @param s - String. Ñòðîêà äëÿ óêîðî÷åíèÿ
* @param count_char - int. Êîëè÷åñòâî ñèìâîëîâ
* @return - String. Ðåçóëüòèðóþùàÿ ñòðîêà
*/
public static String truncateString( final String s, int count_char) {
if (s == null)
return null;
if (s.length() > count_char)
return s.substring(0, count_char - 1);
else
return s;
}
public static String rewriteString( final String s_) {
if (s_ == null)
return null;
StringBuilder resultStr = new StringBuilder();
for (int i = 0; i < s_.length(); i++) {
resultStr.append('%')
.append(
convertByte(s_.substring(i, i + 1).getBytes()).toUpperCase()
);
}
return resultStr.toString();
}
/**
* Convert a byte array into a printable format containing a
* String of hexadecimal digit characters (two per byte).
*
* @param bytes - byte[] array representation
* @return String
*/
public static String convertByte( final byte bytes[]) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (final byte newVar : bytes) {
sb.append(convertDigit(newVar >> 4));
sb.append(convertDigit(newVar & 0x0f));
}
return (sb.toString());
}
private static char convertDigit( final int valueToConvert) {
int value = valueToConvert;
value &= 0x0f;
if (value >= 10)
return ((char) (value - 10 + 'a'));
else
return ((char) (value + '0'));
}
public static String rewriteURL( final String str_) {
if (str_ == null)
return null;
StringBuilder resultStr = new StringBuilder();
String rewriteStr = "'/\\%?&\"=";
String processStr;
for (int i = 0; i < str_.length(); i++) {
processStr = str_.substring(i, i + 1);
if (rewriteStr.indexOf(processStr) != -1)
processStr = "%" + convertByte(processStr.getBytes()).toUpperCase();
resultStr.append(processStr);
}
return resultStr.toString();
}
public static String getIdByString( final List list, final String defaultForNull ) {
if (list.size()==0)
return defaultForNull;
StringBuilder r = new StringBuilder();
boolean isFirst = true;
for (Object aList : list) {
if (isFirst)
isFirst = false;
else
r.append(',');
r.append(aList);
}
return r.toString();
}
}
See more files for this project here