下面列出了怎么用org.apache.commons.lang.text.StrBuilder的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* <p>Returns the string representation of this range.</p>
*
* <p>This string is the string representation of the minimum and
* maximum numbers in the range, separated by a hyphen. If a number
* is negative, then it is enclosed in parentheses.</p>
*
* @return the string representation of this range
*/
public String toString() {
StrBuilder sb = new StrBuilder();
if (min.doubleValue() < 0) {
sb.append('(')
.append(min)
.append(')');
} else {
sb.append(min);
}
sb.append('-');
if (max.doubleValue() < 0) {
sb.append('(')
.append(max)
.append(')');
} else {
sb.append(max);
}
return sb.toString();
}
/**
* <p>Squeezes any repetitions of a character that is mentioned in the
* supplied set.</p>
*
* <p>An example is:</p>
* <ul>
* <li>squeeze("hello", {"el"}) => "helo"</li>
* </ul>
*
* @see CharSet#getInstance(java.lang.String) for set-syntax.
* @param str the string to squeeze, may be null
* @param set the character set to use for manipulation, may be null
* @return modified String, <code>null</code> if null string input
*/
public static String squeeze(String str, String[] set) {
if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set)) {
return str;
}
CharSet chars = CharSet.getInstance(set);
StrBuilder buffer = new StrBuilder(str.length());
char[] chrs = str.toCharArray();
int sz = chrs.length;
char lastChar = ' ';
char ch = ' ';
for (int i = 0; i < sz; i++) {
ch = chrs[i];
if (chars.contains(ch)) {
if ((ch == lastChar) && (i != 0)) {
continue;
}
}
buffer.append(ch);
lastChar = ch;
}
return buffer.toString();
}
/**
* <p>Gets a string representation of the character range.</p>
*
* @return string representation of this range
*/
public String toString() {
if (iToString == null) {
StrBuilder buf = new StrBuilder(4);
if (isNegated()) {
buf.append('^');
}
buf.append(start);
if (start != end) {
buf.append('-');
buf.append(end);
}
iToString = buf.toString();
}
return iToString;
}
/**
* Converts a class name to a JLS style class name.
*
* @param className the class name
* @return the converted name
*/
private static String toCanonicalName(String className) {
className = StringUtils.deleteWhitespace(className);
if (className == null) {
throw new NullArgumentException("className");
} else if (className.endsWith("[]")) {
StrBuilder classNameBuffer = new StrBuilder();
while (className.endsWith("[]")) {
className = className.substring(0, className.length() - 2);
classNameBuffer.append("[");
}
String abbreviation = (String) abbreviationMap.get(className);
if (abbreviation != null) {
classNameBuffer.append(abbreviation);
} else {
classNameBuffer.append("L").append(className).append(";");
}
className = classNameBuffer.toString();
}
return className;
}
private FixObjectCompareResult checkDirFileList(Map<String, FixFsObject> expectedChldrn, Map<String, FixFsObject> actualChldrn) {
Set<String> expectedDiff = Sets.difference(expectedChldrn.keySet(), actualChldrn.keySet());
Set<String> actualDiff = Sets.difference(actualChldrn.keySet(), expectedChldrn.keySet());
List<String> filesWithDifferentTypes = Lists.newArrayList();
for (String key : Sets.intersection(expectedChldrn.keySet(), actualChldrn.keySet())) {
FixFsObject expected = expectedChldrn.get(key);
FixFsObject actual = actualChldrn.get(key);
if (expected.isFile() != actual.isFile()) {
String message = getWrongTypeDesc(key, expected, actual);
filesWithDifferentTypes.add(message);
}
}
if (expectedDiff.isEmpty() && actualDiff.isEmpty() && filesWithDifferentTypes.isEmpty()) {
return FixObjectCompareResult.SUCCESS;
} else {
StrBuilder strBuilder = new StrBuilder();
appendMessages(expectedDiff, strBuilder, "Files found only in expected set: ");
appendMessages(actualDiff, strBuilder, "Files found only in result set: ");
appendMessages(filesWithDifferentTypes, strBuilder, "Files have different types: ");
return FixObjectCompareResult.failed(strBuilder.toString());
}
}
private static String removeEnclosure( String stringToSplit, String enclosure ) {
int firstIndex = stringToSplit.indexOf( enclosure );
int lastIndex = stringToSplit.lastIndexOf( enclosure );
if ( firstIndex == lastIndex ) {
return stringToSplit;
}
StrBuilder strBuilder = new StrBuilder( stringToSplit );
strBuilder.replace( firstIndex, enclosure.length() + firstIndex, "" );
strBuilder.replace( lastIndex - enclosure.length(), lastIndex, "" );
return strBuilder.toString();
}
static String schemaCompletion(String inputSql, String schema) throws SqlParseException {
if (inputSql == null || inputSql.equals("")) {
return "";
}
SqlNode node = CalciteParser.parse(inputSql);
// get all table node that don't have schema by visitor pattern
PushDownUtil.FromTablesVisitor ftv = new PushDownUtil.FromTablesVisitor();
node.accept(ftv);
List<SqlNode> tablesWithoutSchema = ftv.getTablesWithoutSchema();
// sql do not need completion
if (tablesWithoutSchema.isEmpty()) {
return inputSql;
}
List<Pair<Integer, Integer>> tablesPos = new ArrayList<>();
for (SqlNode tables : tablesWithoutSchema) {
tablesPos.add(CalciteParser.getReplacePos(tables, inputSql));
}
// make the behind position in the front of the list, so that the front position
// will not be affected when replaced
Collections.sort(tablesPos, new Comparator<Pair<Integer, Integer>>() {
@Override
public int compare(Pair<Integer, Integer> o1, Pair<Integer, Integer> o2) {
int r = o2.getFirst() - o1.getFirst();
return r == 0 ? o2.getSecond() - o1.getSecond() : r;
}
});
StrBuilder afterConvert = new StrBuilder(inputSql);
for (Pair<Integer, Integer> pos : tablesPos) {
String tableWithSchema = schema + "." + inputSql.substring(pos.getFirst(), pos.getSecond());
afterConvert.replace(pos.getFirst(), pos.getSecond(), tableWithSchema);
}
return afterConvert.toString();
}
private boolean extractClassFile(final String className) {
boolean classFileExtracted = false;
final File extractedClassFile = tempFile();
final String classFileName = new StrBuilder().append(className).append(".class").toString();
final String classNamePackage = classNamePackage(className);
final Set<File> packageJarFiles = packageJarFilesMappings.get(classNamePackage);
File classFileSourceJar = null;
if (packageJarFiles != null && !packageJarFiles.isEmpty()) {
final Iterator<File> packageJarFilesIt = packageJarFiles.iterator();
while (!classFileExtracted && packageJarFilesIt.hasNext()) {
final File jarFile = packageJarFilesIt.next();
try {
classFileExtracted = JarUtil.extractZipEntry(jarFile, classFileName, extractedClassFile);
if (classFileExtracted) {
classFileSourceJar = jarFile;
}
} catch (IOException e) {
throw new GradleException("failed to extract class file from jar (" + jarFile + ")", e);
}
}
if (classFileExtracted) {
LOGGER.debug("extracted class {} from {}", className, classFileSourceJar.getName());
extractedJarClasses.put(className, extractedClassFile);
}
} // super class not on the classpath - unable to scan parent class
return classFileExtracted;
}
private boolean extractClassFile(final String className) {
boolean classFileExtracted = false;
final File extractedClassFile = tempFile();
final String classFileName = new StrBuilder().append(className).append(".class").toString();
final String classNamePackage = classNamePackage(className);
final Set<File> packageJarFiles = packageJarFilesMappings.get(classNamePackage);
File classFileSourceJar = null;
if (packageJarFiles != null && !packageJarFiles.isEmpty()) {
final Iterator<File> packageJarFilesIt = packageJarFiles.iterator();
while (!classFileExtracted && packageJarFilesIt.hasNext()) {
final File jarFile = packageJarFilesIt.next();
try {
classFileExtracted = JarUtil.extractZipEntry(jarFile, classFileName, extractedClassFile);
if (classFileExtracted) {
classFileSourceJar = jarFile;
}
} catch (IOException e) {
throw new GradleException("failed to extract class file from jar (" + jarFile + ")", e);
}
}
if (classFileExtracted) {
LOGGER.debug("extracted class {} from {}", className, classFileSourceJar.getName());
extractedJarClasses.put(className, extractedClassFile);
}
} // super class not on the classpath - unable to scan parent class
return classFileExtracted;
}
/**
* <p>Gets the range as a <code>String</code>.</p>
*
* <p>The format of the String is 'Range[<i>min</i>,<i>max</i>]'.</p>
*
* @return the <code>String</code> representation of this range
*/
public String toString() {
if (toString == null) {
StrBuilder buf = new StrBuilder(32);
buf.append("Range[");
buf.append(min);
buf.append(',');
buf.append(max);
buf.append(']');
toString = buf.toString();
}
return toString;
}
/**
* <p>Gets the range as a <code>String</code>.</p>
*
* <p>The format of the String is 'Range[<i>min</i>,<i>max</i>]'.</p>
*
* @return the <code>String</code> representation of this range
*/
public String toString() {
if (toString == null) {
StrBuilder buf = new StrBuilder(32);
buf.append("Range[");
buf.append(min);
buf.append(',');
buf.append(max);
buf.append(']');
toString = buf.toString();
}
return toString;
}
/**
* <p>Gets the range as a <code>String</code>.</p>
*
* <p>The format of the String is 'Range[<i>min</i>,<i>max</i>]'.</p>
*
* @return the <code>String</code> representation of this range
*/
public String toString() {
if (toString == null) {
StrBuilder buf = new StrBuilder(32);
buf.append("Range[");
buf.append(min);
buf.append(',');
buf.append(max);
buf.append(']');
toString = buf.toString();
}
return toString;
}
/**
* <p>Gets the fraction as a <code>String</code>.</p>
*
* <p>The format used is '<i>numerator</i>/<i>denominator</i>' always.
*
* @return a <code>String</code> form of the fraction
*/
public String toString() {
if (toString == null) {
toString = new StrBuilder(32)
.append(getNumerator())
.append('/')
.append(getDenominator()).toString();
}
return toString;
}
/**
* <p>Gets the fraction as a proper <code>String</code> in the format X Y/Z.</p>
*
* <p>The format used in '<i>wholeNumber</i> <i>numerator</i>/<i>denominator</i>'.
* If the whole number is zero it will be ommitted. If the numerator is zero,
* only the whole number is returned.</p>
*
* @return a <code>String</code> form of the fraction
*/
public String toProperString() {
if (toProperString == null) {
if (numerator == 0) {
toProperString = "0";
} else if (numerator == denominator) {
toProperString = "1";
} else if (numerator == -1 * denominator) {
toProperString = "-1";
} else if ((numerator>0?-numerator:numerator) < -denominator) {
// note that we do the magnitude comparison test above with
// NEGATIVE (not positive) numbers, since negative numbers
// have a larger range. otherwise numerator==Integer.MIN_VALUE
// is handled incorrectly.
int properNumerator = getProperNumerator();
if (properNumerator == 0) {
toProperString = Integer.toString(getProperWhole());
} else {
toProperString = new StrBuilder(32)
.append(getProperWhole()).append(' ')
.append(properNumerator).append('/')
.append(getDenominator()).toString();
}
} else {
toProperString = new StrBuilder(32)
.append(getNumerator()).append('/')
.append(getDenominator()).toString();
}
}
return toProperString;
}
/**
* <p>Gets the range as a <code>String</code>.</p>
*
* <p>The format of the String is 'Range[<i>min</i>,<i>max</i>]'.</p>
*
* @return the <code>String</code> representation of this range
*/
public String toString() {
if (toString == null) {
StrBuilder buf = new StrBuilder(32);
buf.append("Range[");
buf.append(min);
buf.append(',');
buf.append(max);
buf.append(']');
toString = buf.toString();
}
return toString;
}
/**
* Implementation of delete and keep
*
* @param str String to modify characters within
* @param set String[] set of characters to modify
* @param expect whether to evaluate on match, or non-match
* @return modified String
*/
private static String modify(String str, String[] set, boolean expect) {
CharSet chars = CharSet.getInstance(set);
StrBuilder buffer = new StrBuilder(str.length());
char[] chrs = str.toCharArray();
int sz = chrs.length;
for(int i=0; i<sz; i++) {
if(chars.contains(chrs[i]) == expect) {
buffer.append(chrs[i]);
}
}
return buffer.toString();
}
/**
* <p>Gets the class name minus the package name from a String.</p>
*
* <p>The string passed in is assumed to be a class name - it is not checked.</p>
*
* @param className the className to get the short name for
* @return the class name of the class without the package name or an empty string
*/
public static String getShortClassName(String className) {
if (className == null) {
return StringUtils.EMPTY;
}
if (className.length() == 0) {
return StringUtils.EMPTY;
}
StrBuilder arrayPrefix = new StrBuilder();
// Handle array encoding
if (className.startsWith("[")) {
while (className.charAt(0) == '[') {
className = className.substring(1);
arrayPrefix.append("[]");
}
// Strip Object type encoding
if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
className = className.substring(1, className.length() - 1);
}
}
if (reverseAbbreviationMap.containsKey(className)) {
className = (String)reverseAbbreviationMap.get(className);
}
int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
int innerIdx = className.indexOf(
INNER_CLASS_SEPARATOR_CHAR, lastDotIdx == -1 ? 0 : lastDotIdx + 1);
String out = className.substring(lastDotIdx + 1);
if (innerIdx != -1) {
out = out.replace(INNER_CLASS_SEPARATOR_CHAR, PACKAGE_SEPARATOR_CHAR);
}
return out + arrayPrefix;
}
/**
* <p>Converts a given name of class into canonical format.
* If name of class is not a name of array class it returns
* unchanged name.</p>
* <p>Example:
* <ul>
* <li><code>getCanonicalName("[I") = "int[]"</code></li>
* <li><code>getCanonicalName("[Ljava.lang.String;") = "java.lang.String[]"</code></li>
* <li><code>getCanonicalName("java.lang.String") = "java.lang.String"</code></li>
* </ul>
* </p>
*
* @param className the name of class
* @return canonical form of class name
* @since 2.4
*/
private static String getCanonicalName(String className) {
className = StringUtils.deleteWhitespace(className);
if (className == null) {
return null;
} else {
int dim = 0;
while (className.startsWith("[")) {
dim++;
className = className.substring(1);
}
if (dim < 1) {
return className;
} else {
if (className.startsWith("L")) {
className = className.substring(
1,
className.endsWith(";")
? className.length() - 1
: className.length());
} else {
if (className.length() > 0) {
className = (String) reverseAbbreviationMap.get(
className.substring(0, 1));
}
}
StrBuilder canonicalClassNameBuffer = new StrBuilder(className);
for (int i = 0; i < dim; i++) {
canonicalClassNameBuffer.append("[]");
}
return canonicalClassNameBuffer.toString();
}
}
}
public String getHelp() {
StrBuilder builder = new StrBuilder();
builder.appendln("Available commands:");
for (String cmd : processors.keySet()) {
builder.append("\t").appendln(cmd);
}
return builder.toString();
}
@Override
public void process(Mxisd m, _MatrixClient client, _MatrixRoom room, CommandLine cmdLine) {
if (cmdLine.getArgList().size() != 3) {
room.sendNotice(getUsage());
return;
}
String medium = cmdLine.getArgList().get(1);
String address = cmdLine.getArgList().get(2);
if (StringUtils.isAnyBlank(medium, address)) {
room.sendNotice(getUsage());
return;
}
room.sendNotice("Processing...");
Optional<SingleLookupReply> r = m.getIdentity().find(medium, address, true);
if (!r.isPresent()) {
room.sendNotice("No result");
return;
}
SingleLookupReply lookup = r.get();
StrBuilder b = new StrBuilder();
b.append("Result for 3PID lookup of ").append(medium).append(" ").appendln(address).appendNewLine();
b.append("Matrix ID: ").appendln(lookup.getMxid().getId());
b.appendln("Validity:")
.append(" Not Before: ").appendln(lookup.getNotBefore())
.append(" Not After: ").appendln(lookup.getNotAfter());
b.appendln("Signatures:");
lookup.getSignatures().forEach((host, signs) -> {
b.append(" ").append(host).appendln(":");
signs.forEach((key, sign) -> b.append(" ").append(key).append(" -> ").appendln("OK"));
});
room.sendNotice(b.toString());
}
private boolean extractClassFile(final String className) {
boolean classFileExtracted = false;
final File extractedClassFile = tempFile();
final String classFileName = new StrBuilder().append(className).append(".class").toString();
final String classNamePackage = classNamePackage(className);
final Set<File> packageJarFiles = packageJarFilesMappings.get(classNamePackage);
File classFileSourceJar = null;
if (packageJarFiles != null && !packageJarFiles.isEmpty()) {
final Iterator<File> packageJarFilesIt = packageJarFiles.iterator();
while (!classFileExtracted && packageJarFilesIt.hasNext()) {
final File jarFile = packageJarFilesIt.next();
try {
classFileExtracted = JarUtil.extractZipEntry(jarFile, classFileName, extractedClassFile);
if (classFileExtracted) {
classFileSourceJar = jarFile;
}
} catch (IOException e) {
throw new GradleException("failed to extract class file from jar (" + jarFile + ")", e);
}
}
if (classFileExtracted) {
LOGGER.debug("extracted class {} from {}", className, classFileSourceJar.getName());
extractedJarClasses.put(className, extractedClassFile);
}
} // super class not on the classpath - unable to scan parent class
return classFileExtracted;
}
private boolean extractClassFile(final String className) {
boolean classFileExtracted = false;
final File extractedClassFile = tempFile();
final String classFileName = new StrBuilder().append(className).append(".class").toString();
final String classNamePackage = classNamePackage(className);
final Set<File> packageJarFiles = packageJarFilesMappings.get(classNamePackage);
File classFileSourceJar = null;
if (packageJarFiles != null && !packageJarFiles.isEmpty()) {
final Iterator<File> packageJarFilesIt = packageJarFiles.iterator();
while (!classFileExtracted && packageJarFilesIt.hasNext()) {
final File jarFile = packageJarFilesIt.next();
try {
classFileExtracted = JarUtil.extractZipEntry(jarFile, classFileName, extractedClassFile);
if (classFileExtracted) {
classFileSourceJar = jarFile;
}
} catch (IOException e) {
throw new GradleException("failed to extract class file from jar (" + jarFile + ")", e);
}
}
if (classFileExtracted) {
LOGGER.debug("extracted class {} from {}", className, classFileSourceJar.getName());
extractedJarClasses.put(className, extractedClassFile);
}
} // super class not on the classpath - unable to scan parent class
return classFileExtracted;
}
static String schemaCompletion(String inputSql, String schema) throws SqlParseException {
if (inputSql == null || inputSql.equals("")) {
return "";
}
SqlNode node = CalciteParser.parse(inputSql);
// get all table node that don't have schema by visitor pattern
PushDownUtil.FromTablesVisitor ftv = new PushDownUtil.FromTablesVisitor();
node.accept(ftv);
List<SqlNode> tablesWithoutSchema = ftv.getTablesWithoutSchema();
// sql do not need completion
if (tablesWithoutSchema.isEmpty()) {
return inputSql;
}
List<Pair<Integer, Integer>> tablesPos = new ArrayList<>();
for (SqlNode tables : tablesWithoutSchema) {
tablesPos.add(CalciteParser.getReplacePos(tables, inputSql));
}
// make the behind position in the front of the list, so that the front position
// will not be affected when replaced
Collections.sort(tablesPos, new Comparator<Pair<Integer, Integer>>() {
@Override
public int compare(Pair<Integer, Integer> o1, Pair<Integer, Integer> o2) {
int r = o2.getFirst() - o1.getFirst();
return r == 0 ? o2.getSecond() - o1.getSecond() : r;
}
});
StrBuilder afterConvert = new StrBuilder(inputSql);
for (Pair<Integer, Integer> pos : tablesPos) {
String tableWithSchema = schema + "." + inputSql.substring(pos.getFirst(), pos.getSecond());
afterConvert.replace(pos.getFirst(), pos.getSecond(), tableWithSchema);
}
return afterConvert.toString();
}
/**
* @see org.kuali.kfs.module.tem.batch.service.DataReportService#getMessageAsString(java.util.List)
*/
@Override
public String getMessageAsString(List<ErrorMessage> errorMessages){
List<String> messageList = new ArrayList<String>();
for (ErrorMessage error : errorMessages){
messageList.add(MessageUtils.getErrorMessage(error));
}
StrBuilder builder = new StrBuilder();
builder.appendWithSeparators(messageList, BusinessObjectReportHelper.LINE_BREAK);
return builder.toString();
}
protected String getMessageAsString(List<ErrorMessage> errorMessages){
List<String> messageList = new ArrayList<String>();
for (ErrorMessage error : errorMessages){
messageList.add(MessageUtils.getErrorMessage(error));
}
StrBuilder builder = new StrBuilder();
builder.appendWithSeparators(messageList, BusinessObjectReportHelper.LINE_BREAK);
return builder.toString();
}
private void appendMessages(Collection<String> messages, StrBuilder strBuilder, String header) {
if (messages.size() == 0) {
return;
}
if (!strBuilder.isEmpty()) {
strBuilder.appendNewLine();
}
strBuilder.append(header);
List<String> sortedMessages = Lists.newArrayList(messages);
Collections.sort(sortedMessages);
strBuilder.appendWithSeparators(sortedMessages, ", ");
}
public String generateDescription() throws IOException {
StrBuilder strBuilder = new StrBuilder();
PathToMessageProcessor pathToMessage = new PathToMessageProcessor();
TreeObjectProcessor.process(this, pathToMessage);
for (Map.Entry<Path, String> pathMessage : pathToMessage.messages.entrySet()) {
String keyText = StringUtils.isEmpty(pathMessage.getKey().toString()) ? "" : pathMessage.getKey() + " : " ;
strBuilder.appendln(keyText + pathMessage.getValue());
}
return strBuilder.toString();
}
private static String removeEnclosure( String stringToSplit, String enclosure ) {
int firstIndex = stringToSplit.indexOf( enclosure );
int lastIndex = stringToSplit.lastIndexOf( enclosure );
if ( firstIndex == lastIndex ) {
return stringToSplit;
}
StrBuilder strBuilder = new StrBuilder( stringToSplit );
strBuilder.replace( firstIndex, enclosure.length() + firstIndex, "" );
strBuilder.replace( lastIndex - enclosure.length(), lastIndex, "" );
return strBuilder.toString();
}
/**
* <p>Translate characters in a String.
* This is a multi character search and replace routine.</p>
*
* <p>An example is:</p>
* <ul>
* <li>translate("hello", "ho", "jy")
* => jelly</li>
* </ul>
*
* <p>If the length of characters to search for is greater than the
* length of characters to replace, then the last character is
* used.</p>
*
* <pre>
* CharSetUtils.translate(null, *, *) = null
* CharSetUtils.translate("", *, *) = ""
* </pre>
*
* @param str String to replace characters in, may be null
* @param searchChars a set of characters to search for, must not be null
* @param replaceChars a set of characters to replace, must not be null or empty ("")
* @return translated String, <code>null</code> if null string input
* @throws NullPointerException if <code>searchChars</code> or <code>replaceChars</code>
* is <code>null</code>
* @throws ArrayIndexOutOfBoundsException if <code>replaceChars</code> is empty ("")
* @deprecated Use {@link StringUtils#replaceChars(String, String, String)}.
* Method will be removed in Commons Lang 3.0.
* NOTE: StringUtils#replaceChars behaves differently when 'searchChars' is longer
* than 'replaceChars'. CharSetUtils#translate will use the last char of the replacement
* string whereas StringUtils#replaceChars will delete
*/
public static String translate(String str, String searchChars, String replaceChars) {
if (StringUtils.isEmpty(str)) {
return str;
}
StrBuilder buffer = new StrBuilder(str.length());
char[] chrs = str.toCharArray();
char[] withChrs = replaceChars.toCharArray();
int sz = chrs.length;
int withMax = replaceChars.length() - 1;
for(int i=0; i<sz; i++) {
int idx = searchChars.indexOf(chrs[i]);
if(idx != -1) {
if(idx > withMax) {
idx = withMax;
}
buffer.append(withChrs[idx]);
} else {
buffer.append(chrs[i]);
}
}
return buffer.toString();
}
/**
* <p>The internal method to do the formatting.</p>
*
* @param tokens the tokens
* @param years the number of years
* @param months the number of months
* @param days the number of days
* @param hours the number of hours
* @param minutes the number of minutes
* @param seconds the number of seconds
* @param milliseconds the number of millis
* @param padWithZeros whether to pad
* @return the formatted string
*/
static String format(Token[] tokens, int years, int months, int days, int hours, int minutes, int seconds,
int milliseconds, boolean padWithZeros) {
StrBuilder buffer = new StrBuilder();
boolean lastOutputSeconds = false;
int sz = tokens.length;
for (int i = 0; i < sz; i++) {
Token token = tokens[i];
Object value = token.getValue();
int count = token.getCount();
if (value instanceof StringBuffer) {
buffer.append(value.toString());
} else {
if (value == y) {
buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(years), count, '0') : Integer
.toString(years));
lastOutputSeconds = false;
} else if (value == M) {
buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(months), count, '0') : Integer
.toString(months));
lastOutputSeconds = false;
} else if (value == d) {
buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(days), count, '0') : Integer
.toString(days));
lastOutputSeconds = false;
} else if (value == H) {
buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(hours), count, '0') : Integer
.toString(hours));
lastOutputSeconds = false;
} else if (value == m) {
buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(minutes), count, '0') : Integer
.toString(minutes));
lastOutputSeconds = false;
} else if (value == s) {
buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(seconds), count, '0') : Integer
.toString(seconds));
lastOutputSeconds = true;
} else if (value == S) {
if (lastOutputSeconds) {
milliseconds += 1000;
String str = padWithZeros
? StringUtils.leftPad(Integer.toString(milliseconds), count, '0')
: Integer.toString(milliseconds);
buffer.append(str.substring(1));
} else {
buffer.append(padWithZeros
? StringUtils.leftPad(Integer.toString(milliseconds), count, '0')
: Integer.toString(milliseconds));
}
lastOutputSeconds = false;
}
}
}
return buffer.toString();
}