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.finra.dm.service.AbstractServiceTest.java

/**
 * Creates relative database entities required for the unit tests.
 *//*from w w  w  . j  a v a  2 s.  com*/
protected void createDatabaseEntitiesForBusinessObjectDataDdlTesting(String businessObjectFormatFileType,
        String partitionKey, String partitionKeyGroupName, int partitionColumnPosition,
        List<String> partitionValues, List<String> subPartitionValues, String schemaDelimiterCharacter,
        String schemaEscapeCharacter, String schemaNullValue, List<SchemaColumn> schemaColumns,
        List<SchemaColumn> partitionColumns, boolean replaceUnderscoresWithHyphens, String customDdlName,
        boolean generateStorageFileEntities) {
    // Create a business object format entity if it does not exist.
    BusinessObjectFormatEntity businessObjectFormatEntity = dmDao
            .getBusinessObjectFormatByAltKey(new BusinessObjectFormatKey(NAMESPACE_CD, BOD_NAME,
                    FORMAT_USAGE_CODE, businessObjectFormatFileType, FORMAT_VERSION));
    if (businessObjectFormatEntity == null) {
        businessObjectFormatEntity = createBusinessObjectFormatEntity(NAMESPACE_CD, BOD_NAME, FORMAT_USAGE_CODE,
                businessObjectFormatFileType, FORMAT_VERSION, FORMAT_DESCRIPTION, true, partitionKey,
                partitionKeyGroupName, schemaDelimiterCharacter, schemaEscapeCharacter, schemaNullValue,
                schemaColumns, partitionColumns);
    }

    if (StringUtils.isNotBlank(customDdlName)) {
        boolean partitioned = (partitionColumns != null);
        createCustomDdlEntity(businessObjectFormatEntity, customDdlName, getTestCustomDdl(partitioned));
    }

    // Create business object data entities along with the corresponding storage unit entities.
    StorageEntity storageEntity = dmDao.getStorageByName(StorageEntity.MANAGED_STORAGE);

    // Create business object data for each partition value.
    for (String partitionValue : partitionValues) {
        BusinessObjectDataEntity businessObjectDataEntity;
        if (partitionColumnPosition == BusinessObjectDataEntity.FIRST_PARTITION_COLUMN_POSITION) {
            businessObjectDataEntity = createBusinessObjectDataEntity(NAMESPACE_CD, BOD_NAME, FORMAT_USAGE_CODE,
                    businessObjectFormatFileType, FORMAT_VERSION, partitionValue, subPartitionValues,
                    DATA_VERSION, true, BusinessObjectDataStatusEntity.VALID);
        } else {
            List<String> testSubPartitionValues = new ArrayList<>(subPartitionValues);
            // Please note that the second partition column is located at index 0.
            testSubPartitionValues.set(partitionColumnPosition - 2, partitionValue);
            businessObjectDataEntity = createBusinessObjectDataEntity(NAMESPACE_CD, BOD_NAME, FORMAT_USAGE_CODE,
                    businessObjectFormatFileType, FORMAT_VERSION, PARTITION_VALUE, testSubPartitionValues,
                    DATA_VERSION, true, BusinessObjectDataStatusEntity.VALID);
        }

        String s3KeyPrefix = businessObjectDataHelper.buildS3KeyPrefix(businessObjectFormatEntity,
                dmDaoHelper.getBusinessObjectDataKey(businessObjectDataEntity));
        StorageUnitEntity storageUnitEntity = createStorageUnitEntity(storageEntity, businessObjectDataEntity);

        // If flag is set, create one storage file for each "auto-discoverable" partition.
        // Please note that is n! - thus we want to keep the number of partition levels small.
        if (generateStorageFileEntities) {
            int discoverableSubPartitionsCount = partitionColumns != null
                    ? partitionColumns.size() - subPartitionValues.size() - 1
                    : 0;
            int storageFilesCount = (int) Math.pow(2, discoverableSubPartitionsCount);
            for (int i = 0; i < storageFilesCount; i++) {
                // Build a relative sub-directory path.
                StringBuilder subDirectory = new StringBuilder();
                String binaryString = StringUtils.leftPad(Integer.toBinaryString(i),
                        discoverableSubPartitionsCount, "0");
                for (int j = 0; j < discoverableSubPartitionsCount; j++) {
                    String subpartitionKey = partitionColumns.get(j + subPartitionValues.size() + 1).getName()
                            .toLowerCase();
                    if (replaceUnderscoresWithHyphens) {
                        subpartitionKey = subpartitionKey.replace("_", "-");
                    }
                    subDirectory
                            .append(String.format("/%s=%s", subpartitionKey, binaryString.substring(j, j + 1)));
                }
                // Create a storage file entity.
                createStorageFileEntity(storageUnitEntity,
                        String.format("%s%s/data.dat", s3KeyPrefix, subDirectory.toString()), FILE_SIZE_1_KB,
                        ROW_COUNT_1000);
            }
        }
        // Add storage directory path value to the storage unit, since we have no storage files generated.
        else {
            storageUnitEntity.setDirectoryPath(s3KeyPrefix);
        }

        dmDao.saveAndRefresh(storageUnitEntity);
        dmDao.saveAndRefresh(businessObjectDataEntity);
    }
}

From source file:org.fsl.roms.service.action.RoadCheckServiceAction.java

public static String doTRNBumpUp(String trnNbr) {
    int trnLen = 9;
    String trnVal = "";
    //Pads the TRN with the required number of zeros
    trnVal = StringUtils.leftPad(trnNbr, trnLen, "0");
    return trnVal;
}

From source file:org.fuin.auction.common.AbstractOperationResult.java

@Override
public final String getCodeStr() {
    return StringUtils.leftPad("" + code, 5, "0");
}

From source file:org.gradle.configuration.TaskDetailPrinter.java

private LinePrefixingStyledTextOutput createIndentedOutput(StyledTextOutput output, int offset) {
    return createIndentedOutput(output, StringUtils.leftPad("", offset, ' '));
}

From source file:org.jahia.modules.external.ExternalContentStoreProvider.java

/**
 * Initializes this provider instance. Should be called after the {@link #setKey(String)} was called to set the provider key.
 *
 * @throws RepositoryException//  w ww .jav a 2  s .  c o  m
 *             in case of an initialization error
 */
protected void init() throws RepositoryException {
    if (getKey() == null) {
        throw new IllegalArgumentException(
                "The key is not specified for the provider instance." + " Unable to initialize this provider.");
    }
    id = StringUtils.leftPad(externalProviderInitializerService.getProviderId(getKey()).toString(), 8, "f");
}

From source file:org.jahia.services.render.filter.URLFilter.java

public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    if (handlers != null && handlers.length > 0) {
        final String thisuuid = StringUtils.leftPad(Integer.toHexString(resource.hashCode()), 8, "0");
        Map<String, String> alreadyParsedFragmentsMap = new HashMap<>();
        StringBuilder sb = null;//from  ww w.  jav  a 2  s .co m
        int i;
        if (previousOut.indexOf(TEMP_START_TAG) > -1) {
            sb = new StringBuilder(previousOut);

            // store all the already processed url traverse
            while ((i = sb.indexOf(TEMP_START_TAG)) > -1) {
                String uuid = sb.substring(i + TEMP_START_TAG.length(), i + TEMP_START_TAG.length() + 8);
                final String endTag = TEMP_END_TAG + uuid + TEMP_CLOSING;
                int j = sb.indexOf(endTag);
                alreadyParsedFragmentsMap.put(uuid, sb.substring(i + TEMP_FULL_START_TAG.length(), j));
                sb.delete(i, j + endTag.length());
                sb.insert(i, "\"/>").insert(i, uuid).insert(i, REPLACED_START_TAG);
            }
        }

        // traverse the fragment and wrap it with a temp tag
        sb = new StringBuilder(urlTraverser.traverse(sb == null ? previousOut : sb.toString(), renderContext,
                resource, handlers));
        sb.insert(0, TEMP_CLOSING).insert(0, thisuuid).insert(0, TEMP_START_TAG);
        sb.append(TEMP_END_TAG).append(thisuuid).append(TEMP_CLOSING);

        // replace all the previous stored fragments
        while ((i = sb.indexOf(REPLACED_START_TAG)) > -1) {
            String uuid = sb.substring(i + REPLACED_START_TAG.length(), i + REPLACED_START_TAG.length() + 8);
            sb.replace(i, i + REPLACED_START_TAG.length() + 8 + 3, alreadyParsedFragmentsMap.get(uuid));
        }
        return sb.toString();
    }

    return previousOut;
}

From source file:org.jajuk.util.UtilPrepareParty.java

/**
   * Copies the files contained in the list to the specified directory.
   * // w w w  .j a v  a2 s  .com
   * @param files The list of flies to copy.
   * @param destDir The target location.
   * @param isNormalize 
   * @param isConvertMedia 
   * @param media 
   * @param convertCommand 
   */
  public static void copyFiles(final List<org.jajuk.base.File> files, final java.io.File destDir,
          final boolean isNormalize, final boolean isConvertMedia, final String media,
          final String convertCommand) {
      Thread thread = new Thread("PrepareParty - File Copy") {
          @Override
          public void run() {
              UtilGUI.waiting();
              // start time to display elapsed time at the end
              long lRefreshDateStart = System.currentTimeMillis();
              // start copying and create a playlist on the fly
              int convert_errors = 0;
              final java.io.File file = new java.io.File(destDir.getAbsolutePath() + "/playlist.m3u");
              try {
                  final BufferedWriter bw = new BufferedWriter(new FileWriter(file));
                  try {
                      bw.write(Const.PLAYLIST_NOTE);
                      int count = 0;
                      for (final org.jajuk.base.File entry : files) {
                          // update progress
                          count++;
                          // We can use the actual file name as we do numbering of the files,
                          // this is important for existing playlists to keep the order
                          String name = StringUtils.leftPad(Integer.valueOf(count).toString(), 5, '0') + '_'
                                  + entry.getFIO().getName();
                          // normalize filenames if necessary
                          if (isNormalize) {
                              name = UtilPrepareParty.normalizeFilename(name);
                          }
                          // check if we need to convert the file format
                          if (isConvertMedia && !entry.getType().getExtension().equals(media)) {
                              // Notify that we are converting a file
                              Properties properties = new Properties();
                              properties.put(Const.DETAIL_CONTENT, entry.getName());
                              properties.put(Const.DETAIL_NEW, name + "." + media);
                              ObservationManager.notify(new JajukEvent(JajukEvents.FILE_CONVERSION, properties));
                              int ret = UtilPrepareParty.convertPACPL(convertCommand, entry.getFIO(), media,
                                      destDir, name);
                              if (ret != 0) {
                                  convert_errors++;
                                  // do a normal copy of original format if it cannot be converted
                                  FileUtils.copyFile(entry.getFIO(), new File(destDir, name));
                              } else {
                                  // Conversion is done, new filename is <oldname.old_extension.target_extension>
                                  name = name + "." + media;
                              }
                          } else {
                              // do a normal copy otherwise
                              FileUtils.copyFile(entry.getFIO(), new File(destDir, name));
                          }
                          // increase hits for this track/file as it is likely played outside of Jajuk
                          entry.getTrack().incHits();
                          // write playlist as well
                          bw.newLine();
                          bw.write(name);
                          // Notify that a file has been copied
                          Properties properties = new Properties();
                          properties.put(Const.DETAIL_CONTENT, entry.getName());
                          ObservationManager.notify(new JajukEvent(JajukEvents.FILE_COPIED, properties));
                      }
                      bw.flush();
                  } finally {
                      bw.close();
                  }
                  // Send a last event with null properties to inform the
                  // client that the party is done
                  ObservationManager.notify(new JajukEvent(JajukEvents.FILE_COPIED));
              } catch (final IOException e) {
                  Log.error(e);
                  Messages.showErrorMessage(180, e.getMessage());
                  return;
              } finally {
                  long refreshTime = System.currentTimeMillis() - lRefreshDateStart;
                  // inform the user about the number of resulting tracks
                  StringBuilder sbOut = new StringBuilder();
                  sbOut.append(Messages.getString("PreparePartyWizard.31")).append(" ")
                          .append(destDir.getAbsolutePath()).append(".\n").append(files.size()).append(" ")
                          .append(Messages.getString("PreparePartyWizard.23")).append(" ")
                          .append(((refreshTime < 1000) ? refreshTime + " ms." : refreshTime / 1000 + " s."));
                  // inform user if converting did not work
                  if (convert_errors > 0) {
                      sbOut.append("\n").append(Integer.toString(convert_errors))
                              .append(Messages.getString("PreparePartyWizard.36"));
                  }
                  String message = sbOut.toString();
                  Log.debug(message);
                  UtilGUI.stopWaiting();
                  // Display end of copy message with stats
                  Messages.showInfoMessage(message);
              }
          }
      };
      thread.start();
  }

From source file:org.jasig.portal.utils.cache.CacheKey.java

@Override
public String toString() {
    int d = DEPTH.get();
    DEPTH.set(d + 1);//w ww .j a v  a  2  s  .  c  o  m
    final String indent = StringUtils.leftPad("", DEPTH.get(), '\t');
    final String s = indent + "CacheKey [" + this.source + "\n\t" + indent + Arrays.deepToString(this.key)
            + "\n" + indent + "]";
    DEPTH.set(d);
    return s;
}

From source file:org.jasig.schedassist.impl.relationship.advising.TermCalculator.java

/**
 * Calculate the term number for the specified date time (as a {@link Calendar}).
 * This uses a rough formula to determine Fall/Spring/Summer semesters:
 <pre>// w  w w  .j  a  v a 2  s.  com
 if the month is between January and May (inclusive), the term is Spring.
 if the month is between June and August (inclusive), the term is Summer.
 if the month is between September and December (inclusive), the term is Fall.
 </pre>
 *
 * This is only approximate.
 * 
 * @param calendar
 * @return
 */
public static String calculateTerm(final Calendar calendar) {
    StringBuilder term = new StringBuilder();

    int month = calendar.get(Calendar.MONTH);
    String monthDigit;
    if (month >= Calendar.JANUARY && month <= Calendar.MAY) {
        monthDigit = "4";
    } else if (month >= Calendar.JUNE && month <= Calendar.AUGUST) {
        monthDigit = "6";
    } else {
        monthDigit = "2";
    }

    int year = calendar.get(Calendar.YEAR);
    if ("2".equals(monthDigit)) {
        // increment year by one for fall semester
        year++;
    }

    String centuryDigit = "0";
    if (year >= 2000) {
        centuryDigit = "1";
    }

    int twoDigitYear = year % 100;
    String yearDigit = StringUtils.leftPad(Integer.toString(twoDigitYear), 2, "0");

    term.append(centuryDigit);
    term.append(yearDigit);
    term.append(monthDigit);
    return term.toString();
}

From source file:org.jasig.ssp.service.impl.PersonServiceBulkCoachLookupIntegrationTest.java

private Set<String> addCoachesToExternalDataAndAttributeService(int quota) {
    Set<String> usernames = Sets.newHashSet();
    if (quota <= 0) {
        return usernames;
    }//  w w  w .  j ava2 s.co m
    for (int i = 1; i <= quota; i++) {
        String paddedIdx = StringUtils.leftPad("" + i, 3, "0");
        String username = "bulk_coach_" + paddedIdx;
        createExternalPerson("bulk_coach_school_id_" + paddedIdx, username, "BulkCoach",
                "BulkCoach" + paddedIdx, "" + i, "bulkcoach" + paddedIdx + "@school.edu");
        usernames.add(username);
    }
    personAttributesService.getCoachUsernames().addAll(usernames);
    sessionFactory.getCurrentSession().flush();
    return usernames;
}