下面列出了org.apache.commons.lang3.StringUtils#leftPad ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testFilenamePattern() {
final String invalidPattern = "${filename}_${${pageId}_${pageNr}";
Assert.assertFalse("Filename pattern was erroneously evaluated to be valid: " + invalidPattern,
ExportFilePatternUtils.isFileNamePatternValid(invalidPattern));
final String validPattern = "${filename}_${pageId}_${pageNr}";
Assert.assertTrue("Filename pattern was erroneously evaluated to be invalid: " + validPattern,
ExportFilePatternUtils.isFileNamePatternValid(validPattern));
final String exampleFilename = "test.jpg";
final String exampleBaseName = FilenameUtils.getBaseName(exampleFilename);
final int pageNr = 7;
final String actualResult = ExportFilePatternUtils.buildBaseFileName(validPattern, exampleFilename, 123, 456, "AAAAA", pageNr);
//ExportFilePatternUtils will leftpad the pageNr
final String pageIdStr = StringUtils.leftPad(""+pageNr, ExportFilePatternUtils.PAGE_NR_LEFTPAD_TO_SIZE, '0');
final String expectedResult = exampleBaseName + "_123_" + pageIdStr;
Assert.assertEquals(expectedResult, actualResult);
try {
String thisShouldNeverBeAssigned = ExportFilePatternUtils.buildBaseFileName(invalidPattern, exampleFilename, 123, 456, "AAAAA", 7);
Assert.fail("The filename '" + thisShouldNeverBeAssigned + "' was created by pattern '" + invalidPattern +"' although it was evaluated to be invalid!");
} catch (IllegalArgumentException e) {
//IllegalArgumentException == success
}
}
/**
* Sets the nanoseconds within the current second
* <p>
* Note that this method sets the
* same value as {@link #setMillis(int)} but with more precision.
* </p>
*/
public BaseDateTimeType setNanos(long theNanos) {
validateValueInRange(theNanos, 0, NANOS_PER_SECOND - 1);
String fractionalSeconds = StringUtils.leftPad(Long.toString(theNanos), 9, '0');
// Strip trailing 0s
for (int i = fractionalSeconds.length(); i > 0; i--) {
if (fractionalSeconds.charAt(i - 1) != '0') {
fractionalSeconds = fractionalSeconds.substring(0, i);
break;
}
}
int millis = (int) (theNanos / NANOS_PER_MILLIS);
setFieldValue(Calendar.MILLISECOND, millis, fractionalSeconds, 0, 999);
return this;
}
@ServiceMethodAuthority(type={ServiceMethodType.SELECT})
@Transactional(propagation=Propagation.REQUIRES_NEW, readOnly=true)
@Override
public String findForMaxPerId(String date) throws ServiceException, Exception {
if (super.isBlank(date) || !NumberUtils.isCreatable(date) || date.length()!=8 ) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK));
}
String maxVisionId = this.perspectiveService.findForMaxPerId(BscConstants.HEAD_FOR_PER_ID+date);
if (StringUtils.isBlank(maxVisionId)) {
return BscConstants.HEAD_FOR_PER_ID + date + "001";
}
int maxSeq = Integer.parseInt( maxVisionId.substring(11, 14) ) + 1;
if ( maxSeq > 999 ) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_ERRORS) + " over max seq 999!");
}
return BscConstants.HEAD_FOR_PER_ID + date + StringUtils.leftPad(String.valueOf(maxSeq), 3, "0");
}
public String createTextOnLine(String text, char space, String alignment, int charsOnLine) {
if (text.length() > charsOnLine) {
StringBuilder out = new StringBuilder();
int len = text.length();
for (int i = 0; i <= len / charsOnLine; i++) {
String str = text.substring(i * charsOnLine, Math.min((i + 1) * charsOnLine, len));
if (!str.trim().isEmpty()) {
out.append(createTextOnLine(str, space, alignment));
}
}
return out.toString();
}
switch (alignment) {
case TEXT_ALIGNMENT_RIGHT:
return StringUtils.leftPad(text, charsOnLine, space) + "\n";
case TEXT_ALIGNMENT_CENTER:
return StringUtils.center(text, charsOnLine, space) + "\n";
default:
return StringUtils.rightPad(text, charsOnLine, space) + "\n";
}
}
public String formatOffset(final NakadiCursor nakadiCursor) {
if (nakadiCursor.getOffset().equals("-1")) {
// TODO: Before old should be calculated differently
return Cursor.BEFORE_OLDEST_OFFSET;
} else {
return StringUtils.leftPad(nakadiCursor.getOffset(), VERSION_ZERO_MIN_OFFSET_LENGTH, '0');
}
}
private static String readableFileSize(File file) {
long size = FileUtils.sizeOf(file);
if (size <= 0) {
return "0";
}
final String[] units = new String[]{"B", "kB", "MB", "GB", "TB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return StringUtils.leftPad(new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)), 8) + " " + units[digitGroups];
}
@Override
public String findForMaxMailIdComplete(String mailId) throws ServiceException, Exception {
if (StringUtils.isBlank(mailId) || !SimpleUtils.isDate(mailId)) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK));
}
String maxMailId = this.findForMaxMailId(mailId);
if (StringUtils.isBlank(maxMailId)) {
return mailId + "000000001";
}
int maxSeq = Integer.parseInt( maxMailId.substring(8, 17) ) + 1;
if (maxSeq > 999999999) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_ERRORS) + " over max mail-id 999999999!");
}
return mailId + StringUtils.leftPad(String.valueOf(maxSeq), 9, "0");
}
/**
* Return the finalised digest as a 32 byte hex string. It's important
* elsewhere and in the server that the string be exactly 32 bytes long, so
* we stitch it up if possible to make it that long...
*/
public String digestAs32ByteHex() {
String retStr = new BigInteger(1, messageDigest.digest()).toString(16).toUpperCase();
if (retStr.length() > 0 && (retStr.length() <= LENGTH_OF_HEX_STRING)) {
return StringUtils.leftPad(retStr, LENGTH_OF_HEX_STRING, '0');
} else {
throw new P4JavaError("Bad 32 byte digest string size in MD5Digester.digestAs32ByteHex;"
+ " string: " + retStr + ";" + " length: " + retStr.length());
}
}
private String renderDay(int day) {
String value = String.valueOf(day);
if ("numeric-leading-zeros".equals(form)) {
value = StringUtils.leftPad(value, 2, '0');
}
return value;
}
/**
* @param hoursExpression
* @param minutesExpression
* @param secondsExpression
* @return
*/
public static String formatTime(String hoursExpression, String minutesExpression, String secondsExpression) {
int hour = Integer.parseInt(hoursExpression);
String amPM = hour >= 12 ? "PM" : "AM";
if (hour > 12) {
hour -= 12;
}
String minute = String.valueOf(Integer.parseInt(minutesExpression));
String second = "";
if (!StringUtils.isEmpty(secondsExpression)) {
second = ":" + StringUtils.leftPad(String.valueOf(Integer.parseInt(secondsExpression)), 2, '0');
}
return MessageFormat.format("{0}:{1}{2} {3}", String.valueOf(hour), StringUtils.leftPad(minute, 2, '0'), second, amPM);
}
/**
* [身份证号] 显示最后四位,其他隐藏。共计18位或者15位。<例子:*************5762>.
*
* @param id
* the id
* @return the string
*/
public static String idCardNum(String id){
if (StringUtils.isBlank(id)){
return "";
}
String num = StringUtils.right(id, 4);
return StringUtils.leftPad(num, StringUtils.length(id), "*");
}
/**
* Returns the full salt in a {@code byte[]} for this cipher provider (i.e. {@code $2a$10$abcdef...} format).
*
* @return the full salt as a byte[]
*/
@Override
public byte[] generateSalt() {
byte[] salt = new byte[DEFAULT_SALT_LENGTH];
SecureRandom sr = new SecureRandom();
sr.nextBytes(salt);
// TODO: This library allows for 2a, 2b, and 2y versions so this should be changed to be configurable
String saltString = "$2a$" +
StringUtils.leftPad(String.valueOf(workFactor), 2, "0") +
"$" + new String(new Radix64Encoder.Default().encode(salt), StandardCharsets.UTF_8);
return saltString.getBytes(StandardCharsets.UTF_8);
}
public static final String getStrYMD(final int type) {
Calendar calendar=Calendar.getInstance();
if (type==SimpleUtils.IS_YEAR) {
return calendar.get(Calendar.YEAR)+"";
}
if (type==SimpleUtils.IS_MONTH) {
return StringUtils.leftPad((calendar.get(Calendar.MONTH)+1 )+"", 2, "0");
}
if (type==SimpleUtils.IS_DAY) {
return StringUtils.leftPad(calendar.get(Calendar.DAY_OF_MONTH)+"", 2, "0");
}
return calendar.get(Calendar.YEAR)+"";
}
private String printWinners(List<AwardWinner> winners) {
String dispFormat = race.getStringAttribute("TimeDisplayFormat");
String roundMode = race.getStringAttribute("TimeRoundingMode");
Integer dispFormatLength; // add a space
if (dispFormat.contains("[HH:]")) dispFormatLength = dispFormat.length()-1; // get rid of the two brackets and add a space
else dispFormatLength = dispFormat.length()+1;
String report = new String();
for(AwardWinner aw: winners) {
report += StringUtils.center(aw.awardPlace.toString(),6); // 4R chars
report += StringUtils.rightPad(aw.participant.fullNameProperty().getValue(),fullNameLength.get()); // based on the longest name
report += StringUtils.leftPad(aw.participant.getBib(),5); // 5R chars for the bib #
report += StringUtils.leftPad(aw.participant.getAge().toString(),4); // 4R for the age
report += StringUtils.center(aw.participant.getSex(),5); // 4R for the sex
report += StringUtils.rightPad(aw.processedResult.getAGCode(),5); //6L for the AG Group
report += " ";
report += StringUtils.rightPad(aw.participant.getCity(),18); // 18L for the city
if (showState.get()) report += StringUtils.center(aw.participant.getState(),4); // 4C for the state code
if (showCountry.get()) report += StringUtils.leftPad(aw.participant.getCountry(),4); // 4C for the state code
if (showCustomAttributes) {
for( CustomAttribute a: customAttributesList){
report += StringUtils.rightPad(" " + aw.participant.getCustomAttribute(a.getID()).getValueSafe(),customAttributeSizeMap.get(a.getID()));
}
}
report += StringUtils.leftPad(DurationFormatter.durationToString(aw.awardTime, dispFormat, roundMode), dispFormatLength);
report += System.lineSeparator();
}
return report;
}
private String printHeader(){
String dispFormat = race.getStringAttribute("TimeDisplayFormat");
Integer dispFormatLength = dispFormat.length()+1; // add a space
if (dispFormat.contains("[HH:]")) dispFormatLength = dispFormat.length()-1; // get rid of the two brackets and add a space
Pace pace = Pace.valueOf(race.getStringAttribute("PaceDisplayFormat"));
String report = new String();
// print the headder
report += " OA#"; // 4R chars
report += " SEX#"; // 5R chars
report += " AG#"; // 5R chars
report += " BIB"; // 5R chars for the bib #
report += " AGE"; // 4R for the age
report += " SEX"; // 4R for the sex
report += " AG "; //6L for the AG Group
report += StringUtils.rightPad(" Name",fullNameLength.get()); // based on the longest name
report += " City "; // 18L for the city
if (showState.get() )report += " ST "; // 4C for the state code
if (showCountry.get() )report += " CO "; // 4C for the state code
if (showCustomAttributes) {
for( CustomAttribute a: customAttributesList){
report += StringUtils.rightPad(a.getName(),customAttributeSizeMap.get(a.getID()));
}
}
// Insert split stuff here
if (showSplits) {
// do stuff
// 9 chars per split
for (int i = 2; i < race.splitsProperty().size(); i++) {
if (!race.splitsProperty().get(i-1).getIgnoreTime()) report += StringUtils.leftPad(race.splitsProperty().get(i-1).getSplitName(),dispFormatLength);
}
}
if (showSegments) {
final StringBuilder chars = new StringBuilder();
Integer dispLeg = dispFormatLength;
race.raceSegmentsProperty().forEach(seg -> {
if(seg.getHidden() ) return;
chars.append(StringUtils.leftPad(seg.getSegmentName(),dispLeg));
if (showSegmentPace) {
if (seg.getUseCustomPace() ) {
if (! (seg.getUseCustomPace() && Pace.NONE.equals(seg.getCustomPace())))
chars.append(StringUtils.leftPad("Pace",seg.getCustomPace().getFieldWidth()+1));
} else chars.append(StringUtils.leftPad("Pace",pace.getFieldWidth()+1));
} // pace.getFieldWidth()+1
});
report += chars.toString();
}
if (penaltiesOrBonuses) report += StringUtils.leftPad("Adj", dispFormatLength);
// Chip time
report += StringUtils.leftPad("Finish", dispFormatLength);
// gun time
if (showGun) report += StringUtils.leftPad("Gun", dispFormatLength);
// pace
if (showPace) report += StringUtils.leftPad("Pace",pace.getFieldWidth()+1);
report += System.lineSeparator();
return report;
}
/**
* <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) {
StringBuffer buffer = new StringBuffer();
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();
}
public String getNumberString() {
return StringUtils.leftPad(String.valueOf(getNumber()), 3, "0");
}
public static String toHex(int i){
return StringUtils.leftPad(Integer.toHexString(i), 8, '0');
}
@Override
public String generateProductCode() {
Long count = countProductNum() + 1;
return StringUtils.leftPad(count.toString(), 6, "0");
}
/**
* <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(final Token[] tokens, final int years, final int months, final int days, final int hours, final int minutes, final int seconds,
int milliseconds, final boolean padWithZeros) {
final StringBuilder buffer = new StringBuilder();
boolean lastOutputSeconds = false;
final int sz = tokens.length;
for (int i = 0; i < sz; i++) {
final Token token = tokens[i];
final Object value = token.getValue();
final int count = token.getCount();
if (value instanceof StringBuilder) {
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;
final 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();
}