Java 类org.apache.commons.lang.text.StrBuilder 实例源码

项目:Open-DM    文件:ArcProfileMgr.java   
/**
 * Entry point for generating a directory listing.
 */
public void execute(PrintWriter out, PrintWriter err) {
    StrBuilder output = new StrBuilder();

    if (listProfiles) {
        output.append(createProfileListing());
    } else if (printProfile) {
        output.append(getProfileDetails(profileName));
    } else if (createProfile) {
        output.append(createProfile());
    } else if (deleteProfile) {
        output.append(deleteProfile());
    } else {
        output.append(helpScreen());
    }

    out.println(output.toString());
    out.flush();
    err.flush();
}
项目:Open-DM    文件:ArcProfileMgr.java   
/**
 * Delete an existing Profile
 */
protected String deleteProfile() {
    StrBuilder output = new StrBuilder();
    AbstractProfileBase profile = ProfileManager.getProfileByName(profileName);

    try {
        ProfileManager.deleteProfile(profile, true);
    } catch (Exception e) {
        String errMsg = "Error deleting profile '" + profile + "'";
        errMsg = DBUtils.getErrorMessage(errMsg, e);
        LOG.log(Level.WARNING, errMsg, e);
        output.append(errMsg);
        setExitCode(EXIT_CODE_DM_ERROR);
    }

    return output.toString();
}
项目:Open-DM    文件:ArcProfileMgr.java   
/**
 * Create the Profile listing output
 */
protected String createProfileListing() {
    StrBuilder sb = new StrBuilder();
    List<AbstractProfileBase> profileList = getProfiles();

    columnWidths = calcColumnWidths(profileList);

    for (Map.Entry<String, Integer> entry : columnWidths.entrySet()) {
        sb.appendFixedWidthPadRight(entry.getKey(), entry.getValue(), ' ').append(COL_SEP);
    }
    sb.append(NEWLINE);

    for (AbstractProfileBase profile : profileList) {
        sb.appendFixedWidthPadRight("" + profile.getName(), columnWidths.get(KEY_PROFILE_NAME),
                                    ' ')
                .append(COL_SEP);
        sb.appendFixedWidthPadRight("" + profile.getType(), columnWidths.get(KEY_TYPE), ' ')
                .append(COL_SEP);
        sb.append(NEWLINE);
    }

    return sb.toString();
}
项目:lams    文件:NumberRange.java   
/**
 * <p>Returns the string representation of this range.</p>
 *
 * <p>This string is the string representation of the minimum and
 * maximum numbers in the range, separated by a hyphen. If a number
 * is negative, then it is enclosed in parentheses.</p>
 *
 * @return the string representation of this range
 */
public String toString() {
    StrBuilder sb = new StrBuilder();

    if (min.doubleValue() < 0) {
        sb.append('(')
            .append(min)
            .append(')');
    } else {
        sb.append(min);
    }

    sb.append('-');

    if (max.doubleValue() < 0) {
        sb.append('(')
            .append(max)
            .append(')');
    } else {
        sb.append(max);
    }

    return sb.toString();
}
项目:lams    文件:CharSetUtils.java   
/**
 * <p>Squeezes any repetitions of a character that is mentioned in the
 * supplied set.</p>
 *
 * <p>An example is:</p>
 * <ul>
 *   <li>squeeze(&quot;hello&quot;, {&quot;el&quot;}) => &quot;helo&quot;</li>
 * </ul>
 * 
 * @see CharSet#getInstance(java.lang.String) for set-syntax.
 * @param str  the string to squeeze, may be null
 * @param set  the character set to use for manipulation, may be null
 * @return modified String, <code>null</code> if null string input
 */
public static String squeeze(String str, String[] set) {
    if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set)) {
        return str;
    }
    CharSet chars = CharSet.getInstance(set);
    StrBuilder buffer = new StrBuilder(str.length());
    char[] chrs = str.toCharArray();
    int sz = chrs.length;
    char lastChar = ' ';
    char ch = ' ';
    for (int i = 0; i < sz; i++) {
        ch = chrs[i];
        if (chars.contains(ch)) {
            if ((ch == lastChar) && (i != 0)) {
                continue;
            }
        }
        buffer.append(ch);
        lastChar = ch;
    }
    return buffer.toString();
}
项目:lams    文件:CharRange.java   
/**
 * <p>Gets a string representation of the character range.</p>
 * 
 * @return string representation of this range
 */
public String toString() {
    if (iToString == null) {
        StrBuilder buf = new StrBuilder(4);
        if (isNegated()) {
            buf.append('^');
        }
        buf.append(start);
        if (start != end) {
            buf.append('-');
            buf.append(end);
        }
        iToString = buf.toString();
    }
    return iToString;
}
项目:lams    文件:ClassUtils.java   
/**
 * Converts a class name to a JLS style class name.
 *
 * @param className  the class name
 * @return the converted name
 */
private static String toCanonicalName(String className) {
    className = StringUtils.deleteWhitespace(className);
    if (className == null) {
        throw new NullArgumentException("className");
    } else if (className.endsWith("[]")) {
        StrBuilder classNameBuffer = new StrBuilder();
        while (className.endsWith("[]")) {
            className = className.substring(0, className.length() - 2);
            classNameBuffer.append("[");
        }
        String abbreviation = (String) abbreviationMap.get(className);
        if (abbreviation != null) {
            classNameBuffer.append(abbreviation);
        } else {
            classNameBuffer.append("L").append(className).append(";");
        }
        className = classNameBuffer.toString();
    }
    return className;
}
项目:cuba    文件:Param.java   
protected void setValue(Object value, boolean updateEditComponent) {
    if (!Objects.equals(value, this.value)) {
        Object prevValue = this.value;
        this.value = value;
        for (ParamValueChangeListener listener : new ArrayList<>(listeners)) {
            listener.valueChanged(prevValue, value);
        }
        if (updateEditComponent && this.editComponent instanceof Component.HasValue) {
            if (value instanceof Collection && editComponent instanceof TextField) {
                //if the value type is an array and the editComponent is a textField ('IN' condition for String attribute)
                //then we should set the string value (not the array) to the text field
                String caption = new StrBuilder().appendWithSeparators((Collection) value, ",").toString();
                ((TextField) editComponent).setValue(caption);
            } else {
                ((Component.HasValue) editComponent).setValue(value);
            }
        }
    }
}
项目:FinanceAnalytics    文件:PriorityResolvingCombiningLiveDataServerComponentFactory.java   
@Override
protected LiveDataMetaData createMetaData(ComponentRepository repo) {
  List<ComponentInfo> infos = buildInfoList();
  Set<ExternalScheme> schemes = Sets.newLinkedHashSet();
  StrBuilder buf = new StrBuilder();
  for (ComponentInfo info : infos) {
    ComponentInfo infoProvider = repo.findInfo(LiveDataMetaDataProvider.class, info.getClassifier());
    if (infoProvider == null) {
      throw new OpenGammaRuntimeException("Unable to find matching LiveDataMetaDataProvider: " + info);
    }
    LiveDataMetaDataProvider provider = (LiveDataMetaDataProvider) repo.getInstance(infoProvider);
    LiveDataMetaData metaData = provider.metaData();
    schemes.addAll(metaData.getSupportedSchemes());
    buf.appendSeparator(", ").append(metaData.getDescription());
  }
  return new LiveDataMetaData(ImmutableList.copyOf(schemes), LiveDataServerTypes.STANDARD, buf.toString());
}
项目:FinanceAnalytics    文件:AbstractExceptionMapper.java   
private String errorLocator(Throwable exception) {
  String base = exception.getClass().getSimpleName();
  if (exception.getStackTrace().length == 0) {
    return base;
  }
  StrBuilder buf = new StrBuilder(512);
  buf.append(base).append("<br />");
  int count = 0;
  for (int i = 0; i < exception.getStackTrace().length && count < 4; i++) {
    StackTraceElement ste = exception.getStackTrace()[i];
    if (ste.getClassName().startsWith("sun.") || ste.getClassName().startsWith("javax.") || ste.getClassName().startsWith("com.sun.") ||
        (ste.getClassName().equals("java.lang.reflect.Method") && ste.getMethodName().equals("invoke"))) {
      continue;
    }
    if (ste.getLineNumber() >= 0) {
      buf.append(String.format("&nbsp;&nbsp;at %s.%s() L%d<br />", ste.getClassName(), ste.getMethodName(), ste.getLineNumber()));
    } else {
      buf.append(String.format("&nbsp;&nbsp;at %s.%s()<br />", ste.getClassName(), ste.getMethodName()));
    }
    count++;
  }
  return buf.toString();
}
项目:FinanceAnalytics    文件:FailureResult.java   
/**
 * Obtains a failure result for a non-empty list of failures.
 * 
 * @param failures  the failures, not empty, not null
 * @return the failure result, not null
 */
static <U> Result<U> of(List<Failure> failures) {
  ArgumentChecker.notEmpty(failures, "failures");
  ImmutableSet<Failure> fails = ImmutableSet.copyOf(failures);
  FailureStatus status = fails.iterator().next().getStatus();
  StrBuilder buf = new StrBuilder();
  for (Failure failure : fails) {
    buf.appendSeparator(", ");
    buf.append(failure.getMessage());
    if (!status.equals(failure.getStatus())) {
      status = FailureStatus.MULTIPLE;
    }
  }
  Result<?> result = new FailureResult<>(fails, status, buf.toString());
  return Result.failure(result);
}
项目:FinanceAnalytics    文件:SimplePortfolioNode.java   
/**
 * Gets a full-detail string containing all child nodes and positions.
 * 
 * @return the full-detail string, not null
 */
public String toLongString() {
  StrBuilder childBuf = new StrBuilder(1024);
  childBuf.append("[");
  for (int i = 0; i < getChildNodes().size(); i++) {
    PortfolioNode child = getChildNodes().get(i);
    if (child instanceof SimplePortfolioNode) {
      childBuf.append(((SimplePortfolioNode) child).toLongString());
    } else {
      childBuf.append(child.toString());
    }
    if (i != getChildNodes().size() - 1) {
      childBuf.append(",");
    }
  }
  childBuf.append("]");
  return new StrBuilder(childBuf.size() + 128)
      .append("PortfolioNode[uniqueId=")
      .append(getUniqueId())
      .append(",childNodes=")
      .append(childBuf)
      .append(",positions=")
      .append(getPositions()).append("]")
      .toString();
}
项目:FinanceAnalytics    文件:SimpleTrade.java   
@Override
public String toString() {
  return new StrBuilder(256)
      .append("Trade[")
      .append(getUniqueId())
      .append(", ")
      .append(getQuantity())
      .append(' ')
      .append(LinkUtils.best(getSecurityLink()))
      .append(", ")
      .append(getCounterparty())
      .append(", ")
      .append(getTradeDate())
      .append(" ")
      .append(getTradeTime())
      .append(']')
      .toString();
}
项目:GoogleCharts    文件:SqlDataSourceHelper.java   
/**
 * Appends the ORDER BY clause of the sql query to the given string builder.
 *
 * @param query The query.
 * @param queryStringBuilder The string builder holding the string query.
 */
static void appendOrderByClause(Query query, StrBuilder queryStringBuilder) {
  if (!query.hasSort()) {
    return;
  }
  queryStringBuilder.append("ORDER BY ");
  QuerySort querySort = query.getSort();
  List<ColumnSort> sortColumns = querySort.getSortColumns();
  int numOfSortColumns = sortColumns.size();
  for (int col = 0; col < numOfSortColumns; col++) {
    ColumnSort columnSort = sortColumns.get(col);
    queryStringBuilder.append(getColumnId(columnSort.getColumn()));
    if (columnSort.getOrder() == SortOrder.DESCENDING) {
      queryStringBuilder.append(" DESC");
    }
    if (col < numOfSortColumns - 1) {
      queryStringBuilder.append(", ");
    }
  }
  queryStringBuilder.append(" ");
}
项目:GoogleCharts    文件:SqlDataSourceHelper.java   
/**
 * Appends the SELECT clause of the sql query to the given string builder.
 *
 * @param query The query.
 * @param queryStringBuilder The string builder holding the string query.
 */

static void appendSelectClause(Query query,
    StrBuilder queryStringBuilder) {
  queryStringBuilder.append("SELECT ");

  // If it's a selectAll query, build "select *" clause.
  if (!query.hasSelection()) {
    queryStringBuilder.append("* ");
    return;
  }

  List<AbstractColumn> columns = query.getSelection().getColumns();
  int numOfColsInQuery = columns.size();

  // Add the Ids of the columns to the select clause
  for (int col = 0; col < numOfColsInQuery; col++) {
    queryStringBuilder.append(getColumnId(columns.get(col)));
    if (col < numOfColsInQuery - 1) {
      queryStringBuilder.append(", ");
    }
  }
  queryStringBuilder.append(" ");
}
项目:GoogleCharts    文件:SqlDataSourceHelper.java   
/**
 * Returns the column id in SQL.
 *
 * @param abstractColumn The column.
 *
 * @return The column id for the data table.
 */
private static StrBuilder getColumnId(AbstractColumn abstractColumn) {
  StrBuilder columnId = new StrBuilder();

  // For simple column the id is simply the column id.
  if (abstractColumn instanceof SimpleColumn) {
    columnId.append("`").append(abstractColumn.getId()).append("`");
  } else {
    // For aggregation column build the id from the aggregation type and the
    // column id (e.g. for aggregation type 'min' and column id 'salary', the
    // sql column id will be: min(`salary`);
    AggregationColumn aggregationColumn = (AggregationColumn) abstractColumn;
    columnId.append(getAggregationFunction(
        aggregationColumn.getAggregationType())).append("(`").
        append(aggregationColumn.getAggregatedColumn()).append("`)");
  }
  return columnId;
}
项目:OLE-INST    文件:CreditMemoServiceImpl.java   
/**
 * Since PaymentRequest does not have the app doc status, perform an additional lookup
 * through doc search by using list of PaymentRequest Doc numbers.  Query appDocStatus
 * from workflow document and filter against the provided status
 * <p/>
 * DocumentSearch allows for multiple docNumber lookup by docId|docId|docId conversion
 *
 * @param lookupDocNumbers
 * @param appDocStatus
 * @return
 */
private List<String> filterCreditMemoByAppDocStatus(List<String> lookupDocNumbers, String... appDocStatus) {
    boolean valid = false;

    final String DOC_NUM_DELIM = "|";
    StrBuilder routerHeaderIdBuilder = new StrBuilder().appendWithSeparators(lookupDocNumbers, DOC_NUM_DELIM);

    List<String> creditMemoDocNumbers = new ArrayList<String>();

    DocumentSearchCriteria.Builder documentSearchCriteriaDTO = DocumentSearchCriteria.Builder.create();
    documentSearchCriteriaDTO.setDocumentId(routerHeaderIdBuilder.toString());
    documentSearchCriteriaDTO.setDocumentTypeName(PurapConstants.PurapDocTypeCodes.CREDIT_MEMO_DOCUMENT);

    DocumentSearchResults creditMemoDocumentsList = KewApiServiceLocator.getWorkflowDocumentService().documentSearch(
            GlobalVariables.getUserSession().getPrincipalId(), documentSearchCriteriaDTO.build());

    for (DocumentSearchResult creditMemoDocument : creditMemoDocumentsList.getSearchResults()) {
        ///use the appDocStatus from the KeyValueDTO result to look up custom status
        if (Arrays.asList(appDocStatus).contains(creditMemoDocument.getDocument().getApplicationDocumentStatus())) {
            //found the matching status, retrieve the routeHeaderId and add to the list
            creditMemoDocNumbers.add(creditMemoDocument.getDocument().getDocumentId());
        }
    }

    return creditMemoDocNumbers;
}
项目:OLE-INST    文件:PurchaseOrderServiceImpl.java   
/**
 * Since PaymentRequest does not have the app doc status, perform an additional lookup
 * through doc search by using list of PaymentRequest Doc numbers.  Query appDocStatus
 * from workflow document and filter against the provided status
 * <p/>
 * DocumentSearch allows for multiple docNumber lookup by docId|docId|docId conversion
 *
 * @param lookupDocNumbers
 * @param appDocStatus
 * @return List<String> purchaseOrderDocumentNumbers
 */
protected List<String> filterPurchaseOrderDocumentNumbersByAppDocStatus(List<String> lookupDocNumbers, String... appDocStatus) {
    boolean valid = false;

    final String DOC_NUM_DELIM = "|";
    StrBuilder routerHeaderIdBuilder = new StrBuilder().appendWithSeparators(lookupDocNumbers, DOC_NUM_DELIM);

    List<String> purchaseOrderDocNumbers = new ArrayList<String>();

    DocumentSearchCriteria.Builder documentSearchCriteriaDTO = DocumentSearchCriteria.Builder.create();
    documentSearchCriteriaDTO.setDocumentId(routerHeaderIdBuilder.toString());
    documentSearchCriteriaDTO.setDocumentTypeName(PurapConstants.PurapDocTypeCodes.PO_DOCUMENT);

    DocumentSearchResults poDocumentsList = KewApiServiceLocator.getWorkflowDocumentService().documentSearch(
            GlobalVariables.getUserSession().getPrincipalId(), documentSearchCriteriaDTO.build());

    for (DocumentSearchResult poDocument : poDocumentsList.getSearchResults()) {
        ///use the appDocStatus from the KeyValueDTO result to look up custom status
        if (Arrays.asList(appDocStatus).contains(poDocument.getDocument().getApplicationDocumentStatus())) {
            //found the matching status, retrieve the routeHeaderId and add to the list
            purchaseOrderDocNumbers.add(poDocument.getDocument().getDocumentId());
        }
    }

    return purchaseOrderDocNumbers;
}
项目:perfload-perfmon    文件:PerfMonProc.java   
@Override
public String executeCommand(final SigarProxy sigar) throws SigarException {
    StrBuilder sb = new StrBuilder(200);

    ProcStat procStat = sigar.getProcStat();

    sb.append(TYPE_PROC);
    sb.append(separator);
    sb.append(procStat.getTotal());
    sb.append(separator);
    sb.append(procStat.getRunning());
    sb.append(separator);
    sb.append(procStat.getIdle());
    sb.append(separator);
    sb.append(procStat.getSleeping());
    sb.append(separator);
    sb.append(procStat.getStopped());
    sb.append(separator);
    sb.append(procStat.getZombie());
    sb.append(separator);
    sb.append(procStat.getThreads());

    return sb.toString();
}
项目:perfload-perfmon    文件:PerfMonCpu.java   
@Override
public String executeCommand(final SigarProxy sigar) throws SigarException {
    StrBuilder sb = new StrBuilder(200);

    CpuPerc[] cpus = sigar.getCpuPercList();
    CpuPerc cpuAll = sigar.getCpuPerc();

    sb.append(TYPE_CPU_X);
    sb.append(separator);
    writeCpu(sb, cpuAll);

    if (cpus.length > 1) { // more than one CPU
        appendLineBreak(sb);
        for (int i = 0; i < cpus.length; i++) {
            appendLineBreak(sb, i);
            sb.append(TYPE_CPU + i);
            sb.append(separator);
            writeCpu(sb, cpus[i]);
        }
    }

    return sb.toString();
}
项目:perfload-perfmon    文件:PerfMonSwap.java   
@Override
public String executeCommand(final SigarProxy sigar) throws SigarException {
    StrBuilder sb = new StrBuilder(200);

    Swap swap = sigar.getSwap();

    sb.append(TYPE_SWAP);
    sb.append(separator);
    sb.append(swap.getTotal() / 1024L);
    sb.append(separator);
    sb.append(swap.getUsed() / 1024L);
    sb.append(separator);
    sb.append(swap.getFree() / 1024L);

    return sb.toString();
}
项目:perfload-perfmon    文件:PerfMonJava.java   
@Override
public String executeCommand(final SigarProxy sigar) throws SigarException {
    StrBuilder sb = new StrBuilder(200);

    String[] type = new String[] { "State.Name.sw=java" };
    long[] pids = Shell.getPids(sigar, type);

    for (int i = 0; i < pids.length; i++) {
        appendLineBreak(sb, i);

        sb.append(TYPE_JAVA_X + i);
        sb.append(separator);
        long pid = pids[i];

        String cpuPerc = "?";
        @SuppressWarnings("unchecked")
        List<Object> info = new ArrayList<Object>(Ps.getInfo(sigar, pid));
        ProcCpu cpu = sigar.getProcCpu(pid);
        cpuPerc = CpuPerc.format(cpu.getPercent());
        info.add(info.size() - 1, cpuPerc);
        sb.append(Ps.join(info));
    }

    return sb.toString();
}
项目:perfload-perfmon    文件:PerfMonMem.java   
@Override
public String executeCommand(final SigarProxy sigar) throws SigarException {
    StrBuilder sb = new StrBuilder(200);

    Mem mem = sigar.getMem();

    sb.append(TYPE_MEM);
    sb.append(separator);
    sb.append(mem.getTotal() / 1024L);
    sb.append(separator);
    sb.append(mem.getUsed() / 1024L);
    sb.append(separator);
    sb.append(mem.getFree() / 1024L);
    sb.append(separator);
    sb.append(mem.getActualUsed() / 1024L);
    sb.append(separator);
    sb.append(mem.getActualFree() / 1024L);

    return sb.toString();
}
项目:celos    文件:RecursiveFsObjectComparer.java   
private FixObjectCompareResult checkDirFileList(Map<String, FixFsObject> expectedChldrn, Map<String, FixFsObject> actualChldrn) {
    Set<String> expectedDiff = Sets.difference(expectedChldrn.keySet(), actualChldrn.keySet());
    Set<String> actualDiff = Sets.difference(actualChldrn.keySet(), expectedChldrn.keySet());

    List<String> filesWithDifferentTypes = Lists.newArrayList();
    for (String key : Sets.intersection(expectedChldrn.keySet(), actualChldrn.keySet())) {
        FixFsObject expected = expectedChldrn.get(key);
        FixFsObject actual = actualChldrn.get(key);
        if (expected.isFile() != actual.isFile()) {
            String message = getWrongTypeDesc(key, expected, actual);
            filesWithDifferentTypes.add(message);
        }
    }

    if (expectedDiff.isEmpty() && actualDiff.isEmpty() && filesWithDifferentTypes.isEmpty()) {
        return FixObjectCompareResult.SUCCESS;
    } else {
        StrBuilder strBuilder = new StrBuilder();
        appendMessages(expectedDiff, strBuilder, "Files found only in expected set: ");
        appendMessages(actualDiff, strBuilder, "Files found only in result set: ");
        appendMessages(filesWithDifferentTypes, strBuilder, "Files have different types: ");
        return FixObjectCompareResult.failed(strBuilder.toString());
    }
}
项目:SuperSkyBros    文件:MessageUtil.java   
public static String fullline(final ChatColor color, final ChatColor color2, final ChatColor style, char character, String mess) {
    StrBuilder sb = new StrBuilder();
    boolean t = true;
    int l = 0;
    if ((54 - mess.length()) % 2 == 0)
        l = 54 / mess.length();

    for (int i = 0; i < l + 1; i++) {
        sb.append(style);
        if (t) {
            sb.append(color);
            t = false;
        } else {
            sb.append(color2);
            t = true;
        }
        sb.append(character);
    }
    return sb.toString() + " " + mess + " " + sb.toString();


}
项目:Reer    文件:ClassFileExtractionManager.java   
private boolean extractClassFile(final String className) {
    boolean classFileExtracted = false;

    final File extractedClassFile = tempFile();
    final String classFileName = new StrBuilder().append(className).append(".class").toString();
    final String classNamePackage = classNamePackage(className);
    final Set<File> packageJarFiles = packageJarFilesMappings.get(classNamePackage);

    File classFileSourceJar = null;

    if (packageJarFiles != null && !packageJarFiles.isEmpty()) {
        final Iterator<File> packageJarFilesIt = packageJarFiles.iterator();

        while (!classFileExtracted && packageJarFilesIt.hasNext()) {
            final File jarFile = packageJarFilesIt.next();

            try {
                classFileExtracted = JarUtil.extractZipEntry(jarFile, classFileName, extractedClassFile);

                if (classFileExtracted) {
                    classFileSourceJar = jarFile;
                }
            } catch (IOException e) {
                throw new GradleException("failed to extract class file from jar (" + jarFile + ")", e);
            }
        }

        if (classFileExtracted) {
            LOGGER.debug("extracted class {} from {}", className, classFileSourceJar.getName());

            extractedJarClasses.put(className, extractedClassFile);
        }
    } // super class not on the classpath - unable to scan parent class

    return classFileExtracted;
}
项目:Open-DM    文件:ArcJobMgr.java   
private String createJobListing() throws DatabaseException {
    StrBuilder sb = new StrBuilder();
    List<ManagedJobSummary> jobsList = ArcMoverFactory.getInstance().getAllManagedJobs();

    Map<String, Integer> columnWidths = calcColumnWidths(jobsList);

    for (Map.Entry<String, Integer> entry : columnWidths.entrySet()) {
        sb.appendFixedWidthPadRight(entry.getKey(), entry.getValue(), ' ').append(COL_SEP);
    }
    sb.append(NEWLINE);

    for (ManagedJobSummary job : jobsList) {
        sb.appendFixedWidthPadRight(getValue(job, JOB_NAME_LABEL),
                                    columnWidths.get(JOB_NAME_LABEL), ' ')
                .append(COL_SEP);
        sb.appendFixedWidthPadRight(getValue(job, JOB_TYPE_LABEL),
                                    columnWidths.get(JOB_TYPE_LABEL), ' ')
                .append(COL_SEP);
        sb.appendFixedWidthPadRight(getValue(job, JOB_STATE_LABEL),
                                    columnWidths.get(JOB_STATE_LABEL), ' ')
                .append(COL_SEP);

        sb.append(NEWLINE);
    }

    return sb.toString();

}
项目:Open-DM    文件:FileHandler.java   
protected static String buildPattern(String pattern) {
    String retval;
    if (pattern == null) {
        return null;
    }

    StrBuilder newPattern = new StrBuilder(pattern);
    String applicationHomeDir = System.getProperty("application_home_dir");
    String userHomeDir = System.getProperty("user.home");
    String tmpDir = System.getProperty("java.io.tmpdir");
    if (tmpDir == null) {
        tmpDir = userHomeDir;
    }

    if (applicationHomeDir != null) {
        newPattern = newPattern.replaceAll("%a", applicationHomeDir);
    }
    retval = newPattern.toString();

    // ensure that the log directory exists
    // Replace the known variables that are common in directories so we can create the dir.
    newPattern = newPattern.replaceAll("%t", tmpDir);
    newPattern = newPattern.replaceAll("%h", userHomeDir);

    String logPath = FileUtil.getPath(newPattern.toString());
    FileUtil.mkdirs(logPath);
    return retval;
}
项目:lams    文件:IntRange.java   
/**
 * <p>Gets the range as a <code>String</code>.</p>
 *
 * <p>The format of the String is 'Range[<i>min</i>,<i>max</i>]'.</p>
 *
 * @return the <code>String</code> representation of this range
 */
public String toString() {
    if (toString == null) {
        StrBuilder buf = new StrBuilder(32);
        buf.append("Range[");
        buf.append(min);
        buf.append(',');
        buf.append(max);
        buf.append(']');
        toString = buf.toString();
    }
    return toString;
}
项目:lams    文件:NumberRange.java   
/**
 * <p>Gets the range as a <code>String</code>.</p>
 *
 * <p>The format of the String is 'Range[<i>min</i>,<i>max</i>]'.</p>
 *
 * @return the <code>String</code> representation of this range
 */
public String toString() {
    if (toString == null) {
        StrBuilder buf = new StrBuilder(32);
        buf.append("Range[");
        buf.append(min);
        buf.append(',');
        buf.append(max);
        buf.append(']');
        toString = buf.toString();
    }
    return toString;
}
项目:lams    文件:LongRange.java   
/**
 * <p>Gets the range as a <code>String</code>.</p>
 *
 * <p>The format of the String is 'Range[<i>min</i>,<i>max</i>]'.</p>
 *
 * @return the <code>String</code> representation of this range
 */
public String toString() {
    if (toString == null) {
        StrBuilder buf = new StrBuilder(32);
        buf.append("Range[");
        buf.append(min);
        buf.append(',');
        buf.append(max);
        buf.append(']');
        toString = buf.toString();
    }
    return toString;
}
项目:lams    文件:Fraction.java   
/**
 * <p>Gets the fraction as a <code>String</code>.</p>
 *
 * <p>The format used is '<i>numerator</i>/<i>denominator</i>' always.
 *
 * @return a <code>String</code> form of the fraction
 */
public String toString() {
    if (toString == null) {
        toString = new StrBuilder(32)
            .append(getNumerator())
            .append('/')
            .append(getDenominator()).toString();
    }
    return toString;
}
项目:lams    文件:Fraction.java   
/**
 * <p>Gets the fraction as a proper <code>String</code> in the format X Y/Z.</p>
 *
 * <p>The format used in '<i>wholeNumber</i> <i>numerator</i>/<i>denominator</i>'.
 * If the whole number is zero it will be ommitted. If the numerator is zero,
 * only the whole number is returned.</p>
 *
 * @return a <code>String</code> form of the fraction
 */
public String toProperString() {
    if (toProperString == null) {
        if (numerator == 0) {
            toProperString = "0";
        } else if (numerator == denominator) {
            toProperString = "1";
        } else if (numerator == -1 * denominator) {
            toProperString = "-1";
        } else if ((numerator>0?-numerator:numerator) < -denominator) {
            // note that we do the magnitude comparison test above with
            // NEGATIVE (not positive) numbers, since negative numbers
            // have a larger range.  otherwise numerator==Integer.MIN_VALUE
            // is handled incorrectly.
            int properNumerator = getProperNumerator();
            if (properNumerator == 0) {
                toProperString = Integer.toString(getProperWhole());
            } else {
                toProperString = new StrBuilder(32)
                    .append(getProperWhole()).append(' ')
                    .append(properNumerator).append('/')
                    .append(getDenominator()).toString();
            }
        } else {
            toProperString = new StrBuilder(32)
                .append(getNumerator()).append('/')
                .append(getDenominator()).toString();
        }
    }
    return toProperString;
}
项目:lams    文件:DoubleRange.java   
/**
 * <p>Gets the range as a <code>String</code>.</p>
 *
 * <p>The format of the String is 'Range[<i>min</i>,<i>max</i>]'.</p>
 *
 * @return the <code>String</code> representation of this range
 */
public String toString() {
    if (toString == null) {
        StrBuilder buf = new StrBuilder(32);
        buf.append("Range[");
        buf.append(min);
        buf.append(',');
        buf.append(max);
        buf.append(']');
        toString = buf.toString();
    }
    return toString;
}
项目:lams    文件:CharSetUtils.java   
/**
 * Implementation of delete and keep
 *
 * @param str String to modify characters within
 * @param set String[] set of characters to modify
 * @param expect whether to evaluate on match, or non-match
 * @return modified String
 */
private static String modify(String str, String[] set, boolean expect) {
    CharSet chars = CharSet.getInstance(set);
    StrBuilder buffer = new StrBuilder(str.length());
    char[] chrs = str.toCharArray();
    int sz = chrs.length;
    for(int i=0; i<sz; i++) {
        if(chars.contains(chrs[i]) == expect) {
            buffer.append(chrs[i]);
        }
    }
    return buffer.toString();
}
项目:lams    文件:ClassUtils.java   
/**
 * <p>Gets the class name minus the package name from a String.</p>
 *
 * <p>The string passed in is assumed to be a class name - it is not checked.</p>
 *
 * @param className  the className to get the short name for
 * @return the class name of the class without the package name or an empty string
 */
public static String getShortClassName(String className) {
    if (className == null) {
        return StringUtils.EMPTY;
    }
    if (className.length() == 0) {
        return StringUtils.EMPTY;
    }

    StrBuilder arrayPrefix = new StrBuilder();

    // Handle array encoding
    if (className.startsWith("[")) {
        while (className.charAt(0) == '[') {
            className = className.substring(1);
            arrayPrefix.append("[]");
        }
        // Strip Object type encoding
        if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
            className = className.substring(1, className.length() - 1);
        }
    }

    if (reverseAbbreviationMap.containsKey(className)) {
        className = (String)reverseAbbreviationMap.get(className);
    }

    int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
    int innerIdx = className.indexOf(
            INNER_CLASS_SEPARATOR_CHAR, lastDotIdx == -1 ? 0 : lastDotIdx + 1);
    String out = className.substring(lastDotIdx + 1);
    if (innerIdx != -1) {
        out = out.replace(INNER_CLASS_SEPARATOR_CHAR, PACKAGE_SEPARATOR_CHAR);
    }
    return out + arrayPrefix;
}
项目:lams    文件:ClassUtils.java   
/**
 * <p>Converts a given name of class into canonical format.
 * If name of class is not a name of array class it returns
 * unchanged name.</p>
 * <p>Example:
 * <ul>
 * <li><code>getCanonicalName("[I") = "int[]"</code></li>
 * <li><code>getCanonicalName("[Ljava.lang.String;") = "java.lang.String[]"</code></li>
 * <li><code>getCanonicalName("java.lang.String") = "java.lang.String"</code></li>
 * </ul>
 * </p>
 *
 * @param className the name of class
 * @return canonical form of class name
 * @since 2.4
 */
private static String getCanonicalName(String className) {
    className = StringUtils.deleteWhitespace(className);
    if (className == null) {
        return null;
    } else {
        int dim = 0;
        while (className.startsWith("[")) {
            dim++;
            className = className.substring(1);
        }
        if (dim < 1) {
            return className;
        } else {
            if (className.startsWith("L")) {
                className = className.substring(
                    1,
                    className.endsWith(";")
                        ? className.length() - 1
                        : className.length());
            } else {
                if (className.length() > 0) {
                    className = (String) reverseAbbreviationMap.get(
                        className.substring(0, 1));
                }
            }
            StrBuilder canonicalClassNameBuffer = new StrBuilder(className);
            for (int i = 0; i < dim; i++) {
                canonicalClassNameBuffer.append("[]");
            }
            return canonicalClassNameBuffer.toString();
        }
    }
}
项目:lams    文件:StringUtils.java   
/**
 * <p>Joins the elements of the provided array into a single String
 * containing the provided list of elements.</p>
 *
 * <p>No delimiter is added before or after the list.
 * A <code>null</code> separator is the same as an empty String ("").
 * Null objects or empty strings within the array are represented by
 * empty strings.</p>
 *
 * <pre>
 * StringUtils.join(null, *)                = null
 * StringUtils.join([], *)                  = ""
 * StringUtils.join([null], *)              = ""
 * StringUtils.join(["a", "b", "c"], "--")  = "a--b--c"
 * StringUtils.join(["a", "b", "c"], null)  = "abc"
 * StringUtils.join(["a", "b", "c"], "")    = "abc"
 * StringUtils.join([null, "", "a"], ',')   = ",,a"
 * </pre>
 *
 * @param array  the array of values to join together, may be null
 * @param separator  the separator character to use, null treated as ""
 * @param startIndex the first index to start joining from.  It is
 * an error to pass in an end index past the end of the array
 * @param endIndex the index to stop joining from (exclusive). It is
 * an error to pass in an end index past the end of the array
 * @return the joined String, <code>null</code> if null array input
 */
public static String join(Object[] array, String separator, int startIndex, int endIndex) {
    if (array == null) {
        return null;
    }
    if (separator == null) {
        separator = EMPTY;
    }

    // endIndex - startIndex > 0:   Len = NofStrings *(len(firstString) + len(separator))
    //           (Assuming that all Strings are roughly equally long)
    int bufSize = (endIndex - startIndex);
    if (bufSize <= 0) {
        return EMPTY;
    }

    bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length())
                    + separator.length());

    StrBuilder buf = new StrBuilder(bufSize);

    for (int i = startIndex; i < endIndex; i++) {
        if (i > startIndex) {
            buf.append(separator);
        }
        if (array[i] != null) {
            buf.append(array[i]);
        }
    }
    return buf.toString();
}
项目:lams    文件:StringUtils.java   
/**
 * <p>Joins the elements of the provided <code>Iterator</code> into
 * a single String containing the provided elements.</p>
 *
 * <p>No delimiter is added before or after the list. Null objects or empty
 * strings within the iteration are represented by empty strings.</p>
 *
 * <p>See the examples here: {@link #join(Object[],char)}. </p>
 *
 * @param iterator  the <code>Iterator</code> of values to join together, may be null
 * @param separator  the separator character to use
 * @return the joined String, <code>null</code> if null iterator input
 * @since 2.0
 */
public static String join(Iterator iterator, char separator) {

    // handle null, zero and one elements before building a buffer
    if (iterator == null) {
        return null;
    }
    if (!iterator.hasNext()) {
        return EMPTY;
    }
    Object first = iterator.next();
    if (!iterator.hasNext()) {
        return ObjectUtils.toString(first);
    }

    // two or more elements
    StrBuilder buf = new StrBuilder(256); // Java default is 16, probably too small
    if (first != null) {
        buf.append(first);
    }

    while (iterator.hasNext()) {
        buf.append(separator);
        Object obj = iterator.next();
        if (obj != null) {
            buf.append(obj);
        }
    }

    return buf.toString();
}
项目:lams    文件:StringUtils.java   
/**
 * <p>Joins the elements of the provided <code>Iterator</code> into
 * a single String containing the provided elements.</p>
 *
 * <p>No delimiter is added before or after the list.
 * A <code>null</code> separator is the same as an empty String ("").</p>
 *
 * <p>See the examples here: {@link #join(Object[],String)}. </p>
 *
 * @param iterator  the <code>Iterator</code> of values to join together, may be null
 * @param separator  the separator character to use, null treated as ""
 * @return the joined String, <code>null</code> if null iterator input
 */
public static String join(Iterator iterator, String separator) {

    // handle null, zero and one elements before building a buffer
    if (iterator == null) {
        return null;
    }
    if (!iterator.hasNext()) {
        return EMPTY;
    }
    Object first = iterator.next();
    if (!iterator.hasNext()) {
        return ObjectUtils.toString(first);
    }

    // two or more elements
    StrBuilder buf = new StrBuilder(256); // Java default is 16, probably too small
    if (first != null) {
        buf.append(first);
    }

    while (iterator.hasNext()) {
        if (separator != null) {
            buf.append(separator);
        }
        Object obj = iterator.next();
        if (obj != null) {
            buf.append(obj);
        }
    }
    return buf.toString();
}