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

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

Introduction

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

Prototype

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

Source Link

Document

Left pad a String with a specified String.

Usage

From source file:jenkins.branch.NameMangler.java

public static String apply(String name) {
    if (name.length() <= MAX_SAFE_LENGTH) {
        boolean unsafe = false;
        boolean first = true;
        for (char c : name.toCharArray()) {
            if (first) {
                if (c == '-') {
                    // no leading dash
                    unsafe = true;//from w  w w .j  av  a 2  s  .c om
                    break;
                }
                first = false;
            }
            if (!isSafe(c)) {
                unsafe = true;
                break;
            }
        }
        // See https://msdn.microsoft.com/en-us/library/aa365247 we need to consistently reserve names across all OS
        if (!unsafe) {
            // we know it is only US-ASCII if we got to here
            switch (name.toLowerCase(Locale.ENGLISH)) {
            case ".":
            case "..":
            case "con":
            case "prn":
            case "aux":
            case "nul":
            case "com1":
            case "com2":
            case "com3":
            case "com4":
            case "com5":
            case "com6":
            case "com7":
            case "com8":
            case "com9":
            case "lpt1":
            case "lpt2":
            case "lpt3":
            case "lpt4":
            case "lpt5":
            case "lpt6":
            case "lpt7":
            case "lpt8":
            case "lpt9":
                unsafe = true;
                break;
            default:
                if (name.endsWith(".")) {
                    unsafe = true;
                }
                break;
            }
        }
        if (!unsafe) {
            return name;
        }
    }
    StringBuilder buf = new StringBuilder(name.length() + 16);
    for (char c : name.toCharArray()) {
        if (isSafe(c)) {
            buf.append(c);
        } else if (c == '/' || c == '\\' || c == ' ' || c == '.' || c == '_') {
            if (buf.length() == 0) {
                buf.append("0-");
            } else {
                buf.append('-');
            }
        } else if (c <= 0xff) {
            if (buf.length() == 0) {
                buf.append("0_");
            } else {
                buf.append('_');
            }
            buf.append(StringUtils.leftPad(Integer.toHexString(c & 0xff), 2, '0'));
        } else {
            if (buf.length() == 0) {
                buf.append("0_");
            } else {
                buf.append('_');
            }
            buf.append(StringUtils.leftPad(Integer.toHexString(((c & 0xffff) >> 8) & 0xff), 2, '0'));
            buf.append('_');
            buf.append(StringUtils.leftPad(Integer.toHexString(c & 0xff), 2, '0'));
        }
    }
    // use the digest of the original name
    String digest;
    try {
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        byte[] bytes = sha.digest(name.getBytes(StandardCharsets.UTF_8));
        int bits = 0;
        int data = 0;
        StringBuffer dd = new StringBuffer(32);
        for (byte b : bytes) {
            while (bits >= 5) {
                dd.append(toDigit(data & 0x1f));
                bits -= 5;
                data = data >> 5;
            }
            data = data | ((b & 0xff) << bits);
            bits += 8;
        }
        digest = dd.toString();
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("SHA-1 not installed", e); // impossible
    }
    if (buf.length() <= MAX_SAFE_LENGTH - MIN_HASH_LENGTH - 1) {
        // we have room to add the min hash
        buf.append('.');
        buf.append(StringUtils.right(digest, MIN_HASH_LENGTH));
        return buf.toString();
    }
    // buf now holds the mangled string, we will now try and rip the middle out to put in some of the digest
    int overage = buf.length() - MAX_SAFE_LENGTH;
    String hash;
    if (overage <= MIN_HASH_LENGTH) {
        hash = "." + StringUtils.right(digest, MIN_HASH_LENGTH) + ".";
    } else if (overage > MAX_HASH_LENGTH) {
        hash = "." + StringUtils.right(digest, MAX_HASH_LENGTH) + ".";
    } else {
        hash = "." + StringUtils.right(digest, overage) + ".";
    }
    int start = (MAX_SAFE_LENGTH - hash.length()) / 2;
    buf.delete(start, start + hash.length() + overage);
    buf.insert(start, hash);
    return buf.toString();
}

From source file:eu.alpinweiss.filegen.util.generator.impl.SequenceGenerator.java

@Override
public void generate(final ParameterVault parameterVault, ThreadLocalRandom randomGenerator,
        ValueVault valueVault) {//from  w w  w  .  j a  v  a2s.  c om
    valueVault.storeValue(new StringDataWrapper() {
        @Override
        public String getStringValue() {
            int value = (startNum + (parameterVault.rowCount() * parameterVault.dataPartNumber())
                    + parameterVault.iterationNumber()) - parameterVault.overrun();
            if (value > maxValue && shouldFail) {
                throw new RuntimeException(
                        "Sequence Generator Exception. Value: " + value + " meets limit: " + maxValue);
            } else if (value > maxValue && !shouldFail) {
                parameterVault.setOverrun(value - 1);
                value = value - parameterVault.overrun();
            }
            return sequencePattern[0] + StringUtils.leftPad(Integer.toString(value), digitCount, '0')
                    + sequencePattern[2];
        }
    });
}

From source file:com.enioka.jqm.api.ServiceSimple.java

@GET
@Path("stderr")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public InputStream getLogErr(@QueryParam("id") int id) {
    res.setHeader("Content-Disposition", "attachment; filename=" + id + ".stderr.txt");
    return getFile(FilenameUtils.concat("./logs", StringUtils.leftPad("" + id, 10, "0") + ".stderr.log"));
}

From source file:id.co.teleanjar.ppobws.isoserver.EchoTest.java

private ISOMsg createInquiryRequest(String username) throws ISOException {
    ISOPackager packager = new TelePackager();

    String bit11 = formatterBit11.format(Instant.now())
            .concat(StringUtils.leftPad(random10Digit().toString(), 6, "0"));
    System.out.println("Bit11 " + bit11);

    ISOMsg msg = new ISOMsg();
    msg.setMTI("2100");
    msg.set(7, formatterBit7.format(Instant.now()));
    msg.set(11, bit11);//from  w  w  w . j  av a2  s  . c om
    msg.set(18, "6012");
    msg.set(33, "1234567");
    msg.set(41, "54FAA005");
    msg.set(48, "523030487642");

    msg.setPackager(packager);
    System.out.println("msg send : " + new String(msg.pack()));
    System.out.println("queue msg sending");
    return msg;
}

From source file:com.enioka.jqm.tools.Loader.java

private void runPayload() {
    // Set thread name
    Thread.currentThread().setName(threadName);

    // One log per launch?
    if (System.out instanceof MultiplexPrintStream) {
        String fileName = StringUtils.leftPad("" + this.job.getId(), 10, "0");
        MultiplexPrintStream mps = (MultiplexPrintStream) System.out;
        mps.registerThread(String.valueOf(fileName + ".stdout.log"));
        mps = (MultiplexPrintStream) System.err;
        mps.registerThread(String.valueOf(fileName + ".stderr.log"));
    }/* www  . ja va  2s .co  m*/

    EntityManager em = null;
    final Map<String, String> params;
    final JarClassLoader jobClassLoader;

    // Block needing the database
    try {
        em = Helpers.getNewEm();

        // Refresh entities from the current EM
        this.job = em.find(JobInstance.class, job.getId());
        this.node = em.find(Node.class, job.getNode().getId());

        // Log
        this.resultStatus = State.SUBMITTED;
        jqmlogger.debug("A loader/runner thread has just started for Job Instance " + job.getId() + ". Jar is: "
                + job.getJd().getJarPath() + " - class is: " + job.getJd().getJavaClassName());

        // Disabled
        if (!this.job.getJd().isEnabled()) {
            jqmlogger.info("Job Instance " + job.getId()
                    + " will actually not truly run as its Job Definition is disabled");
            em.getTransaction().begin();
            this.job.setProgress(-1);
            em.getTransaction().commit();
            resultStatus = State.ENDED;
            endOfRun();
            return;
        }

        // Parameters
        params = new HashMap<String, String>();
        for (RuntimeParameter jp : em
                .createQuery("SELECT p FROM RuntimeParameter p WHERE p.ji = :i", RuntimeParameter.class)
                .setParameter("i", job.getId()).getResultList()) {
            jqmlogger.trace("Parameter " + jp.getKey() + " - " + jp.getValue());
            params.put(jp.getKey(), jp.getValue());
        }

        // Update of the job status, dates & co
        em.getTransaction().begin();
        em.refresh(job, LockModeType.PESSIMISTIC_WRITE);
        if (!job.getState().equals(State.KILLED)) {
            // Use a query to avoid locks on FK checks (with setters, every field is updated!)
            em.createQuery(
                    "UPDATE JobInstance j SET j.executionDate = current_timestamp(), state = 'RUNNING' WHERE j.id = :i")
                    .setParameter("i", job.getId()).executeUpdate();
        }
        em.getTransaction().commit();

        jobClassLoader = this.clm.getClassloader(job, em);
    } catch (JqmPayloadException e) {
        jqmlogger.warn("Could not resolve CLASSPATH for job " + job.getJd().getApplicationName(), e);
        resultStatus = State.CRASHED;
        endOfRun();
        return;
    } catch (MalformedURLException e) {
        jqmlogger.warn("The JAR file path specified in Job Definition is incorrect "
                + job.getJd().getApplicationName(), e);
        resultStatus = State.CRASHED;
        endOfRun();
        return;
    } catch (RuntimeException e) {
        firstBlockDbFailureAnalysis(e);
        return;
    } finally {
        Helpers.closeQuietly(em);
    }

    // Class loader switch
    classLoaderToRestoreAtEnd = Thread.currentThread().getContextClassLoader();
    try {
        // Switch
        jqmlogger.trace("Setting class loader");
        Thread.currentThread().setContextClassLoader(jobClassLoader);
        jqmlogger.trace("Class Loader was set correctly");
    } catch (Exception e) {
        jqmlogger.error("Could not switch classloaders", e);
        this.resultStatus = State.CRASHED;
        endOfRun();
        return;
    }

    // Go! (launches the main function in the startup class designated in the manifest)
    try {
        jobClassLoader.launchJar(job, params);
        this.resultStatus = State.ENDED;
    } catch (JqmKillException e) {
        jqmlogger.info("Job instance  " + job.getId() + " has been killed.");
        this.resultStatus = State.KILLED;
    } catch (Exception e) {
        jqmlogger.info("Job instance " + job.getId() + " has crashed. Exception was:", e);
        this.resultStatus = State.CRASHED;
    }

    // Job instance has now ended its run
    try {
        endOfRun();
    } catch (Exception e) {
        jqmlogger.error("An error occurred while finalizing the job instance.", e);
    }

    jqmlogger.debug("End of loader for JobInstance " + this.job.getId() + ". Thread will now end");
}

From source file:net.sourceforge.fenixedu.domain.accounting.util.IndividualCandidacyPaymentCodeGenerator.java

@Override
public String generateNewCodeFor(PaymentCodeType paymentCodeType, Person person) {
    final PaymentCode lastPaymentCode = findLastPaymentCode(paymentCodeType);
    int nextSequentialNumber = lastPaymentCode == null ? 0
            : Integer.valueOf(getSequentialNumber(lastPaymentCode)) + 1;

    String sequentialNumberPadded = StringUtils.leftPad(String.valueOf(nextSequentialNumber),
            NUM_SEQUENTIAL_NUMBERS, CODE_FILLER);
    String typeDigitsPadded = StringUtils.leftPad(String.valueOf(paymentCodeType.getTypeDigit()),
            NUM_TYPE_DIGITS, CODE_FILLER);
    String controDigitsPadded = StringUtils.leftPad(String.valueOf((new Random()).nextInt(99)),
            NUM_CONTROL_DIGITS, CODE_FILLER);

    return START + sequentialNumberPadded + typeDigitsPadded + controDigitsPadded;
}

From source file:com.intuit.tank.harness.functions.GenericFunctions.java

/**
 * //from w  w w.  j av a  2s  .  com
 * @param startSsn
 * @return
 */
public static String getSsn(String val) {
    int ret = 0;
    if (lastSSN < 0) {
        int startSsn = 100000000;
        if (NumberUtils.isDigits(val)) {
            startSsn = Integer.parseInt(val);
        }
        lastSSN = startSsn;
    }
    Stack<Integer> stack = StringFunctions.getStack(lastSSN, 899999999, null, false);
    do {
        ret = stack.pop();
    } while (!isValidSsn(ret));

    String ssnString = Integer.toString(ret);
    StringUtils.leftPad(ssnString, 9, '0');

    ssnString = ssnString.substring(0, 3) + "-" + ssnString.substring(3, 5) + "-" + ssnString.substring(5, 9);
    return ssnString;
}

From source file:net.sourceforge.fenixedu.domain.accounting.util.PersonRotationPaymentCodeGenerator.java

private static String getPersonCodeDigits(Person person) {
    if (person.getIstUsername().length() > 9) {
        throw new RuntimeException(
                "SIBS Payment Code: " + person.getIstUsername() + " exceeded maximun size accepted");
    }/*from  w  w w. j  a  v a2s  .  com*/
    return StringUtils.leftPad(person.getIstUsername().replace("ist", ""), PERSON_CODE_LENGTH, CODE_FILLER);
}

From source file:com.alibaba.otter.shared.arbitrate.impl.manage.helper.ManagePathUtils.java

/**
 * processIdzookeepernode??/*from ww w  .j a  v  a 2  s .c  o m*/
 */
public static String getProcessNode(Long processId) {
    return StringUtils.leftPad(String.valueOf(processId.intValue()), 10, '0');
}

From source file:alma.acs.container.archive.IdentifierJMock.java

private String createUid() {
    String uid = "uid://X" + StringUtils.leftPad(Long.toHexString(archiveid), archiveIdLength, '0') + "/X"
            + Long.toHexString(rangeid) + "/X0";
    return uid;/*from w  ww  . ja v  a 2 s.  co  m*/
}