Example usage for org.apache.commons.lang3 StringUtils leftPad

List of usage examples for org.apache.commons.lang3 StringUtils leftPad

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils leftPad.

Prototype

public static String leftPad(final String str, final int size, String padStr) 

Source Link

Document

Left pad a String with a specified String.

Pad to a size of size .

 StringUtils.leftPad(null, *, *)      = null StringUtils.leftPad("", 3, "z")      = "zzz" StringUtils.leftPad("bat", 3, "yz")  = "bat" StringUtils.leftPad("bat", 5, "yz")  = "yzbat" StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat" StringUtils.leftPad("bat", 1, "yz")  = "bat" StringUtils.leftPad("bat", -1, "yz") = "bat" StringUtils.leftPad("bat", 5, null)  = "  bat" StringUtils.leftPad("bat", 5, "")    = "  bat" 

Usage

From source file:com.netflix.genie.web.data.entities.CommandEntityTest.java

/**
 * Make sure validation works on with failure from command.
 *//*ww w .j  a v  a  2 s . c  o m*/
@Test(expected = ConstraintViolationException.class)
public void testValidateExecutableArgumentTooLong() {
    this.c.setExecutable(Lists.newArrayList(StringUtils.leftPad("", 1025, 'e')));
    this.validate(this.c);
}

From source file:com.streamsets.pipeline.kafka.impl.KafkaProducer09IT.java

@Test
public void testKafkaProducer09WriteFailsRecordTooLarge() throws IOException, StageException {

    HashMap<String, Object> kafkaProducerConfigs = new HashMap<>();
    kafkaProducerConfigs.put("retries", 0);
    kafkaProducerConfigs.put("batch.size", 100);
    kafkaProducerConfigs.put("linger.ms", 0);
    kafkaProducerConfigs.put(KafkaConstants.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    kafkaProducerConfigs.put(KafkaConstants.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class);
    // Set the message size to 510 as "message.max.bytes" is set to 500
    final String message = StringUtils.leftPad("a", 510, "b");
    SdcKafkaProducer sdcKafkaProducer = createSdcKafkaProducer(port, kafkaProducerConfigs);
    sdcKafkaProducer.init();//from ww  w.j  av  a 2  s .co m
    String topic = getNextTopic();
    sdcKafkaProducer.enqueueMessage(topic, message.getBytes(), "0");
    try {
        sdcKafkaProducer.write(null);
        fail("Expected exception but didn't get any");
    } catch (StageException se) {
        assertEquals(KafkaErrors.KAFKA_69, se.getErrorCode());
    } catch (Exception e) {
        fail("Expected Stage Exception but got " + e);
    }
}

From source file:io.stallion.dataAccess.db.SqlGenerationAction.java

public void writeMigrationToFile(Integer migrationNumber, GenerateResult result) {
    String prefix = StringUtils.leftPad(migrationNumber.toString(), 5, '0');

    File dir = new File(System.getProperty("user.dir") + "/src/main/resources/sql");
    File migrationsFile = new File(System.getProperty("user.dir") + "/src/main/resources/sql/migrations.txt");
    ;//from  w  w  w .  j av a  2  s. c  o  m
    if (dir.exists() && migrationsFile.exists()) {
        String name = prefix + "-" + result.getChangePrefix() + ".mysql.js";
        File newMigrationFile = new File(dir.getAbsolutePath() + "/" + name);

        FileUtils.writeAllText(result.getSqlJs(), newMigrationFile, Charset.forName("UTF-8"));

        // Append the new migration to the text file with a list of migrations
        String s = FileUtils.readAllText(migrationsFile);
        if (!s.endsWith("\n")) {
            s += "\n";
        }
        s += prefix + "-" + result.getChangePrefix();
        FileUtils.writeAllText(s, migrationsFile, Charset.forName("UTF-8"));

    } else {
        String file = Settings.instance().getTargetFolder() + "/sql/" + prefix + "-" + result.getChangePrefix()
                + ".mysql.js";
        FileUtils.writeAllText(result.getSqlJs(), new File(file), Charset.forName("UTF-8"));
    }

}

From source file:com.netsteadfast.greenstep.util.SimpleUtils.java

public static final String getStrYMD(final int type) {
    Calendar calendar = Calendar.getInstance();
    if (type == SimpleUtils.IS_YEAR) {
        return calendar.get(Calendar.YEAR) + "";
    }//ww w.  j  a v a  2s . c  o m
    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) + "";
}

From source file:co.rsk.peg.SamplePrecompiledContractTest.java

@Test
public void samplePrecompiledContractMethod1LargeData() {
    DataWord addr = new DataWord(PrecompiledContracts.SAMPLE_ADDR);
    SamplePrecompiledContract contract = (SamplePrecompiledContract) PrecompiledContracts
            .getContractForAddress(addr);

    String funcJson = "{\n" + "   'constant':false, \n" + "   'inputs':[{'name':'param0','type':'int'}, \n"
            + "               {'name':'param1','type':'string'}], \n" + "    'name':'Method1', \n"
            + "   'outputs':[{'name':'output0','type':'int'}], \n" + "    'type':'function' \n" + "}\n";
    funcJson = funcJson.replaceAll("'", "\"");

    CallTransaction.Function function = CallTransaction.Function.fromJsonInterface(funcJson);

    byte[] data = function.encode(111, StringUtils.leftPad("foobar", 1000000, '*'));

    contract.init(null, null, new RepositoryImpl(), null, null, new ArrayList<LogInfo>());
    byte[] result = contract.execute(data);

    Object[] results = function.decodeResult(result);
    assertEquals(new BigInteger("1"), results[0]);
}

From source file:com.netsteadfast.greenstep.action.SystemMessageNoticeManagementAction.java

private void initData() throws ServiceException, Exception {
    this.msgDataMap = this.sysMsgNoticeConfigService.findForDataMap(true);
    this.accountMap = this.accountService.findForAllMap(true);
    for (int hour = 0; hour < 24; hour++) {
        String hourStr = StringUtils.leftPad(String.valueOf(hour), 2, "0");
        hourMap.put(hourStr, hourStr);/*from   w w w . ja v a  2  s. c  om*/
    }
    for (int mins = 0; mins < 60; mins++) {
        String minsStr = StringUtils.leftPad(String.valueOf(mins), 2, "0");
        minutesMap.put(minsStr, minsStr);
    }
}

From source file:com.stratio.cassandra.index.schema.ColumnMapperBigDecimal.java

/** {@inheritDoc} */
@Override/*from  w w w .  j  a v a 2  s.c  o m*/
public String indexValue(String name, Object value) {

    // Check not null
    if (value == null) {
        return null;
    }

    // Parse big decimal
    String svalue = value.toString();
    BigDecimal bd;
    try {
        bd = new BigDecimal(value.toString());
    } catch (NumberFormatException e) {
        String message = String.format("Field %s requires a base 10 decimal, but found \"%s\"", name, svalue);
        throw new IllegalArgumentException(message);
    }

    // Split integer and decimal part
    bd = bd.stripTrailingZeros();
    String[] parts = bd.toPlainString().split("\\.");
    String integerPart = parts[0];
    String decimalPart = parts.length == 1 ? "0" : parts[1];

    if (integerPart.replaceFirst("-", "").length() > integerDigits) {
        throw new IllegalArgumentException("Too much digits in integer part");
    }
    if (decimalPart.length() > decimalDigits) {
        throw new IllegalArgumentException("Too much digits in decimal part");
    }

    BigDecimal complemented = bd.add(complement);
    String bds[] = complemented.toString().split("\\.");
    integerPart = bds[0];
    decimalPart = bds.length == 2 ? bds[1] : "0";
    integerPart = StringUtils.leftPad(integerPart, integerDigits + 1, '0');

    return integerPart + "." + decimalPart;
}

From source file:com.netsteadfast.greenstep.service.impl.SysCalendarNoteServiceImpl.java

/**
 *  CALENDAR_ID/*from  ww  w.ja  v a  2 s  .c  o m*/
 * ?: +001 , 999 ,  20141915001
 * 
 * @param account
 * @param date
 * @return
 * @throws ServiceException
 * @throws Exception
 */
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
@Override
public String findForMaxCalendarId(String account, String date) throws ServiceException, Exception {
    if (StringUtils.isBlank(account) || StringUtils.isBlank(date)) {
        throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK));
    }
    String calendarId = this.sysCalendarNoteDAO.findForMaxCalendarId(account, date);
    if (!StringUtils.isBlank(calendarId)) {
        int num = Integer.parseInt(calendarId.substring(8, 11)) + 1;
        if (num > 999) { // ?999note
            throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_ERRORS));
        }
        return date + StringUtils.leftPad(String.valueOf(num), 3, "0");
    }
    //  calendar_id      
    return date + "001";
}

From source file:com.fanniemae.ezpie.common.ColorUtilities.java

protected String toHexPair(int i) {
    if (i >= 256) {
        i = 255;/* w  w  w . j a va 2s .c o m*/
    }
    return StringUtils.leftPad(Integer.toHexString(i), 2, "0");
}

From source file:com.adobe.acs.commons.httpcache.store.jcr.impl.writer.BucketNodeFactoryTest.java

private BucketNodeFactory buildNodeFactoryWithMocks(MockSettings settings)
        throws RepositoryException, BucketNodeFactoryException {
    final CacheKey cacheKey = mockCacheKey(settings);

    when(session.nodeExists(MockSettings.VALID_ROOT_PATH)).thenReturn(true);
    when(session.getNode(MockSettings.VALID_ROOT_PATH)).thenReturn(cacheRootNode);

    final BucketNodeFactory bucketNodeFactory = new BucketNodeFactory(session, settings.cacheRootPath, cacheKey,
            settings.bucketNodeDepth);//from   w w w .j  a  v a2 s  .  com

    final int hashCode = cacheKey.hashCode();

    if (hashCode > 0) {
        final String hashString = StringUtils.leftPad(String.valueOf(hashCode), (int) HASHCODE_LENGTH, "0");
        final int increment = (int) Math.ceil(HASHCODE_LENGTH / settings.bucketNodeDepth);
        final String[] pathArray = new String[settings.bucketNodeDepth];

        for (int position = 0, i = 0; i < settings.bucketNodeDepth; position += increment, i++) {
            int endIndex = (position + increment > hashString.length()) ? hashString.length()
                    : position + increment;
            String nodeName = StringUtils.leftPad(hashString.substring(position, endIndex), 5, "0");
            pathArray[i] = nodeName;
        }

        Node targetNode = cacheRootNode;

        for (String nodeName : pathArray) {
            Node childNode = mock(Node.class);
            when(childNode.getName()).thenReturn(nodeName);
            when(targetNode.hasNode(nodeName)).thenReturn(true);
            when(targetNode.getNode(nodeName)).thenReturn(childNode);
            when(childNode.getParent()).thenReturn(targetNode);

            targetNode = childNode;
        }
    }

    return bucketNodeFactory;
}