Example usage for java.text StringCharacterIterator StringCharacterIterator

List of usage examples for java.text StringCharacterIterator StringCharacterIterator

Introduction

In this page you can find the example usage for java.text StringCharacterIterator StringCharacterIterator.

Prototype

public StringCharacterIterator(String text) 

Source Link

Document

Constructs an iterator with an initial index of 0.

Usage

From source file:com.alfaariss.oa.util.web.RemoteAddrFilter.java

private static boolean matchWildcard(String s, String sMask) {
    //check empty string
    if (s.length() == 0) {
        if (sMask.length() == 0 || sMask.equals("*") || sMask.equals("?"))
            return true;
        return false;
    }//  ww  w  .  j av a2s . c  om

    char ch;
    int i = 0;
    StringCharacterIterator iter = new StringCharacterIterator(sMask);

    for (ch = iter.first(); ch != StringCharacterIterator.DONE && i < s.length(); ch = iter.next()) {
        if (ch == '?')
            i++;
        else if (ch == '*') {
            int j = iter.getIndex() + 1;
            if (j >= sMask.length())
                return true;
            String sSubFilter = sMask.substring(j);
            while (i < s.length()) {
                if (matchWildcard(s.substring(i), sSubFilter))
                    return true;
                i++;
            }
            return false;
        } else if (ch == s.charAt(i)) {
            i++;
        } else
            return false;
    }
    return (i == s.length());
}

From source file:info.magnolia.cms.taglibs.util.BaseImageTag.java

/**
 * Replace any special characters that are not letters or numbers with a replacement string. The two exceptions are
 * '-' and '_', which are allowed./*from ww  w.  jav a2  s.c  o m*/
 */
public String convertToSimpleString(String string) {

    final StringBuffer result = new StringBuffer();

    final StringCharacterIterator iterator = new StringCharacterIterator(string);
    char character = iterator.current();
    while (character != CharacterIterator.DONE) {
        int charType = Character.getType(character);
        if (charType == Character.SPACE_SEPARATOR) {
            result.append("-");
        } else if ((charType != Character.UPPERCASE_LETTER) && (charType != Character.LOWERCASE_LETTER)
                && (charType != Character.DECIMAL_DIGIT_NUMBER) && (charType != Character.CONNECTOR_PUNCTUATION)
                && (charType != Character.DASH_PUNCTUATION)) {
            result.append("u" + (int) character);

        } else {
            // the char is not a special one
            // add it to the result as is
            result.append(character);
        }
        character = iterator.next();
    }
    return result.toString();
}

From source file:org.mortbay.jetty.load.generator.jenkins.result.LoadResultProjectAction.java

public static List<RunInformations> searchRunInformations(String jettyVersion, ElasticHost elasticHost,
        int maxResult) throws IOException {

    String originalJettyVersion = jettyVersion;

    // jettyVersion 9.4.9*
    //in case jettyVersion is 9.4.9.v20180320 we need to replace with 9.4.9*
    if (StringUtils.contains(jettyVersion, 'v')) {
        jettyVersion = StringUtils.substringBeforeLast(jettyVersion, ".v");
    }/*from ww  w.ja  va  2  s . co m*/
    // FIXME investigate elastic but query such 9.4.10-SNAPSHOT doesn't work...
    // so using 9.4.10* then filter response back....
    if (StringUtils.contains(jettyVersion, "-SNAPSHOT")) {
        jettyVersion = StringUtils.substringBeforeLast(jettyVersion, "-SNAPSHOT");
    }

    // in case of 9.4.11-NO-LOGGER-SNAPSHOT still not working with elastic
    // here we must have only number or . so remove everything else

    StringBuilder versionQuery = new StringBuilder();
    CharacterIterator ci = new StringCharacterIterator(jettyVersion);
    for (char c = ci.first(); c != CharacterIterator.DONE; c = ci.next()) {
        if (NumberUtils.isCreatable(Character.toString(c)) || c == '.') {
            versionQuery.append(c);
        }
    }

    jettyVersion = versionQuery.toString() + "*";

    try (ElasticResultStore elasticResultStore = elasticHost.buildElasticResultStore(); //
            InputStream inputStream = LoadResultProjectAction.class
                    .getResourceAsStream("/versionResult.json")) {
        String versionResultQuery = IOUtils.toString(inputStream);
        Map<String, String> map = new HashMap<>(1);
        map.put("jettyVersion", jettyVersion);
        map.put("maxResult", Integer.toString(maxResult));
        versionResultQuery = StrSubstitutor.replace(versionResultQuery, map);

        String results = elasticResultStore.search(versionResultQuery);

        List<LoadResult> loadResults = ElasticResultStore
                .map(new HttpContentResponse(null, results.getBytes(), null, null));

        List<RunInformations> runInformations = //
                loadResults.stream() //
                        .filter(loadResult -> StringUtils.equalsIgnoreCase(originalJettyVersion, //
                                loadResult.getServerInfo().getJettyVersion())) //
                        .map(loadResult -> new RunInformations(
                                loadResult.getServerInfo().getJettyVersion() + ":"
                                        + loadResult.getServerInfo().getGitHash(), //
                                loadResult.getCollectorInformations(),
                                StringUtils.lowerCase(loadResult.getTransport())) //
                                        .jettyVersion(loadResult.getServerInfo().getJettyVersion()) //
                                        .estimatedQps(LoadTestResultBuildAction.estimatedQps(
                                                LoadTestResultBuildAction.getLoaderConfig(loadResult))) //
                                        .serverInfo(loadResult.getServerInfo())) //
                        .collect(Collectors.toList());

        Collections.sort(runInformations, Comparator.comparing(o -> o.getStartTimeStamp()));
        return runInformations;
    }

}

From source file:org.squale.welcom.outils.Util.java

public final static String formatFile(String st) {
    // Transforme les lettres accentues
    st = Util.formatAccent(st);//  ww  w  . ja  v  a 2  s .co  m

    final StringCharacterIterator iter = new StringCharacterIterator(st);
    final StringBuffer sb = new StringBuffer();

    for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
        if (!(((c >= '0') && (c <= '9')) || ((c >= 'a') && (c <= 'z'))
                || (((c >= 'A') && (c <= 'Z')) || (c == '.')))) {
            sb.append('_');
        } else {
            sb.append(c);
        }
    }

    return sb.toString();
}

From source file:com.tripit.auth.OAuthCredential.java

private static void jsonEncodeString(String string, StringBuilder sb) {
    CharacterIterator ci = new StringCharacterIterator(string);
    sb.append('"');
    for (char c = ci.first(); c != CharacterIterator.DONE; c = ci.next()) {
        switch (c) {
        case '\"':
            sb.append("\\\"");
            break;
        case '\\':
            sb.append("\\\\");
            break;
        case '\b':
            sb.append("\\b");
            break;
        case '\f':
            sb.append("\\f");
            break;
        case '\n':
            sb.append("\\n");
            break;
        case '\r':
            sb.append("\\r");
            break;
        case '\t':
            sb.append("\\t");
            break;
        default://w ww  .j a v a 2 s  .c  om
            sb.append(c);
            break;
        }
    }
    sb.append('"');
}

From source file:Base64.java

public static byte[] decodeBase64(String s) {
    CharacterIterator it = new StringCharacterIterator(s.trim());
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int i = 0, j = 0;
    for (char ch = it.first(); ch != CharacterIterator.DONE && ch != '='; ch = it.next()) {
        int v = b64d(ch);
        if (v >= 0) {
            i = (i << 6) | v;/*from www  .j a  v  a2  s .  co  m*/
            j++;
            if (j >= 4) {
                out.write(i >> 16);
                out.write(i >> 8);
                out.write(i);
                i = 0;
                j = 0;
            }
        }
    }
    switch (j) {
    case 3:
        out.write(i >> 10);
        out.write(i >> 2);
        break;
    case 2:
        out.write(i >> 4);
        break;
    }
    return out.toByteArray();
}

From source file:org.intermine.common.swing.text.RestrictedInputDocument.java

/**
 * Insert the given text into this document, as long as it leaves the document valid.
 * /* w  w  w  .j  av a  2 s .  c  o  m*/
 * @param offset The starting offset &gt;= 0.
 * @param str The string to insert; does nothing with null/empty strings.
 * @param attr The attributes for the inserted content.
 * 
 * @throws BadLocationException if the given insert position is not a valid
 * position within the document.
 *   
 * @see javax.swing.text.Document#insertString
 */
@Override
public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
    if (str == null) {
        return;
    }

    if (limit < 0 || getLength() + str.length() <= limit) {
        if (convertArray == null || convertArray.length < str.length()) {
            convertArray = new char[str.length()];
        }

        CharacterIterator iter = new StringCharacterIterator(str);
        char c = iter.first();
        int index;
        for (index = 0; c != CharacterIterator.DONE; c = iter.next()) {
            if (!overrideChecks && !StringUtils.contains(allowableCharacters, c)) {

                // At this point, c is invalid. See if a case change remedies this.

                if (caseConvert && Character.isLetter(c)) {
                    if (Character.isLowerCase(c)) {
                        c = Character.toUpperCase(c);
                    } else if (Character.isUpperCase(c)) {
                        c = Character.toLowerCase(c);
                    }
                    if (!StringUtils.contains(allowableCharacters, c)) {
                        // Don't insert but otherwise ignore.
                        return;
                    }
                } else {
                    return;
                }
            }
            convertArray[index++] = c;

        }
        super.insertString(offset, new String(convertArray, 0, index), attr);
    }
}

From source file:net.pms.encoders.FFmpegVideo.java

/**
 * Returns a list of strings representing the rescale options for this transcode i.e. the ffmpeg -vf
 * options used to show subtitles in SSA/ASS format and resize a video that's too wide and/or high for the specified renderer.
 * If the renderer has no size limits, or there's no media metadata, or the video is within the renderer's
 * size limits, an empty list is returned.
 *
 * @param dlna The DLNA resource representing the file being transcoded.
 * @param media the media metadata for the video being streamed. May contain unset/null values (e.g. for web videos).
 * @param params The {@link net.pms.io.OutputParams} context object used to store miscellaneous parameters for this request.
 * @return a {@link List} of <code>String</code>s representing the rescale options for this video,
 * or an empty list if the video doesn't need to be resized.
 *//*from www .  j  a v a2s .  c o  m*/
public List<String> getVideoFilterOptions(DLNAResource dlna, DLNAMediaInfo media, OutputParams params)
        throws IOException {
    List<String> options = new ArrayList<String>();
    String subsOption = null;
    String padding = null;
    final RendererConfiguration renderer = params.mediaRenderer;

    DLNAMediaSubtitle tempSubs = null;
    if (!isDisableSubtitles(params)) {
        tempSubs = getSubtitles(params);
    }

    final boolean isResolutionTooHighForRenderer = renderer.isVideoRescale() // renderer defines a max width/height
            && (media != null && media.isMediaparsed()) && ((media.getWidth() > renderer.getMaxVideoWidth())
                    || (media.getHeight() > renderer.getMaxVideoHeight()));

    if (tempSubs != null) {
        StringBuilder s = new StringBuilder();
        CharacterIterator it = new StringCharacterIterator(
                ProcessUtil.getShortFileNameIfWideChars(tempSubs.getExternalFile().getAbsolutePath()));

        for (char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) {
            switch (ch) {
            case ':':
                s.append("\\\\:");
                break;
            case '\\':
                s.append("/");
                break;
            case ']':
                s.append("\\]");
                break;
            case '[':
                s.append("\\[");
                break;
            default:
                s.append(ch);
            }
        }

        String subsFile = s.toString();
        subsFile = subsFile.replace(",", "\\,");
        subsOption = "subtitles=" + subsFile;
    }

    if (renderer.isPadVideoWithBlackBordersTo169AR() && renderer.isRescaleByRenderer()) {
        if (media != null && media.isMediaparsed() && media.getHeight() != 0
                && (media.getWidth() / (double) media.getHeight()) >= (16 / (double) 9)) {
            padding = "pad=iw:iw/(16/9):0:(oh-ih)/2";
        } else {
            padding = "pad=ih*(16/9):ih:(ow-iw)/2:0";
        }
    }

    String rescaleSpec = null;

    if (isResolutionTooHighForRenderer
            || (renderer.isPadVideoWithBlackBordersTo169AR() && !renderer.isRescaleByRenderer())) {
        rescaleSpec = String.format(
                // http://stackoverflow.com/a/8351875
                "scale=iw*min(%1$d/iw\\,%2$d/ih):ih*min(%1$d/iw\\,%2$d/ih),pad=%1$d:%2$d:(%1$d-iw)/2:(%2$d-ih)/2",
                renderer.getMaxVideoWidth(), renderer.getMaxVideoHeight());
    }

    String overrideVF = renderer.getFFmpegVideoFilterOverride();

    if (rescaleSpec != null || padding != null || overrideVF != null || subsOption != null) {
        options.add("-vf");
        StringBuilder filterParams = new StringBuilder();

        if (overrideVF != null) {
            filterParams.append(overrideVF);
            if (subsOption != null) {
                filterParams.append(", ");
            }
        } else {
            if (rescaleSpec != null) {
                filterParams.append(rescaleSpec);
                if (subsOption != null || padding != null) {
                    filterParams.append(", ");
                }
            }

            if (padding != null && rescaleSpec == null) {
                filterParams.append(padding);
                if (subsOption != null) {
                    filterParams.append(", ");
                }
            }
        }

        if (subsOption != null) {
            filterParams.append(subsOption);
        }

        options.add(filterParams.toString());
    }

    return options;
}

From source file:org.fracturedatlas.athena.web.manager.RecordManager.java

static Set<String> parseValues(String valueString) {
    HashSet<String> values = new HashSet<String>();
    valueString = StringUtils.trimToEmpty(valueString);
    valueString = StringUtils.strip(valueString, "()");
    valueString = StringUtils.trimToEmpty(valueString);
    CharacterIterator it = new StringCharacterIterator(valueString);
    boolean inString = false;
    int begin = 0;
    int end = 0;//w  w  w  .  ja v a2s.c  om
    int numValues = 0;
    StringBuilder sb = new StringBuilder();
    // Iterate over the characters in the forward direction
    for (char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) {
        if (ch == '\"') {
            inString = true;
            ch = it.next();
            sb = new StringBuilder();
            for (; ch != CharacterIterator.DONE; ch = it.next()) {
                if (ch == '\\') {
                    // skip any " in a string
                    sb.append(ch);
                    ch = it.next();
                } else if (ch == '\"') {
                    break;
                }
                sb.append(ch);
            }
            inString = false;
            values.add(StringUtils.trimToEmpty(sb.toString()));
        } else if (ch == ',') {
            // new value
        } else if (" \t\n\r".indexOf(ch) > -1) {
            //skip whitespace
        } else {
            // not a comma, whitespace or a string start
            sb = new StringBuilder();
            for (; ch != CharacterIterator.DONE; ch = it.next()) {
                if (ch == ',') {
                    break;
                }
                sb.append(ch);
            }
            inString = false;
            values.add(StringUtils.trimToEmpty(sb.toString()));

        }
    }

    return values;
}

From source file:org.architecturerules.domain.SourceDirectory.java

/**
 * <p>Replaces inappropriate backslash with the appropriate slash based on the operating system's requirements</p>
 *
 * <p>For example, on a Windows system, <tt>src/main/resources</tt> becomes <tt>src\\main\\resource</tt></p>
 *
 * <p>TODO: this may be able to be replaced with String.replaceAll, but I couldn't get the regex just right</p>
 *
 * <p>This todo/issue is open at <a href="http://code.google.com/p/architecturerules/issues/detail?id=29">issue
 * 29</a></p>/*from w ww  .  j a v  a 2s .  co m*/
 *
 * @param path String the path to fix
 * @return String the fixed path
 */
String replaceBackslashForOS(final String path) {

    final StringBuffer result = new StringBuffer();

    final StringCharacterIterator iterator = new StringCharacterIterator(path);

    char character = iterator.current();

    final char goal = File.separator.toCharArray()[0];
    final char target = ((goal == '\\') ? '/' : '\\');

    while (character != CharacterIterator.DONE) {

        result.append((character == target) ? goal : character);
        character = iterator.next();
    }

    return result.toString();
}