Java Code Examples for org.apache.commons.lang.StringUtils#leftPad()

The following examples show how to use org.apache.commons.lang.StringUtils#leftPad() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Base62.java    From youkefu with Apache License 2.0 7 votes vote down vote up
public static String encode(String str){ 
	    String md5Hex = DigestUtils.md5Hex(str);
	    // 6 digit binary can indicate 62 letter & number from 0-9a-zA-Z
	    int binaryLength = 6 * 6;
	    long binaryLengthFixer = Long.valueOf(StringUtils.repeat("1", binaryLength), BINARY);
	    for (int i = 0; i < 4;) {
	      String subString = StringUtils.substring(md5Hex, i * 8, (i + 1) * 8);
	      subString = Long.toBinaryString(Long.valueOf(subString, 16) & binaryLengthFixer);
	      subString = StringUtils.leftPad(subString, binaryLength, "0");
	      StringBuilder sbBuilder = new StringBuilder();
	      for (int j = 0; j < 6; j++) {
	        String subString2 = StringUtils.substring(subString, j * 6, (j + 1) * 6);
	        int charIndex = Integer.valueOf(subString2, BINARY) & NUMBER_61;
	        sbBuilder.append(DIGITS[charIndex]);
	      }
	      String shortUrl = sbBuilder.toString();
	      if(shortUrl!=null){
	    	  return shortUrl;
	      }
	    }
	    // if all 4 possibilities are already exists
	    return null;
}
 
Example 2
Source File: CRCUtil.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Calculate the CRC16-CCITT checksum on the input string and return the
 * input string with the checksum appended.
 * 
 * @param input
 *            String representing hex numbers.
 * @return input string + CRC.
 */
public static String appendCRC(String input) {

    if (input == null) {
        return null;
    }

    int check = CRC_INIT;

    for (byte b : DatatypeConverter.parseHexBinary(input)) {
        for (int i = 0; i < 8; i++) {
            if (((b >> (7 - i) & 1) == 1) ^ ((check >> 15 & 1) == 1)) {
                check = check << 1;
                check = check ^ POLYNOMIAL;
            } else {
                check = check << 1;
            }
        }
    }
    check = check & CRC_INIT;
    String checksum = StringUtils.leftPad(Integer.toHexString(check), 4, "0");
    return (input + checksum).toUpperCase();
}
 
Example 3
Source File: TableListing.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Return the ith row of the column as a set of wrapped strings, each at
 * most wrapWidth in length.
 */
String[] getRow(int idx) {
  String raw = rows.get(idx);
  // Line-wrap if it's too long
  String[] lines = new String[] {raw};
  if (wrap) {
    lines = WordUtils.wrap(lines[0], wrapWidth, "\n", true).split("\n");
  }
  for (int i=0; i<lines.length; i++) {
    if (justification == Justification.LEFT) {
      lines[i] = StringUtils.rightPad(lines[i], maxWidth);
    } else if (justification == Justification.RIGHT) {
      lines[i] = StringUtils.leftPad(lines[i], maxWidth);
    }
  }
  return lines;
}
 
Example 4
Source File: KostFormatter.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * If not given, then ??? will be returned.
 * @param number
 * @return
 * @see StringUtils#leftPad(String, int, char)
 */
public static String format3Digits(final Integer number)
{
  if (number == null) {
    return "???";
  }
  return StringUtils.leftPad(number.toString(), 3, '0');
}
 
Example 5
Source File: ZigBeeGateway.java    From zigbee4java with Apache License 2.0 5 votes vote down vote up
/**
 * Gets device summary.
 * @param device the device
 * @return the summary
 */
private String getDeviceSummary(final ZigBeeDevice device) {
    return StringUtils.leftPad(Integer.toString(device.getNetworkAddress()), 10) + "/"
            + StringUtils.rightPad(Integer.toString(device.getEndpoint()), 3)
            + " " + StringUtils.rightPad(device.getLabel()!= null ? device.getLabel() : "<label>", 20)
            + " " + ZigBeeApiConstants.getDeviceName(device.getProfileId(),
            device.getDeviceType(), device.getDeviceId());
}
 
Example 6
Source File: KostFormatter.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * If not given, then ?? will be returned.
 * @param number
 * @return
 * @see StringUtils#leftPad(String, int, char)
 */
public static String format2Digits(final Integer number)
{
  if (number == null) {
    return "??";
  }
  return StringUtils.leftPad(number.toString(), 2, '0');
}
 
Example 7
Source File: HelpPrinter.java    From FortifyBugTrackerUtility with MIT License 5 votes vote down vote up
public HelpPrinter append(int indent, String str) {
	int leadingSpaces = str.indexOf(str.trim());
	indent += leadingSpaces;
	str = str.substring(leadingSpaces);
	String padding = StringUtils.leftPad("",indent);
	sb.append(padding+WordUtils.wrap(str, width-indent, "\n"+padding, false)).append("\n");
	return this;
}
 
Example 8
Source File: IdentifierType.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public String formatIdentifierValue(String value) {
   if (value.length() > this.length) {
      LOG.debug("Truncating identifiervalue [" + value + "] to length " + this.length);
      return value.substring(0, this.length);
   } else {
      return StringUtils.leftPad(value, this.length, "0");
   }
}
 
Example 9
Source File: StringUtil.java    From heisenberg with Apache License 2.0 5 votes vote down vote up
/**
 * 将数字格式化到固定长度
 * 
 * @param input
 * @param fixLength
 * @return
 */
public static String formatNumberToFixedLength(String input, int fixLength) {
    if (input.length() <= fixLength) {
        // 未到指定长度,左补0
        return StringUtils.leftPad(input, fixLength, '0');
    } else {
        // 超过长度,砍掉左边超长部分
        return input.substring(input.length() - fixLength);
    }
}
 
Example 10
Source File: Arja_0025_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * <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 formetted 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();
}
 
Example 11
Source File: BootStrapUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
private static String getAlias(int i, X509Certificate cert) {
   return StringUtils.leftPad(Integer.toString(i), 3, "0") + " " + cert.getSubjectX500Principal().getName("RFC2253");
}
 
Example 12
Source File: ZookeeperPathUtils.java    From canal-1.1.3 with Apache License 2.0 4 votes vote down vote up
/**
 * 将batchId转化为zookeeper中的node名称
 */
public static String getBatchMarkNode(Long batchId) {
    return StringUtils.leftPad(String.valueOf(batchId.intValue()), 10, '0');
}
 
Example 13
Source File: QueueMessage.java    From unitime with Apache License 2.0 4 votes vote down vote up
protected String formatMessagePlain() {
	Formats.Format<Date> df = Formats.getDateFormat(Formats.Pattern.DATE_TIME_STAMP);
	return df.format(getDate()) + " " + StringUtils.leftPad(getLevel().name(), 5) + " " + getMessage();
}
 
Example 14
Source File: Arja_00101_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * <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 formetted 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();
}
 
Example 15
Source File: PathUtils.java    From oodt with Apache License 2.0 4 votes vote down vote up
public static String doDynamicDateReplacement(String string,
        Metadata metadata) throws CasMetadataException, CommonsException {
    Pattern datePattern = Pattern
            .compile("\\[\\s*DATE\\s*(?:[+-]{1}[^\\.]{1,}?){0,1}\\.\\s*(?:(?:DAY)|(?:MONTH)|(?:YEAR)|(?:UTC)|(?:TAI)){1}\\s*\\]");
    Matcher dateMatcher = datePattern.matcher(string);
    while (dateMatcher.find()) {
        String dateString = string.substring(dateMatcher.start(),
                dateMatcher.end());
        GregorianCalendar gc = new GregorianCalendar();

        // roll the date if roll days was specfied
        int plusMinusIndex;
        if ((plusMinusIndex = dateString.indexOf('-')) != -1
                || (plusMinusIndex = dateString.indexOf('+')) != -1) {
            int dotIndex;
            if ((dotIndex = dateString.indexOf('.', plusMinusIndex)) != -1) {
                int rollDays = Integer.parseInt(PathUtils
                        .replaceEnvVariables(
                                dateString.substring(plusMinusIndex,
                                        dotIndex), metadata).replaceAll(
                                "[\\+\\s]", ""));
                gc.add(GregorianCalendar.DAY_OF_YEAR, rollDays);
            } else {
                throw new CasMetadataException(
                    "Malformed dynamic date replacement specified (no dot separator) - '"
                    + dateString + "'");
            }
        }

        // determine type and make the appropriate replacement
        String[] splitDate = dateString.split("\\.");
        if (splitDate.length < 2) {
            throw new CasMetadataException("No date type specified - '" + dateString
                                           + "'");
        }
        String dateType = splitDate[1].replaceAll("[\\[\\]\\s]", "");
        String replacement;
        if (dateType.equals("DAY")) {
            replacement = StringUtils.leftPad(gc
                    .get(GregorianCalendar.DAY_OF_MONTH)
                    + "", 2, "0");
        } else if (dateType.equals("MONTH")) {
            replacement = StringUtils.leftPad((gc
                    .get(GregorianCalendar.MONTH) + 1)
                    + "", 2, "0");
        } else if (dateType.equals("YEAR")) {
            replacement = gc.get(GregorianCalendar.YEAR) + "";
        } else if (dateType.equals("UTC")) {
            replacement = DateUtils.toString(DateUtils.toUtc(gc));
        } else if (dateType.equals("TAI")) {
            replacement = DateUtils.toString(DateUtils.toTai(gc));
        } else {
            throw new CasMetadataException("Invalid date type specified '"
                    + dateString + "'");
        }

        string = StringUtils.replace(string, dateString, replacement);
        dateMatcher = datePattern.matcher(string);
    }
    return string;
}
 
Example 16
Source File: Lang_63_DurationFormatUtils_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * <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 formetted 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();
}
 
Example 17
Source File: Arja_00137_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * <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 formetted 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();
}
 
Example 18
Source File: V3Parser.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void parseConfig(List<String> configParts) throws BindingConfigParseException {
    String id = "";
    Boolean group = false;
    Integer channelID = 0;

    // Extract parameter values from config parts
    for (int i = 0; i < configParts.size(); i++) {
        String paramName = configParts.get(i).split("=")[0].toLowerCase();
        String paramValue = configParts.get(i).split("=")[1];

        switch (paramName) {
            case "id":
                id = paramValue;
                break;
            case "group":
                if (paramValue.equals("1") || paramValue.toLowerCase().equals("true")) {
                    group = true;
                }
                break;
            case "channel":
                try {
                    channelID = Integer.parseInt(paramValue);
                } catch (NumberFormatException e) {
                    throw new BindingConfigParseException("Channel ID (" + paramValue + ") is not a number.");
                }
        }
    }

    // Check parameter values
    if (id.length() != 26) {
        throw new BindingConfigParseException("The ID must contain exactly 26 digits!");
    }

    for (int i = 0; i < id.length(); i++) {
        if (id.charAt(i) != '0' && id.charAt(i) != '1') {
            throw new BindingConfigParseException("The ID must contains only the digits 1 and 0!");
        }
    }

    if (channelID < 0 || channelID > 15) {
        throw new BindingConfigParseException("The channel ID must be in a range from 0 to 15!");
    }

    // Build command strings
    String channelIDCode = StringUtils.leftPad(Integer.toBinaryString(channelID), 4, "0");

    commandON = id + getGroupCode(group) + "1" + channelIDCode;
    commandOFF = id + getGroupCode(group) + "0" + channelIDCode;

    logger.trace("commandON = {}", commandON);
    logger.trace("commandOFF = {}", commandOFF);
}
 
Example 19
Source File: FixDataSourceImpl.java    From tddl with Apache License 2.0 4 votes vote down vote up
public String getTableName(long userId, String tablePrefix) {
	long tableIndex = userId % tableCount;
	String tableFullName = tablePrefix + "_" + StringUtils.leftPad(tableIndex + "", tableLength, "0");
	return tableFullName;
}
 
Example 20
Source File: RdsLocalBinlogEventParser.java    From canal with Apache License 2.0 4 votes vote down vote up
@Override
public void onFinish(String fileName) {
    try {
        binlogDownloadQueue.downOne();
        File needDeleteFile = new File(directory + File.separator + fileName);
        if (needDeleteFile.exists()) {
            needDeleteFile.delete();
        }
        // 处理下logManager位点问题
        LogPosition logPosition = logPositionManager.getLatestIndexBy(destination);
        Long timestamp = 0L;
        if (logPosition != null && logPosition.getPostion() != null) {
            timestamp = logPosition.getPostion().getTimestamp();
            EntryPosition position = logPosition.getPostion();
            LogPosition newLogPosition = new LogPosition();
            String journalName = position.getJournalName();
            int sepIdx = journalName.indexOf(".");
            String fileIndex = journalName.substring(sepIdx + 1);
            int index = NumberUtils.toInt(fileIndex) + 1;
            String newJournalName = journalName.substring(0, sepIdx) + "."
                                    + StringUtils.leftPad(String.valueOf(index), fileIndex.length(), "0");
            newLogPosition.setPostion(new EntryPosition(newJournalName,
                4L,
                position.getTimestamp(),
                position.getServerId()));
            newLogPosition.setIdentity(logPosition.getIdentity());
            logPositionManager.persistLogPosition(destination, newLogPosition);
        }

        if (binlogDownloadQueue.isLastFile(fileName)) {
            logger.warn("last file : " + fileName + " , timestamp : " + timestamp
                        + " , all file parse complete, switch to mysql parser!");
            finishListener.onFinish();
            return;
        } else {
            logger.warn("parse local binlog file : " + fileName + " , timestamp : " + timestamp
                        + " , try the next binlog !");
        }
        binlogDownloadQueue.prepare();
    } catch (Exception e) {
        logger.error("prepare download binlog file failed!", e);
        throw new RuntimeException(e);
    }
}