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.core.services.impl.S3FileTransferImplUnitTests.java

/**
 * Given a set of valid S3 {prefix,bucket,key}, try all combinations.
 * Ensure they are accepted as valid and the path components are parsed correctly.
 * Each component is tagged as being valid for strict validation.
 *
 * @throws GenieException in case of error building the URI
 *//*from  w w w  .ja v  a2 s. co  m*/
@Test
public void testValidS3Paths() throws GenieException {
    final Map<String, Boolean> prefixes = ImmutableMap.<String, Boolean>builder().put("s3://", true)
            .put("s3n://", true).build();

    final Map<String, Boolean> buckets = ImmutableMap.<String, Boolean>builder().put(".", false).put("b", false)
            .put("bucket", true).put("Bucket", false).put("bucket1", true).put("1bucket", true)
            .put("bucket-bucket", true).put("bucket.bucket", true).put("bucket+bucket", false)
            .put(".bucket", false).put("bucket.", false).put("buc:ket", false).put("buc!ket", false)
            .put("buc(ket", false).put("buc'ket", false).put(StringUtils.leftPad("", 64, "b"), false).build();

    final Map<String, Boolean> keys = ImmutableMap.<String, Boolean>builder()
            .put("Development/Projects1.xls", true).put("Finance/statement1.pdf", true)
            .put("Private/taxdocument.pdf", true).put("s3-dg.pdf", true)
            .put("weird/but/valid/key!-_*'().pdf", true).put("1+1=3.pdf", false).put("/", false)
            .put("//", false).build();

    int notStrictlyValidExpectedCount = 0;

    // Re-run all combinations with stricter check
    for (final Map.Entry<String, Boolean> prefixEntry : prefixes.entrySet()) {
        for (final Map.Entry<String, Boolean> bucketEntry : buckets.entrySet()) {
            for (final Map.Entry<String, Boolean> keyEntry : keys.entrySet()) {

                final String path = prefixEntry.getKey() + bucketEntry.getKey() + "/" + keyEntry.getKey();
                final boolean expectedStrictlyValid = prefixEntry.getValue() && bucketEntry.getValue()
                        && keyEntry.getValue();

                // Turn off strict validation
                Mockito.when(s3FileTransferProperties.isStrictUrlCheckEnabled()).thenReturn(false);
                Assert.assertFalse(s3FileTransferProperties.isStrictUrlCheckEnabled());
                // Should pass non-strict validation
                Assert.assertTrue("Failed validation: " + path, this.s3FileTransfer.isValid(path));
                // Should correctly split bucket from key
                final AmazonS3URI s3Uri = this.s3FileTransfer.getS3Uri(path);
                Assert.assertEquals(bucketEntry.getKey(), s3Uri.getBucket());
                Assert.assertEquals(keyEntry.getKey(), s3Uri.getKey());

                if (!expectedStrictlyValid) {
                    // Count twice, for isValid() and getS3Uri()
                    notStrictlyValidExpectedCount += 2;
                }

                //Turn on strict validation
                Mockito.when(s3FileTransferProperties.isStrictUrlCheckEnabled()).thenReturn(true);
                Assert.assertTrue(s3FileTransferProperties.isStrictUrlCheckEnabled());

                Assert.assertEquals("Failed strict validation: " + path, expectedStrictlyValid,
                        this.s3FileTransfer.isValid(path));
            }
        }
    }

    Mockito.verify(urlFailingStrictValidationCounter, Mockito.times(notStrictlyValidExpectedCount)).increment();
}

From source file:nc.noumea.mairie.appock.services.impl.CommandeServiceImpl.java

private String findNextNumero() {
    String prefixe = LocalDateTime.now().getYear() + "-";
    Commande commande = commandeRepository.findTopByNumeroStartingWithOrderByNumeroDesc(prefixe);
    int numero = 1;
    if (commande != null) {
        numero = Integer// w ww.j  a v a 2  s  . c o m
                .parseInt(commande.getNumero().substring(prefixe.length(), commande.getNumero().length())) + 1;
    }
    return prefixe + StringUtils.leftPad(String.valueOf(numero), 4, "0");
}

From source file:nc.noumea.mairie.appock.services.impl.DemandeServiceImpl.java

private String findNextNumero(Service service) {
    if (service == null) {
        return null;
    }// w ww  .  jav a  2  s .  c  o m

    Catalogue catalogue = catalogueService.findActif();

    String prefixe = service.getDirection().getPole().getLibelle() + "-"
            + service.getDirection().getLibelleCourt() + "-" + service.getLibelleCourt() + "-"
            + catalogue.getLibelle() + "-";
    Demande demande = demandeRepository.findTopByNumeroStartingWithOrderByNumeroDesc(prefixe);
    int numero = 1;
    if (demande != null) {
        numero = Integer.parseInt(demande.getNumero().substring(prefixe.length(), demande.getNumero().length()))
                + 1;
    }
    return prefixe + StringUtils.leftPad(String.valueOf(numero), 4, "0");
}

From source file:com.jdom.mediadownloader.series.domain.Series.java

private String leftPadZerosToTwoPlaces(int season) {
    return StringUtils.leftPad("" + season, 2, '0');
}

From source file:com.netsteadfast.greenstep.bsc.service.logic.impl.ObjectiveLogicServiceImpl.java

@ServiceMethodAuthority(type = { ServiceMethodType.SELECT })
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
@Override/*  w w w.j  a  v a2s  .  c  o m*/
public String findForMaxObjId(String date) throws ServiceException, Exception {
    if (super.isBlank(date) || !NumberUtils.isNumber(date) || date.length() != 8) {
        throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK));
    }
    String maxVisionId = this.objectiveService.findForMaxObjId(BscConstants.HEAD_FOR_OBJ_ID + date);
    if (StringUtils.isBlank(maxVisionId)) {
        return BscConstants.HEAD_FOR_OBJ_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_OBJ_ID + date + StringUtils.leftPad(String.valueOf(maxSeq), 3, "0");
}

From source file:com.netsteadfast.greenstep.bsc.model.BscMeasureDataFrequency.java

/**
 * ,  bb_measure_data  "", "" //w w  w  .j  a  v  a  2 s .  c  o  m
 * yyyyMMdd 
 * 2013/01/01
 * 20130101
 * 
 * @param yyyyMMdd
 * @return
 * @throws Exception
 */
public static Map<String, String> getWeekOrMonthStartEnd(String frequency, String startDate, String endDate)
        throws Exception {
    if (!BscMeasureDataFrequency.FREQUENCY_WEEK.equals(frequency)
            && !BscMeasureDataFrequency.FREQUENCY_MONTH.equals(frequency)) {
        throw new java.lang.IllegalArgumentException("frequency error.");
    }
    Map<String, String> dateMap = new HashMap<String, String>();
    if (!SimpleUtils.isDate(startDate) || !SimpleUtils.isDate(endDate)) {
        throw new java.lang.IllegalArgumentException("startDate/endDate error.");
    }
    if (BscMeasureDataFrequency.FREQUENCY_WEEK.equals(frequency)) {
        int firstDay = Integer.parseInt(startDate.substring(startDate.length() - 2, startDate.length()));
        int endDay = Integer.parseInt(endDate.substring(endDate.length() - 2, endDate.length()));
        if (firstDay >= 1 && firstDay < 8) {
            firstDay = 1;
        }
        if (firstDay >= 8 && firstDay < 15) {
            firstDay = 8;
        }
        if (firstDay >= 15 && firstDay < 22) {
            firstDay = 15;
        }
        if (firstDay >= 22) {
            firstDay = 22;
        }
        if (endDay >= 1 && endDay < 8) {
            endDay = 7;
        }
        if (endDay >= 8 && endDay < 15) {
            endDay = 14;
        }
        if (endDay >= 15 && endDay < 22) {
            endDay = 21;
        }
        if (endDay >= 22) {
            endDay = SimpleUtils.getMaxDayOfMonth(Integer.parseInt(endDate.substring(0, 4)),
                    Integer.parseInt(endDate.substring(5, 7)));
        }
        String newStartDate = startDate.substring(0, startDate.length() - 2)
                + StringUtils.leftPad(String.valueOf(firstDay), 2, "0");
        String newEndDate = endDate.substring(0, endDate.length() - 2)
                + StringUtils.leftPad(String.valueOf(endDay), 2, "0");
        dateMap.put("startDate", newStartDate);
        dateMap.put("endDate", newEndDate);
    }
    if (BscMeasureDataFrequency.FREQUENCY_MONTH.equals(frequency)) {
        int endDay = SimpleUtils.getMaxDayOfMonth(Integer.parseInt(endDate.substring(0, 4)),
                Integer.parseInt(endDate.substring(5, 7)));
        String newStartDate = startDate.substring(0, startDate.length() - 2) + "01";
        String newEndDate = endDate.substring(0, endDate.length() - 2)
                + StringUtils.leftPad(String.valueOf(endDay), 2, "0");
        dateMap.put("startDate", newStartDate);
        dateMap.put("endDate", newEndDate);
    }
    return dateMap;
}

From source file:com.kurniakue.telebot.admin.RecapitulationHandler.java

private boolean showTransactions(List<? extends Record> list, ShowFlag showFlag) {
    Replier replier = getReplier();//from  ww w . j  a  v  a2 s.c om

    long totalPay = 0;
    int count = 0;
    for (Record record : list) {
        long amount = record.getLong(Transaction.V.Rekap);
        if (amount == 0) {
            continue;
        } else if (amount > 0 && showFlag == ShowFlag.Negative) {
            continue;
        } else if (amount < 0 && showFlag == ShowFlag.Positive) {
            continue;
        }

        count += 1;
        String strCount = StringUtils.leftPad(count + ". ", 5, "0");
        final String customer = record.getString(Transaction.F._id);
        replier.addLine(strCount).add(customer).add(": ");
        totalPay += amount;
        replier.add(Tool.formatMoney(amount));
    }
    replier.addLine("");
    replier.addLine("Total : ").add(Tool.formatMoney(totalPay));

    replier.send();
    return true;
}

From source file:com.netsteadfast.greenstep.bsc.service.logic.impl.PerspectiveLogicServiceImpl.java

@ServiceMethodAuthority(type = { ServiceMethodType.SELECT })
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
@Override/*  www.  j  av  a 2  s  .c o  m*/
public String findForMaxPerId(String date) throws ServiceException, Exception {
    if (super.isBlank(date) || !NumberUtils.isNumber(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");
}

From source file:com.nkapps.billing.dao.PgDaoImpl.java

@Override
public void munisSave(MunisPojo munisPojo) throws Exception {
    Session session = getSession();//from ww w . j a  va  2 s .c o  m
    Transaction transaction = session.beginTransaction();

    Munis munis = (Munis) session.get(Munis.class, new BigInteger(munisPojo.getPaymentId()));

    LocalDateTime dateTime = LocalDateTime.now();
    if (munis == null) {
        munis = new Munis();
        munis.setId(new BigInteger(munisPojo.getPaymentId()));
        munis.setConfirmCode(munisPojo.getConfirmCode());
        munis.setConfirmMessage(munisPojo.getConfirmMessage());
        munis.setSysinfoData(munisPojo.getSysinfoData());
        munis.setSysinfoTime(munisPojo.getSysinfoTime());
        munis.setSysinfoBid(munisPojo.getSysinfoBid());
        munis.setSysinfoTid(munisPojo.getSysinfoTid());
        munis.setSysinfoSid(munisPojo.getSysinfoSid());
        munis.setSysinfoHash(munisPojo.getSysinfoHash());
        munis.setPayerBranch(munisPojo.getPayerBranch());
        munis.setPayerAccount(munisPojo.getPayerAccount());
        munis.setPayerName(munisPojo.getPayerName());
        munis.setPayerInn(munisPojo.getPayerInn());
        munis.setPayeeBranch(munisPojo.getPayeeBranch());
        munis.setPayeeAccount(munisPojo.getPayeeAccount());
        munis.setPayeeName(munisPojo.getPayeeName());
        munis.setPayeeInn(munisPojo.getPayeeInn());
        munis.setPurposeCode(munisPojo.getPurposeCode());
        munis.setPurposeText(munisPojo.getPurposeText());
        munis.setAmountCurrency(munisPojo.getAmountCurrency());
        munis.setAmountValue(new BigDecimal(munisPojo.getAmountValue()).divide(new BigDecimal("100"))); // tiyin convert to so'm
        munis.setDocumentNum(StringUtils.leftPad(munisPojo.getDocumentNum(), 10, "0"));
        munis.setDocumentData(new SimpleDateFormat("dd.MM.yyyy").parse(munisPojo.getDocumentData()));
        munis.setSettlementSupplier(munisPojo.getSettlementSupplier());
        munis.setSettlementCode(munisPojo.getSettlementCode());
        munis.setSubjectinfoGni(munisPojo.getSubjectinfoGni());
        munis.setSubjectinfoInn(munisPojo.getSubjectinfoInn());
        munis.setSubjectinfoCodeObj(munisPojo.getSubjectinfoCodeObj());
        munis.setInfoserviceInn(munisPojo.getInfoserviceInn());
        munis.setInfoserviceName(munisPojo.getInfoserviceName());
        munis.setInfoserviceCodeObj(munisPojo.getInfoserviceCodeObj());
        munis.setInfoserviceAddressObj(munisPojo.getInfoserviceAddressObj());
        munis.setDateCreated(dateTime);
        munis.setDateUpdated(dateTime);

        session.save(munis);

        Payment payment = paymentDao.findPayment(munis.getSubjectinfoInn(), munis.getDocumentNum(),
                munis.getDocumentData(), munis.getAmountValue(), munis.getPayerInn(), (short) 1); // bank statement payment to search
        if (payment == null) {
            payment = new Payment();
            payment.setTin(munis.getSubjectinfoInn());
            payment.setPaymentNum(munis.getDocumentNum());
            payment.setPaymentDate(munis.getDocumentData());
            payment.setPaymentSum(munis.getAmountValue()); //
            payment.setTinDebtor(munis.getPayerInn());
            payment.setSourceCode((short) 2); // for munis
            payment.setState((short) 1); // 
            payment.setClaim((short) 0); //
            payment.setDateCreated(dateTime);
            payment.setDateUpdated(dateTime);

            session.save(payment);

            MunisPayment mp = new MunisPayment();
            MunisPaymentId mpId = new MunisPaymentId();
            mpId.setMunis(munis);
            mpId.setPayment(payment);
            mp.setId(mpId);

            session.save(mp);

        } else {
            BankStatementMunis bsm = new BankStatementMunis();
            BankStatementMunisId bsmId = new BankStatementMunisId();
            bsmId.setBankStatement(payment.getBankStatementPayment().getId().getBankStatement());
            bsmId.setMunis(munis);
            bsm.setId(bsmId);

            session.save(bsm);
        }

    } else {
        munis.setDateUpdated(dateTime);
        session.update(munis);
    }

    transaction.commit();
    session.close();
}

From source file:com.serotonin.bacnet4j.util.sero.StreamUtils.java

public static String dumpHex(byte[] b, int pos, int len) {
    StringBuilder sb = new StringBuilder();
    for (int i = pos; i < len; i++)
        sb.append(StringUtils.leftPad(Integer.toHexString(b[i] & 0xff), 2, '0'));
    return sb.toString();
}