org.apache.commons.lang.text.StrBuilder Java Examples

The following examples show how to use org.apache.commons.lang.text.StrBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CharRange.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <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;
}
 
Example #2
Source File: ClassUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #3
Source File: RecursiveFsObjectComparer.java    From celos with Apache License 2.0 6 votes vote down vote up
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());
    }
}
 
Example #4
Source File: CharSetUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <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();
}
 
Example #5
Source File: NumberRange.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <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();
}
 
Example #6
Source File: ClassFileExtractionManager.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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;
}
 
Example #7
Source File: Const.java    From hop with Apache License 2.0 5 votes vote down vote up
private static String removeEnclosure( String stringToSplit, String enclosure ) {
  int firstIndex = stringToSplit.indexOf( enclosure );
  int lastIndex = stringToSplit.lastIndexOf( enclosure );
  if ( firstIndex == lastIndex ) {
    return stringToSplit;
  }
  StrBuilder strBuilder = new StrBuilder( stringToSplit );
  strBuilder.replace( firstIndex, enclosure.length() + firstIndex, "" );
  strBuilder.replace( lastIndex - enclosure.length(), lastIndex, "" );

  return strBuilder.toString();
}
 
Example #8
Source File: ClassUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <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();
        }
    }
}
 
Example #9
Source File: MessageEventProcessor.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getHelp() {
    StrBuilder builder = new StrBuilder();
    builder.appendln("Available commands:");
    for (String cmd : processors.keySet()) {
        builder.append("\t").appendln(cmd);
    }
    return builder.toString();
}
 
Example #10
Source File: LookupCommandProcessor.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void process(Mxisd m, _MatrixClient client, _MatrixRoom room, CommandLine cmdLine) {
    if (cmdLine.getArgList().size() != 3) {
        room.sendNotice(getUsage());
        return;
    }

    String medium = cmdLine.getArgList().get(1);
    String address = cmdLine.getArgList().get(2);
    if (StringUtils.isAnyBlank(medium, address)) {
        room.sendNotice(getUsage());
        return;
    }

    room.sendNotice("Processing...");
    Optional<SingleLookupReply> r = m.getIdentity().find(medium, address, true);
    if (!r.isPresent()) {
        room.sendNotice("No result");
        return;
    }

    SingleLookupReply lookup = r.get();
    StrBuilder b = new StrBuilder();
    b.append("Result for 3PID lookup of ").append(medium).append(" ").appendln(address).appendNewLine();
    b.append("Matrix ID: ").appendln(lookup.getMxid().getId());
    b.appendln("Validity:")
            .append("  Not Before: ").appendln(lookup.getNotBefore())
            .append("  Not After: ").appendln(lookup.getNotAfter());
    b.appendln("Signatures:");
    lookup.getSignatures().forEach((host, signs) -> {
        b.append("  ").append(host).appendln(":");
        signs.forEach((key, sign) -> b.append("    ").append(key).append(" -> ").appendln("OK"));
    });

    room.sendNotice(b.toString());
}
 
Example #11
Source File: ClassUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <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;
}
 
Example #12
Source File: ClassFileExtractionManager.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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;
}
 
Example #13
Source File: PushDownUtil.java    From kylin with Apache License 2.0 5 votes vote down vote up
static String schemaCompletion(String inputSql, String schema) throws SqlParseException {
    if (inputSql == null || inputSql.equals("")) {
        return "";
    }
    SqlNode node = CalciteParser.parse(inputSql);

    // get all table node that don't have schema by visitor pattern
    PushDownUtil.FromTablesVisitor ftv = new PushDownUtil.FromTablesVisitor();
    node.accept(ftv);
    List<SqlNode> tablesWithoutSchema = ftv.getTablesWithoutSchema();
    // sql do not need completion
    if (tablesWithoutSchema.isEmpty()) {
        return inputSql;
    }

    List<Pair<Integer, Integer>> tablesPos = new ArrayList<>();
    for (SqlNode tables : tablesWithoutSchema) {
        tablesPos.add(CalciteParser.getReplacePos(tables, inputSql));
    }

    // make the behind position in the front of the list, so that the front position
    // will not be affected when replaced
    Collections.sort(tablesPos, new Comparator<Pair<Integer, Integer>>() {
        @Override
        public int compare(Pair<Integer, Integer> o1, Pair<Integer, Integer> o2) {
            int r = o2.getFirst() - o1.getFirst();
            return r == 0 ? o2.getSecond() - o1.getSecond() : r;
        }
    });

    StrBuilder afterConvert = new StrBuilder(inputSql);
    for (Pair<Integer, Integer> pos : tablesPos) {
        String tableWithSchema = schema + "." + inputSql.substring(pos.getFirst(), pos.getSecond());
        afterConvert.replace(pos.getFirst(), pos.getSecond(), tableWithSchema);
    }
    return afterConvert.toString();
}
 
Example #14
Source File: DataReportServiceImpl.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @see org.kuali.kfs.module.tem.batch.service.DataReportService#getMessageAsString(java.util.List)
 */
@Override
public String getMessageAsString(List<ErrorMessage> errorMessages){

    List<String> messageList = new ArrayList<String>();
    for (ErrorMessage error : errorMessages){
        messageList.add(MessageUtils.getErrorMessage(error));
    }
    StrBuilder builder = new StrBuilder();
    builder.appendWithSeparators(messageList, BusinessObjectReportHelper.LINE_BREAK);
   return  builder.toString();
}
 
Example #15
Source File: AgencyStagingDataMaintainable.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
protected String getMessageAsString(List<ErrorMessage> errorMessages){

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

        for (ErrorMessage error : errorMessages){
            messageList.add(MessageUtils.getErrorMessage(error));
        }

        StrBuilder builder = new StrBuilder();
        builder.appendWithSeparators(messageList, BusinessObjectReportHelper.LINE_BREAK);
        return  builder.toString();
    }
 
Example #16
Source File: RecursiveFsObjectComparer.java    From celos with Apache License 2.0 5 votes vote down vote up
private void appendMessages(Collection<String> messages, StrBuilder strBuilder, String header) {
    if (messages.size() == 0) {
        return;
    }
    if (!strBuilder.isEmpty()) {
        strBuilder.appendNewLine();
    }
    strBuilder.append(header);
    List<String> sortedMessages = Lists.newArrayList(messages);
    Collections.sort(sortedMessages);
    strBuilder.appendWithSeparators(sortedMessages, ", ");
}
 
Example #17
Source File: FixObjectCompareResult.java    From celos with Apache License 2.0 5 votes vote down vote up
public String generateDescription() throws IOException {
    StrBuilder strBuilder = new StrBuilder();
    PathToMessageProcessor pathToMessage = new PathToMessageProcessor();
    TreeObjectProcessor.process(this, pathToMessage);
    for (Map.Entry<Path, String> pathMessage : pathToMessage.messages.entrySet()) {
        String keyText = StringUtils.isEmpty(pathMessage.getKey().toString()) ? "" : pathMessage.getKey() + " : " ;
        strBuilder.appendln(keyText + pathMessage.getValue());
    }
    return strBuilder.toString();
}
 
Example #18
Source File: Const.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private static String removeEnclosure( String stringToSplit, String enclosure ) {

    int firstIndex = stringToSplit.indexOf( enclosure );
    int lastIndex = stringToSplit.lastIndexOf( enclosure );
    if ( firstIndex == lastIndex ) {
      return stringToSplit;
    }
    StrBuilder strBuilder = new StrBuilder( stringToSplit );
    strBuilder.replace( firstIndex, enclosure.length() + firstIndex, "" );
    strBuilder.replace( lastIndex - enclosure.length(), lastIndex, "" );

    return strBuilder.toString();
  }
 
Example #19
Source File: Fraction.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <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;
}
 
Example #20
Source File: PushDownUtil.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
static String schemaCompletion(String inputSql, String schema) throws SqlParseException {
    if (inputSql == null || inputSql.equals("")) {
        return "";
    }
    SqlNode node = CalciteParser.parse(inputSql);

    // get all table node that don't have schema by visitor pattern
    PushDownUtil.FromTablesVisitor ftv = new PushDownUtil.FromTablesVisitor();
    node.accept(ftv);
    List<SqlNode> tablesWithoutSchema = ftv.getTablesWithoutSchema();
    // sql do not need completion
    if (tablesWithoutSchema.isEmpty()) {
        return inputSql;
    }

    List<Pair<Integer, Integer>> tablesPos = new ArrayList<>();
    for (SqlNode tables : tablesWithoutSchema) {
        tablesPos.add(CalciteParser.getReplacePos(tables, inputSql));
    }

    // make the behind position in the front of the list, so that the front position
    // will not be affected when replaced
    Collections.sort(tablesPos, new Comparator<Pair<Integer, Integer>>() {
        @Override
        public int compare(Pair<Integer, Integer> o1, Pair<Integer, Integer> o2) {
            int r = o2.getFirst() - o1.getFirst();
            return r == 0 ? o2.getSecond() - o1.getSecond() : r;
        }
    });

    StrBuilder afterConvert = new StrBuilder(inputSql);
    for (Pair<Integer, Integer> pos : tablesPos) {
        String tableWithSchema = schema + "." + inputSql.substring(pos.getFirst(), pos.getSecond());
        afterConvert.replace(pos.getFirst(), pos.getSecond(), tableWithSchema);
    }
    return afterConvert.toString();
}
 
Example #21
Source File: ClassFileExtractionManager.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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;
}
 
Example #22
Source File: ClassFileExtractionManager.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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;
}
 
Example #23
Source File: IntRange.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <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;
}
 
Example #24
Source File: NumberRange.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <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;
}
 
Example #25
Source File: LongRange.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <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;
}
 
Example #26
Source File: Fraction.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <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;
}
 
Example #27
Source File: DoubleRange.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <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;
}
 
Example #28
Source File: CharSetUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #29
Source File: StringEscapeUtils.java    From ymate-platform-v2 with Apache License 2.0 4 votes vote down vote up
public static String unescapeJava(String str) {
    if (str == null) {
        return null;
    }
    int sz = str.length();
    StringBuilder out = new StringBuilder();
    StrBuilder unicode = new StrBuilder(4);
    boolean hadSlash = false;
    boolean inUnicode = false;
    for (int i = 0; i < sz; i++) {
        char ch = str.charAt(i);
        if (inUnicode) {
            unicode.append(ch);
            if (unicode.length() == 4) {
                try {
                    int value = Integer.parseInt(unicode.toString(), 16);
                    out.append((char) value);
                    unicode.setLength(0);
                    inUnicode = false;
                    hadSlash = false;
                } catch (NumberFormatException nfe) {
                    throw new NestableRuntimeException("Unable to parse unicode value: " + unicode, nfe);
                }
            }
            continue;
        }
        if (hadSlash) {
            hadSlash = false;
            switch (ch) {
                case '\\':
                    out.append('\\');
                    break;
                case '\'':
                    out.append('\'');
                    break;
                case '\"':
                    out.append('"');
                    break;
                case 'r':
                    out.append('\r');
                    break;
                case 'f':
                    out.append('\f');
                    break;
                case 't':
                    out.append('\t');
                    break;
                case 'n':
                    out.append('\n');
                    break;
                case 'b':
                    out.append('\b');
                    break;
                case 'u': {
                    inUnicode = true;
                    break;
                }
                default:
                    out.append(ch);
                    break;
            }
            continue;
        } else if (ch == '\\') {
            hadSlash = true;
            continue;
        }
        out.append(ch);
    }
    if (hadSlash) {
        out.append('\\');
    }
    return out.toString();
}
 
Example #30
Source File: FastDateFormat.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * <p>Performs the parsing of tokens.</p>
 * 
 * @param pattern  the pattern
 * @param indexRef  index references
 * @return parsed token
 */
protected String parseToken(String pattern, int[] indexRef) {
    StrBuilder buf = new StrBuilder();

    int i = indexRef[0];
    int length = pattern.length();

    char c = pattern.charAt(i);
    if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') {
        // Scan a run of the same character, which indicates a time
        // pattern.
        buf.append(c);

        while (i + 1 < length) {
            char peek = pattern.charAt(i + 1);
            if (peek == c) {
                buf.append(c);
                i++;
            } else {
                break;
            }
        }
    } else {
        // This will identify token as text.
        buf.append('\'');

        boolean inLiteral = false;

        for (; i < length; i++) {
            c = pattern.charAt(i);

            if (c == '\'') {
                if (i + 1 < length && pattern.charAt(i + 1) == '\'') {
                    // '' is treated as escaped '
                    i++;
                    buf.append(c);
                } else {
                    inLiteral = !inLiteral;
                }
            } else if (!inLiteral &&
                     (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) {
                i--;
                break;
            } else {
                buf.append(c);
            }
        }
    }

    indexRef[0] = i;
    return buf.toString();
}