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:org.codehaus.mojo.mrm.impl.digest.MD5DigestFileEntry.java

/**
 * Generates the digest.//from w w  w.  j  av  a  2  s. co  m
 *
 * @return the digest.
 * @throws IOException if the backing entry could not be read.
 * @since 1.0
 */
private byte[] getContent() throws IOException {
    InputStream is = null;
    try {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.reset();
        byte[] buffer = new byte[8192];
        int read;
        try {
            is = entry.getInputStream();
            while ((read = is.read(buffer)) > 0) {
                digest.update(buffer, 0, read);
            }
        } catch (IOException e) {
            if (is != null) {
                throw e;
            }
        }
        final String md5 = StringUtils.leftPad(new BigInteger(1, digest.digest()).toString(16), 32, "0");
        return md5.getBytes();
    } catch (NoSuchAlgorithmException e) {
        IOException ioe = new IOException("Unable to calculate hash");
        ioe.initCause(e);
        throw ioe;
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:org.codehaus.mojo.mrm.impl.digest.SHA1DigestFileEntry.java

/**
 * Generates the digest./*www .  ja  v  a 2  s .c om*/
 *
 * @return the digest.
 * @throws IOException if the backing entry could not be read.
 * @since 1.0
 */
private byte[] getContent() throws IOException {
    InputStream is = null;
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA1");
        digest.reset();
        byte[] buffer = new byte[8192];
        int read;
        try {
            is = entry.getInputStream();
            while ((read = is.read(buffer)) > 0) {
                digest.update(buffer, 0, read);
            }
        } catch (IOException e) {
            if (is != null) {
                throw e;
            }
        }
        final String md5 = StringUtils.leftPad(new BigInteger(1, digest.digest()).toString(16), 40, "0");
        return md5.getBytes();
    } catch (NoSuchAlgorithmException e) {
        IOException ioe = new IOException("Unable to calculate hash");
        ioe.initCause(e);
        throw ioe;
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:org.codelabor.example.lang.StringUtilsTest.java

/**
 * Test method for// w  w w  .  ja v  a 2s . c  o  m
 * {@link org.apache.commons.lang.StringEscapeUtils#escapeHtml(java.lang.String)}
 * .
 */
@Test
public void testLeftPad() {
    String originalString = "abcd";
    String paddedString = StringUtils.leftPad(originalString, 10, "0");
    logger.debug("originalString: {}", originalString);
    logger.debug("paddedString: {}", paddedString);

    paddedString = StringUtils.leftPad(originalString, 2, "0");
    logger.debug("originalString: {}", originalString);
    logger.debug("paddedString: {}", paddedString);
}

From source file:org.codelabor.system.file.anyframe.idgen.UniqueFilenameStrategy.java

public String makeId(String originalId) {
    DateFormat dateFormat = new SimpleDateFormat(dateAndTimePattern, Locale.getDefault());
    String dateFormatString = dateFormat.format(System.currentTimeMillis());
    StringBuilder sb = new StringBuilder();
    sb.append(prefix);//from   ww w  . j ava 2 s .c  o  m
    if (delimiter != null) {
        sb.append(delimiter);
    }
    sb.append(dateFormatString);
    if (delimiter != null) {
        sb.append(delimiter);
    }
    String trimedId = null;
    if (originalId.length() > cipers) {
        trimedId = originalId.substring(0, cipers);
    } else {
        trimedId = originalId;
    }
    sb.append(StringUtils.leftPad(trimedId, cipers, fillChar));
    logger.debug("id: {}", sb.toString());

    return sb.toString();
}

From source file:org.commonjava.maven.ext.core.impl.VersionCalculator.java

/**
 * Calculate any project version changes for the given set of projects, and return them in a Map keyed by project
 * GA.//www . j  a  va  2 s  .co m
 *
 * @param projects the Projects to adjust.
 * @param session the container session.
 * @return a collection of GAV : new Version
 * @throws ManipulationException if an error occurs.
 */
public Map<ProjectVersionRef, String> calculateVersioningChanges(final List<Project> projects,
        final ManipulationSession session) throws ManipulationException {
    final VersioningState state = session.getState(VersioningState.class);
    final Map<ProjectVersionRef, String> versionsByGAV = new HashMap<>();
    final Set<String> versionsWithBuildNums = new HashSet<>();

    for (final Project project : projects) {
        String originalVersion = PropertyResolver.resolveInheritedProperties(session, project,
                project.getVersion());
        String modifiedVersion = calculate(project.getGroupId(), project.getArtifactId(), originalVersion,
                session);

        if (state.osgi()) {
            modifiedVersion = Version.getOsgiVersion(modifiedVersion);
        }

        versionsByGAV.put(project.getKey(), modifiedVersion);

        if (Version.hasBuildNumber(modifiedVersion)) {
            versionsWithBuildNums.add(modifiedVersion);
        }
    }

    // Have to loop through the versions a second time to make sure that the versions are in sync
    // between projects in the reactor.
    logger.debug("Syncing projects within reactor...");
    for (final Project project : projects) {
        final String originalVersion = project.getVersion();

        String modifiedVersion = versionsByGAV.get(project.getKey());

        // If there is only a single version there is no real need to try and find the highest matching.
        // This also fixes the problem where there is a single version and leading zeros.
        int buildNumber = findHighestMatchingBuildNumber(modifiedVersion, versionsWithBuildNums);

        // If the buildNumber is greater than zero, it means we found a match and have to
        // set the build number to avoid version conflicts.
        if (buildNumber > 0) {
            String paddedBuildNum = StringUtils.leftPad(Integer.toString(buildNumber), Version
                    .getBuildNumberPadding(state.getIncrementalSerialSuffixPadding(), versionsWithBuildNums),
                    '0');
            modifiedVersion = Version.setBuildNumber(modifiedVersion, paddedBuildNum);
        }

        versionsWithBuildNums.add(modifiedVersion);
        logger.debug(gav(project) + " has updated version: {}. Marking for rewrite.", modifiedVersion);

        if (!originalVersion.equals(modifiedVersion)) {
            versionsByGAV.put(project.getKey(), modifiedVersion);
        }
    }

    return versionsByGAV;
}

From source file:org.commonjava.maven.ext.core.impl.VersionCalculator.java

/**
 * Calculate the version modification for a given GAV.
 *
 * @param groupId the groupId to search for
 * @param artifactId the artifactId to search for.
 * @param version the original version to search for.
 * @param session the container session.
 * @return a Version object allowing the modified version to be extracted.
 * @throws ManipulationException if an error occurs.
 *//*from w w w . ja  va  2s .c o m*/
protected String calculate(final String groupId, final String artifactId, final String version,
        final ManipulationSession session) throws ManipulationException {
    final VersioningState state = session.getState(VersioningState.class);

    final String incrementalSuffix = state.getIncrementalSerialSuffix();
    final String staticSuffix = state.getSuffix();
    final String override = state.getOverride();

    logger.debug("Got the following original version: {}", version);
    logger.debug("Got the following version suffixes:\n  Static: {}\n  Incremental: {}", staticSuffix,
            incrementalSuffix);
    logger.debug("Got the following version override: {}", override);

    String newVersion = version;

    if (override != null) {
        newVersion = override;
    }

    if (staticSuffix != null) {
        newVersion = Version.appendQualifierSuffix(newVersion, staticSuffix);
        if (!state.preserveSnapshot()) {
            newVersion = Version.removeSnapshot(newVersion);
        }
    } else if (incrementalSuffix != null) {
        final Set<String> versionCandidates = this.getVersionCandidates(state, groupId, artifactId);

        newVersion = Version.appendQualifierSuffix(newVersion, incrementalSuffix);
        int highestRemoteBuildNumPlusOne = findHighestMatchingBuildNumber(newVersion, versionCandidates) + 1;

        if (highestRemoteBuildNumPlusOne > Version.getIntegerBuildNumber(newVersion)) {
            String paddedBuildNumber = StringUtils.leftPad(Integer.toString(highestRemoteBuildNumPlusOne),
                    Version.getBuildNumberPadding(state.getIncrementalSerialSuffixPadding(), versionCandidates),
                    '0');
            newVersion = Version.setBuildNumber(newVersion, paddedBuildNumber);
        }
        if (!state.preserveSnapshot()) {
            newVersion = Version.removeSnapshot(newVersion);
        }
    }
    logger.debug("Returning version: {}", newVersion);

    return newVersion;
}

From source file:org.commonjava.maven.ext.core.impl.VersioningCalculatorTest.java

@Test
public void verifyPaddingSuffix() {
    String paddedBuildNum = StringUtils.leftPad("1", 0, '0');
    System.out.println("### got " + paddedBuildNum);
    assertTrue(paddedBuildNum.equals("1"));
    paddedBuildNum = StringUtils.leftPad("1", 1, '0');
    System.out.println("### got " + paddedBuildNum);
    assertTrue(paddedBuildNum.equals("1"));

    paddedBuildNum = StringUtils.leftPad("1", 2, '0');
    System.out.println("### got " + paddedBuildNum);
    assertTrue(paddedBuildNum.equals("01"));

    paddedBuildNum = StringUtils.leftPad("1", 3, '0');
    System.out.println("### got " + paddedBuildNum);
    assertTrue(paddedBuildNum.equals("001"));

    paddedBuildNum = StringUtils.leftPad("10", 3, '0');
    System.out.println("### got " + paddedBuildNum);
    assertTrue(paddedBuildNum.equals("010"));

    paddedBuildNum = StringUtils.leftPad("010", 3, '0');
    System.out.println("### got " + paddedBuildNum);
    assertTrue(paddedBuildNum.equals("010"));

    paddedBuildNum = StringUtils.leftPad("010", 6, '0');
    System.out.println("### got " + paddedBuildNum);
    assertTrue(paddedBuildNum.equals("000010"));
}

From source file:org.commonjava.maven.ext.manip.impl.VersionCalculator.java

/**
 * Calculate any project version changes for the given set of projects, and return them in a Map keyed by project
 * GA.//from  ww w.ja  v a  2s .c o m
 *
 * @param projects the Projects to adjust.
 * @param session the container session.
 * @return a collection of GAV : new Version
 * @throws ManipulationException if an error occurs.
 */
public Map<ProjectVersionRef, String> calculateVersioningChanges(final List<Project> projects,
        final ManipulationSession session) throws ManipulationException {
    final VersioningState state = session.getState(VersioningState.class);
    final Map<ProjectVersionRef, String> versionsByGAV = new HashMap<>();
    final Map<ProjectVersionRef, Version> versionObjsByGAV = new HashMap<>();
    final Set<String> versionSet = new HashSet<>();

    for (final Project project : projects) {
        String originalVersion = project.getVersion();
        String modifiedVersionString;
        originalVersion = PropertiesUtils.resolveProperties(projects, originalVersion);
        final Version modifiedVersion = calculate(project.getGroupId(), project.getArtifactId(),
                originalVersion, session);
        versionObjsByGAV.put(project.getKey(), modifiedVersion);

        if (state.osgi()) {
            modifiedVersionString = modifiedVersion.getOSGiVersionString();
        } else {
            modifiedVersionString = modifiedVersion.getVersionString();
        }

        if (modifiedVersion.hasBuildNumber()) {
            versionSet.add(modifiedVersionString);
        }
    }

    // Have to loop through the versions a second time to make sure that the versions are in sync
    // between projects in the reactor.
    for (final Project project : projects) {
        final String originalVersion = project.getVersion();
        String modifiedVersionString;

        final Version modifiedVersion = versionObjsByGAV.get(project.getKey());

        // If there is only a single version there is no real need to try and find the highest matching.
        // This also fixes the problem where there is a single version and leading zeros.
        if (versionSet.size() > 1) {
            int buildNumber = findHighestMatchingBuildNumber(modifiedVersion, versionSet);

            // If the buildNumber is greater than zero, it means we found a match and have to
            // set the build number to avoid version conflicts.
            if (buildNumber > 0) {
                modifiedVersion.setBuildNumber(StringUtils.leftPad(Integer.toString(buildNumber),
                        state.getIncrementalSerialSuffixPadding(), '0'));
            }
        }

        if (state.osgi()) {
            modifiedVersionString = modifiedVersion.getOSGiVersionString();
        } else {
            modifiedVersionString = modifiedVersion.getVersionString();
        }

        versionSet.add(modifiedVersionString);
        logger.debug(gav(project) + " has updated version: {}. Marking for rewrite.", modifiedVersionString);

        if (!originalVersion.equals(modifiedVersionString)) {
            versionsByGAV.put(project.getKey(), modifiedVersionString);
        }
    }

    return versionsByGAV;
}

From source file:org.commonjava.maven.ext.manip.impl.VersionCalculator.java

/**
 * Calculate the version modification for a given GAV.
 *
 * @param groupId the groupId to search for
 * @param artifactId the artifactId to search for.
 * @param version the original version to search for.
 * @param session the container session.
 * @return a Version object allowing the modified version to be extracted.
 * @throws ManipulationException if an error occurs.
 *//*from www. j  a  v  a  2  s  .co  m*/
protected Version calculate(final String groupId, final String artifactId, final String version,
        final ManipulationSession session) throws ManipulationException {
    final VersioningState state = session.getState(VersioningState.class);

    final String incrementalSuffix = state.getIncrementalSerialSuffix();
    final String staticSuffix = state.getSuffix();
    final String override = state.getOverride();

    logger.debug("Got the following version:\n  Original version: " + version);
    logger.debug("Got the following version suffixes:\n  Static: " + staticSuffix + "\n  Incremental: "
            + incrementalSuffix);
    logger.debug("Got the following override:\n  Version: " + override);

    Version versionObj;

    if (override != null) {
        versionObj = new Version(override);
    } else {
        versionObj = new Version(version);
    }

    if (staticSuffix != null) {
        versionObj.appendQualifierSuffix(staticSuffix);
        if (!state.preserveSnapshot()) {
            versionObj.setSnapshot(false);
        }
    } else if (incrementalSuffix != null) {
        // Find matching version strings in the remote repo and increment to the next
        // available version
        final Set<String> versionCandidates = new HashSet<>();

        Map<ProjectRef, Set<String>> rm = state.getRESTMetadata();
        if (rm != null) {
            // If the REST Client has prepopulated incremental data use that instead of the examining the repository.
            if (!rm.isEmpty()) {
                // Use preloaded metadata from remote repository, loaded via a REST Call.
                if (rm.get(new SimpleProjectRef(groupId, artifactId)) != null) {
                    versionCandidates.addAll(rm.get(new SimpleProjectRef(groupId, artifactId)));
                }
            }
        } else {
            // Load metadata from local repository
            versionCandidates.addAll(getMetadataVersions(groupId, artifactId));
        }
        versionObj.appendQualifierSuffix(incrementalSuffix);
        int highestRemoteBuildNum = findHighestMatchingBuildNumber(versionObj, versionCandidates);
        ++highestRemoteBuildNum;

        if (highestRemoteBuildNum > versionObj.getIntegerBuildNumber()) {
            versionObj.setBuildNumber(StringUtils.leftPad(Integer.toString(highestRemoteBuildNum),
                    state.getIncrementalSerialSuffixPadding(), '0'));
        }
        if (!state.preserveSnapshot()) {
            versionObj.setSnapshot(false);
        }
    }

    return versionObj;
}

From source file:org.dspace.util.SolrImportExport.java

/**
 * Creates a filename for the export batch.
 *
 * @param indexName The name of the index being exported.
 * @param exportStart The start timestamp of the export
 * @param totalRecords The total number of records in the export.
 * @param index The index of the current batch.
 * @return A file name that is appropriate to use for exporting the batch of data described by the parameters.
 *//* w w w.j  a v  a2s  . c  o  m*/
private static String makeExportFilename(String indexName, Date exportStart, long totalRecords, int index) {
    String exportFileNumber = "";
    if (totalRecords > ROWS_PER_FILE) {
        exportFileNumber = StringUtils.leftPad("" + (index / ROWS_PER_FILE),
                (int) Math.ceil(Math.log10(totalRecords / ROWS_PER_FILE)), "0");
    }
    return indexName + EXPORT_SEP + EXPORT_DATE_FORMAT.get().format(exportStart)
            + (StringUtils.isNotBlank(exportFileNumber) ? "_" + exportFileNumber : "") + ".csv";
}