Example usage for java.lang StringBuilder charAt

List of usage examples for java.lang StringBuilder charAt

Introduction

In this page you can find the example usage for java.lang StringBuilder charAt.

Prototype

char charAt(int index);

Source Link

Document

Returns the char value at the specified index.

Usage

From source file:org.georchestra.security.Proxy.java

private String findTarget(String requestURI) {
    String[] segments;// w w w  .  j ava 2s  . c om
    if (requestURI.charAt(0) == '/') {
        segments = requestURI.substring(1).split("/");
    } else {
        segments = requestURI.split("/");
    }

    if (segments.length == 0) {
        return null;
    }
    String target = targets.get(segments[0]);
    if (target == null) {
        return null;
    } else {
        StringBuilder builder = new StringBuilder("/");
        for (int i = 1; i < segments.length; i++) {
            String segment = segments[i];
            builder.append(segment);
            if (i + 1 < segments.length)
                builder.append("/");
        }

        if (requestURI.endsWith("/") && builder.charAt(builder.length() - 1) != '/') {
            builder.append('/');
        }

        return concat(target, builder);
    }
}

From source file:com.heliosdecompiler.helios.tasks.DecompileTask.java

private Set<String> handleClassOrInterfaceType(ClassOrInterfaceType classOrInterfaceType) {
    Set<String> result = handled.get(classOrInterfaceType);
    if (result != null) {
        return result;
    }//from w ww  . ja  va  2s  . c o m
    result = new HashSet<>();
    handled.put(classOrInterfaceType, result);

    System.out.println("Handling ClassOrInterfaceType " + classOrInterfaceType + " on line "
            + classOrInterfaceType.getBeginLine());

    /*
     * Possibilities:
     * Simple name: System
     * -> Could be imported direcly
     * -> Could be imported using wildcard
     * -> Could be package-local
     * -> Could be java.lang
     * Inner class (Java): System.Inner
     * Inner class (Internal): System$Inner
     * Fully Qualified Name (Java): java.lang.System
     * Fully Qualified Name with inner (Java): java.lang.System.Inner
     * Fully Qualified Name with inner (internal): java.lang.System$Inner
     */
    Pair<Integer, Integer> offsets = getOffsets(lineSizes, classOrInterfaceType);
    ClickableSyntaxTextArea.Link link = new ClickableSyntaxTextArea.Link(classOrInterfaceType.getBeginLine(),
            classOrInterfaceType.getBeginColumn(), offsets.getValue0(), offsets.getValue1());

    /* Could be any of the above possibilities */
    String fullName = tostring.computeIfAbsent(classOrInterfaceType, toStringComputer);

    Set<String> allPossibilitiesWithoutImports = new HashSet<>();
    String[] split = fullName.split("\\.");
    for (int i = 0; i < split.length; i++) {
        StringBuilder builder = new StringBuilder();
        for (int start = 0; start < i; start++) {
            builder.append(split[start]).append("/");
        }
        for (int start = i; start < split.length; start++) {
            builder.append(split[start]).append("$");
        }
        if (builder.length() > 0 && (builder.charAt(builder.length() - 1) == '$'
                || builder.charAt(builder.length() - 1) == '/')) {
            builder.setLength(builder.length() - 1);
        }
        builder.append(".class");
        allPossibilitiesWithoutImports.add(builder.toString());
    }

    Set<String> possibleClassNames = new HashSet<>();
    possibleClassNames.addAll(allPossibilitiesWithoutImports);

    for (ImportDeclaration importDeclaration : compilationUnit.getImports()) {
        String javaName = importDeclaration.getName().toString();
        if (importDeclaration.isAsterisk()) {
            String fullImport = importDeclaration.getName().toString();
            String internalName = fullImport.replace('.', '/');
            for (String name : allPossibilitiesWithoutImports) {
                possibleClassNames.add(internalName + "/" + name);
            }
        } else if (importDeclaration.isStatic()) {

        } else {
            for (String name : allPossibilitiesWithoutImports) {
                String nameWithoutClass = name.substring(0, name.length() - 6);
                String simple = nameWithoutClass;
                int index;
                if ((index = simple.indexOf('.')) != -1) {
                    simple = simple.substring(0, index);
                    if (importDeclaration.getName().getName().equals(simple)) {
                        possibleClassNames.add(javaName.replace('.', '/') + "$"
                                + simple.substring(index + 1).replace('.', '$') + ".class");
                    }
                }
                if (importDeclaration.getName().getName().equals(nameWithoutClass)) {
                    possibleClassNames.add(javaName.replace('.', '/') + ".class");
                }
            }
        }
    }

    possibleClassNames.add("java/lang/" + classOrInterfaceType.getName() + ".class");

    if (packageName != null) {
        possibleClassNames.add(packageName + "/" + classOrInterfaceType.getName() + ".class");
    }

    System.out.println(possibleClassNames);

    Map<String, LoadedFile> mapping = possibleClassNames.stream()
            .map(name -> new AbstractMap.SimpleEntry<>(name, getFileFor(name)))
            .filter(ent -> ent.getValue() != null)
            .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue));

    System.out.println("Result: " + mapping.keySet());
    if (mapping.size() == 0) {
        System.out.println("ERROR: Could not find file which contains " + possibleClassNames);
    } else if (mapping.size() > 1) {
        System.out.println("ERROR: Multiple results: " + mapping.keySet());
    } else {
        Map.Entry<String, LoadedFile> entry = mapping.entrySet().iterator().next();
        link.fileName = entry.getValue().getName();
        link.className = entry.getKey();
        link.jumpTo = " " + classOrInterfaceType.getName() + " ";
        textArea.links.add(link);
    }

    result.addAll(mapping.keySet());

    return result;
}

From source file:com.example.phonetic.KoelnerPhonetik.java

private String substitute(String str) {
    String s = expandUmlauts(str.toUpperCase(Locale.GERMAN));
    s = removeSequences(s);/* w  ww.  j  av  a  2  s  . co m*/
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        char current = s.charAt(i);
        char next = i + 1 < s.length() ? s.charAt(i + 1) : '_';
        char prev = i > 0 ? s.charAt(i - 1) : '_';
        switch (current) {
        case 'A':
        case 'E':
        case 'I':
        case 'J':
        case 'Y':
        case 'O':
        case 'U':
            if (i == 0 || ((i == 1) && prev == 'H')) {
                sb.append(getCode());
            }
            break;
        case 'P':
            sb.append(next == 'H' ? "33" : '1');
            break;
        case 'B':
            sb.append('1');
            break;
        case 'D':
        case 'T':
            sb.append(csz.contains(next) ? '8' : '2');
            break;
        case 'F':
        case 'V':
        case 'W':
            sb.append('3');
            break;
        case 'G':
        case 'K':
        case 'Q':
            sb.append('4');
            break;
        case 'C':
            if (i == 0) {
                sb.append(ahkloqrux.contains(next) ? '4' : '8');
            } else {
                sb.append(aouhkxq.contains(next) ? '4' : '8');
            }
            if (sb.length() >= 2 && sb.charAt(sb.length() - 2) == '8') {
                sb.setCharAt(sb.length() - 1, '8');
            }
            break;
        case 'X':
            sb.append(i < 1 || !ckq.contains(prev) ? "48" : '8');
            break;
        case 'L':
            sb.append('5');
            break;
        case 'M':
        case 'N':
            sb.append('6');
            break;
        case 'R':
            sb.append('7');
            break;
        case 'S':
        case 'Z':
            sb.append('8');
            break;
        case 'H':
            break;
        }
    }
    s = sb.toString();
    s = removeSequences(s);
    return s;
}

From source file:com.nttec.everychan.ui.presentation.HtmlParser.java

public void characters(char ch[], int start, int length) throws SAXException {
    StringBuilder sb = new StringBuilder();

    /*//from  ww w  . j  a  v  a  2  s  . c om
     * Ignore whitespace that immediately follows other whitespace;
     * newlines count as spaces.
     */

    for (int i = 0; i < length; i++) {
        char c = ch[i + start];

        if (c == ' ' || c == '\n') {
            char pred;
            int len = sb.length();

            if (len == 0) {
                len = mSpannableStringBuilder.length();

                if (len == 0) {
                    pred = '\n';
                } else {
                    pred = mSpannableStringBuilder.charAt(len - 1);
                }
            } else {
                pred = sb.charAt(len - 1);
            }

            if (pred != ' ' && pred != '\n') {
                sb.append(' ');
            }
        } else {
            sb.append(c);
        }
    }

    mSpannableStringBuilder.append(sb);
}

From source file:org.apache.hadoop.mapreduce.v2.hs.webapp.HsJobsBlock.java

@Override
protected void render(Block html) {
    TBODY<TABLE<Hamlet>> tbody = html.h2("Retired Jobs").table("#jobs").thead().tr().th("Submit Time")
            .th("Start Time").th("Finish Time").th(".id", "Job ID").th(".name", "Name").th("User").th("Queue")
            .th(".state", "State").th("Maps Total").th("Maps Completed").th("Reduces Total")
            .th("Reduces Completed").th("Elapsed Time")._()._().tbody();
    LOG.info("Getting list of all Jobs.");
    // Write all the data into a JavaScript array of arrays for JQuery
    // DataTables to display
    StringBuilder jobsTableData = new StringBuilder("[\n");
    for (Job j : appContext.getAllJobs().values()) {
        JobInfo job = new JobInfo(j);
        jobsTableData.append("[\"").append(dateFormat.format(new Date(job.getSubmitTime()))).append("\",\"")
                .append(dateFormat.format(new Date(job.getStartTime()))).append("\",\"")
                .append(dateFormat.format(new Date(job.getFinishTime()))).append("\",\"").append("<a href='")
                .append(url("job", job.getId())).append("'>").append(job.getId()).append("</a>\",\"")
                .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(job.getName())))
                .append("\",\"")
                .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(job.getUserName())))
                .append("\",\"")
                .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(job.getQueueName())))
                .append("\",\"").append(job.getState()).append("\",\"")
                .append(String.valueOf(job.getMapsTotal())).append("\",\"")
                .append(String.valueOf(job.getMapsCompleted())).append("\",\"")
                .append(String.valueOf(job.getReducesTotal())).append("\",\"")
                .append(String.valueOf(job.getReducesCompleted())).append("\",\"")
                .append(StringUtils/*from  w w w  .jav  a2s .c  o m*/
                        .formatTimeSortable(Times.elapsed(job.getStartTime(), job.getFinishTime(), false)))
                .append("\"],\n");
    }

    //Remove the last comma and close off the array of arrays
    if (jobsTableData.charAt(jobsTableData.length() - 2) == ',') {
        jobsTableData.delete(jobsTableData.length() - 2, jobsTableData.length() - 1);
    }
    jobsTableData.append("]");
    html.script().$type("text/javascript")._("var jobsTableData=" + jobsTableData)._();
    tbody._().tfoot().tr().th().input("search_init").$type(InputType.text).$name("submit_time")
            .$value("Submit Time")._()._().th().input("search_init").$type(InputType.text).$name("start_time")
            .$value("Start Time")._()._().th().input("search_init").$type(InputType.text).$name("finish_time")
            .$value("Finish Time")._()._().th().input("search_init").$type(InputType.text).$name("job_id")
            .$value("Job ID")._()._().th().input("search_init").$type(InputType.text).$name("name")
            .$value("Name")._()._().th().input("search_init").$type(InputType.text).$name("user").$value("User")
            ._()._().th().input("search_init").$type(InputType.text).$name("queue").$value("Queue")._()._().th()
            .input("search_init").$type(InputType.text).$name("state").$value("State")._()._().th()
            .input("search_init").$type(InputType.text).$name("maps_total").$value("Maps Total")._()._().th()
            .input("search_init").$type(InputType.text).$name("maps_completed").$value("Maps Completed")._()._()
            .th().input("search_init").$type(InputType.text).$name("reduces_total").$value("Reduces Total")._()
            ._().th().input("search_init").$type(InputType.text).$name("reduces_completed")
            .$value("Reduces Completed")._()._().th().input("search_init").$type(InputType.text)
            .$name("elapsed_time").$value("Elapsed Time")._()._()._()._()._();
}

From source file:com.wavemaker.tools.ws.WebServiceToolsManager.java

/**
 * Generates the REST settings using the given request URL. This method will make a HTTP GET call using the request
 * URL and by using the XML response, it will then try to generate the REST settings.
 * /* ww w .  j a va 2s .  co m*/
 * @param endpointAddress The actual request URL.
 * @param method Request method (GET, POST)
 * @param contentType Mime content type
 * @param postData post data
 * @return
 * @throws WebServiceException
 * @throws IOException
 * @throws XmlException
 */
public RESTWsdlSettings generateRESTWsdlSettings(String endpointAddress, String method, String contentType,
        String postData, boolean basicAuth, String userName, String password, Map<String, String> headers)
        throws WebServiceException, IOException, XmlException {
    RESTWsdlSettings settings = new RESTWsdlSettings();

    URL serviceUrl = new URL(endpointAddress);

    serviceUrl.getHost();
    String serviceName = constructServiceName(serviceUrl);
    QName serviceQName = new QName(constructNamespace(endpointAddress), serviceName);

    // TODO: For now, we only support the xml contenty type. It should be
    // extended to cover other content
    // TODO: types such as text/plain.
    String cType = contentType + "; charset=UTF-8";
    DataSource postSource = HTTPBindingSupport.createDataSource(cType, postData);

    BindingProperties bp = null;
    if (basicAuth) {
        bp = new BindingProperties();
        bp.setHttpBasicAuthUsername(userName);
        bp.setHttpBasicAuthPassword(password);
    }

    Map<String, Object> headerParams = new HashMap<String, Object>();
    Set<Entry<String, String>> entries = headers.entrySet();
    for (Map.Entry<String, String> entry : entries) {
        headerParams.put(entry.getKey(), entry.getValue());
    }

    String responseString = HTTPBindingSupport.getResponseString(serviceQName, serviceQName, endpointAddress,
            HTTPRequestMethod.valueOf(method), postSource, bp, headerParams);

    String outputType = null;
    String xmlSchemaText = null;
    try {
        xmlSchemaText = convertXmlToSchema(responseString);
        outputType = getXmlRootElementType(responseString);
    } catch (Exception e) {
        // can't generate schema, so just set the output type to raw string
        outputType = "string";
    }

    String query = serviceUrl.getQuery();
    List<RESTInputParam> inputs = new ArrayList<RESTInputParam>();
    String parameterizedUrl = null;
    if (query != null) {
        StringBuilder sb = new StringBuilder();
        sb.append(getUrlOmitQuery(endpointAddress));
        sb.append("?");
        String[] qparts = query.split("&");
        for (String qpart : qparts) {
            int i = qpart.indexOf('=');
            if (i > -1) {
                String name = qpart.substring(0, i);
                sb.append(name);
                sb.append("={");
                sb.append(name);
                sb.append("}&");
                inputs.add(new RESTInputParam(name, "string"));
            } else {
                sb.append(qpart);
                sb.append("&");
            }
        }
        if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '&') {
            sb.deleteCharAt(sb.length() - 1);
        }
        parameterizedUrl = sb.toString();
    } else {
        parameterizedUrl = endpointAddress;
    }

    Set<Entry<String, String>> headerEntries = headers.entrySet();
    for (Map.Entry<String, String> entry : headerEntries) {
        inputs.add(new RESTInputParam(entry.getKey(), RESTInputParam.InputType.STRING,
                RESTInputParam.InputLocation.HEADER));
    }

    settings.setServiceName(serviceName);
    settings.setOperationName("invoke");
    settings.setInputs(inputs);
    settings.setParameterizedUrl(parameterizedUrl);
    settings.setOutputType(outputType);
    settings.setXmlSchemaText(xmlSchemaText);

    return settings;
}

From source file:net.sf.jabref.importer.fileformat.BibtexParser.java

/**
 * Tries to restore the key//from ww w.  ja v a2s .c om
 *
 * @return rest of key on success, otherwise empty string
 * @throws IOException on Reader-Error
 */
private String fixKey() throws IOException {
    StringBuilder key = new StringBuilder();
    int lookaheadUsed = 0;
    char currentChar;

    // Find a char which ends key (','&&'\n') or entryfield ('='):
    do {
        currentChar = (char) read();
        key.append(currentChar);
        lookaheadUsed++;
    } while ((currentChar != ',') && (currentChar != '\n') && (currentChar != '=')
            && (lookaheadUsed < BibtexParser.LOOKAHEAD));

    // Consumed a char too much, back into reader and remove from key:
    unread(currentChar);
    key.deleteCharAt(key.length() - 1);

    // Restore if possible:
    switch (currentChar) {
    case '=':
        // Get entryfieldname, push it back and take rest as key
        key = key.reverse();

        boolean matchedAlpha = false;
        for (int i = 0; i < key.length(); i++) {
            currentChar = key.charAt(i);

            /// Skip spaces:
            if (!matchedAlpha && (currentChar == ' ')) {
                continue;
            }
            matchedAlpha = true;

            // Begin of entryfieldname (e.g. author) -> push back:
            unread(currentChar);
            if ((currentChar == ' ') || (currentChar == '\n')) {

                /*
                 * found whitespaces, entryfieldname completed -> key in
                 * keybuffer, skip whitespaces
                 */
                StringBuilder newKey = new StringBuilder();
                for (int j = i; j < key.length(); j++) {
                    currentChar = key.charAt(j);
                    if (!Character.isWhitespace(currentChar)) {
                        newKey.append(currentChar);
                    }
                }

                // Finished, now reverse newKey and remove whitespaces:
                parserResult.addWarning(
                        Localization.lang("Line %0: Found corrupted BibTeX key.", String.valueOf(line)));
                key = newKey.reverse();
            }
        }
        break;

    case ',':
        parserResult.addWarning(Localization.lang("Line %0: Found corrupted BibTeX key (contains whitespaces).",
                String.valueOf(line)));
        break;

    case '\n':
        parserResult.addWarning(Localization.lang("Line %0: Found corrupted BibTeX key (comma missing).",
                String.valueOf(line)));
        break;

    default:

        // No more lookahead, give up:
        unreadBuffer(key);
        return "";
    }

    return removeWhitespaces(key).toString();
}

From source file:com.irccloud.android.ColorFormatter.java

public static String irc_to_html(String msg) {
    if (msg == null)
        return "";

    int pos = 0;/*from w w w .  j a va2  s .c  o m*/
    boolean bold = false, underline = false, italics = false;
    String fg = "", bg = "";
    StringBuilder builder = new StringBuilder(msg);
    builder.insert(0, "<irc>");

    while (pos < builder.length()) {
        if (builder.charAt(pos) == 2) { //Bold
            String html = "";
            if (bold) {
                html += "</b>";
                if (fg.length() > 0) {
                    html += "</font>";
                }
                if (bg.length() > 0) {
                    html += "</_bg" + bg + ">";
                }
                if (italics)
                    html += "</i>";
                if (underline)
                    html += "</u>";
                if (fg.length() > 0) {
                    html += "<font color=\"#" + fg + "\">";
                }
                if (bg.length() > 0) {
                    html += "<_bg" + bg + ">";
                }
                if (italics)
                    html += "<i>";
                if (underline)
                    html += "<u>";
            } else {
                html += "<b>";
            }
            bold = !bold;
            builder.deleteCharAt(pos);
            builder.insert(pos, html);
        } else if (builder.charAt(pos) == 22 || builder.charAt(pos) == 29) { //Italics
            String html = "";
            if (italics) {
                html += "</i>";
                if (fg.length() > 0) {
                    html += "</font>";
                }
                if (bg.length() > 0) {
                    html += "</_bg" + bg + ">";
                }
                if (bold)
                    html += "</b>";
                if (underline)
                    html += "</u>";
                if (fg.length() > 0) {
                    html += "<font color=\"#" + fg + "\">";
                }
                if (bg.length() > 0) {
                    html += "<_bg" + bg + ">";
                }
                if (bold)
                    html += "<b>";
                if (underline)
                    html += "<u>";
            } else {
                html += "<i>";
            }
            italics = !italics;
            builder.deleteCharAt(pos);
            builder.insert(pos, html);
        } else if (builder.charAt(pos) == 31) { //Underline
            String html = "";
            if (underline) {
                html += "</u>";
                if (fg.length() > 0) {
                    html += "</font>";
                }
                if (bg.length() > 0) {
                    html += "</_bg" + bg + ">";
                }
                if (bold)
                    html += "</b>";
                if (italics)
                    html += "</i>";
                if (fg.length() > 0) {
                    html += "<font color=\"#" + fg + "\">";
                }
                if (bg.length() > 0) {
                    html += "<_bg" + bg + ">";
                }
                if (bold)
                    html += "<b>";
                if (italics)
                    html += "<i>";
            } else {
                html += "<u>";
            }
            underline = !underline;
            builder.deleteCharAt(pos);
            builder.insert(pos, html);
        } else if (builder.charAt(pos) == 15) { //Formatting clear
            String html = "";
            if (fg.length() > 0) {
                html += "</font>";
                fg = "";
            }
            if (bg.length() > 0) {
                html += "</_bg" + bg + ">";
                bg = "";
            }
            if (bold) {
                html += "</b>";
                bold = false;
            }
            if (underline) {
                html += "</u>";
                underline = false;
            }
            if (italics) {
                html += "</i>";
                italics = false;
            }
            builder.deleteCharAt(pos);
            if (html.length() > 0)
                builder.insert(pos, html);
        } else if (builder.charAt(pos) == 3 || builder.charAt(pos) == 4) { //Color
            boolean rgb = (builder.charAt(pos) == 4);
            int count = 0;
            String new_fg = "", new_bg = "";
            builder.deleteCharAt(pos);
            if (pos < builder.length()) {
                while (pos + count < builder.length()
                        && ((builder.charAt(pos + count) >= '0' && builder.charAt(pos + count) <= '9') || rgb
                                && ((builder.charAt(pos + count) >= 'a' && builder.charAt(pos + count) <= 'f')
                                        || (builder.charAt(pos + count) >= 'A'
                                                && builder.charAt(pos + count) <= 'F')))) {
                    if ((++count == 2 && !rgb) || count == 6)
                        break;
                }
                if (count > 0) {
                    if (count < 3 && !rgb) {
                        try {
                            int col = Integer.parseInt(builder.substring(pos, pos + count));
                            if (col > 15) {
                                count--;
                                col /= 10;
                            }
                            new_fg = COLOR_MAP[col];
                        } catch (NumberFormatException e) {
                            new_fg = builder.substring(pos, pos + count);
                        }
                    } else
                        new_fg = builder.substring(pos, pos + count);
                    builder.delete(pos, pos + count);
                }
                if (pos < builder.length() && builder.charAt(pos) == ',') {
                    builder.deleteCharAt(pos);
                    if (new_fg.length() == 0)
                        new_fg = "clear";
                    new_bg = "clear";
                    count = 0;
                    while (pos + count < builder.length()
                            && ((builder.charAt(pos + count) >= '0' && builder.charAt(pos + count) <= '9')
                                    || rgb && ((builder.charAt(pos + count) >= 'a'
                                            && builder.charAt(pos + count) <= 'f')
                                            || (builder.charAt(pos + count) >= 'A'
                                                    && builder.charAt(pos + count) <= 'F')))) {
                        if ((++count == 2 && !rgb) || count == 6)
                            break;
                    }
                    if (count > 0) {
                        if (count < 3 && !rgb) {
                            try {
                                int col = Integer.parseInt(builder.substring(pos, pos + count));
                                if (col > 15) {
                                    count--;
                                    col /= 10;
                                }
                                new_bg = COLOR_MAP[col];
                            } catch (NumberFormatException e) {
                                new_bg = builder.substring(pos, pos + count);
                            }
                        } else
                            new_bg = builder.substring(pos, pos + count);
                        builder.delete(pos, pos + count);
                    } else {
                        builder.insert(pos, ",");
                    }
                }
                String html = "";
                if (new_fg.length() == 0 && new_bg.length() == 0) {
                    new_fg = "clear";
                    new_bg = "clear";
                }
                if (new_fg.length() > 0 && fg.length() > 0) {
                    html += "</font>";
                }
                if (new_bg.length() > 0 && bg.length() > 0) {
                    html += "</_bg" + bg + ">";
                }
                if (new_bg.length() > 0) {
                    if (new_bg.equals("clear")) {
                        bg = "";
                    } else {
                        bg = "";
                        if (new_bg.length() == 6) {
                            bg = new_bg;
                        } else if (new_bg.length() == 3) {
                            bg += new_bg.charAt(0);
                            bg += new_bg.charAt(0);
                            bg += new_bg.charAt(1);
                            bg += new_bg.charAt(1);
                            bg += new_bg.charAt(2);
                            bg += new_bg.charAt(2);
                        } else {
                            bg = "ffffff";
                        }
                        if (bg.length() > 0)
                            html += "<_bg" + bg + ">";
                    }
                }
                if (new_fg.length() > 0) {
                    if (new_fg.equals("clear")) {
                        fg = "";
                    } else {
                        fg = "";
                        if (new_fg.length() == 6) {
                            fg = new_fg;
                        } else if (new_fg.length() == 3) {
                            fg += new_fg.charAt(0);
                            fg += new_fg.charAt(0);
                            fg += new_fg.charAt(1);
                            fg += new_fg.charAt(1);
                            fg += new_fg.charAt(2);
                            fg += new_fg.charAt(2);
                        } else {
                            fg = "000000";
                        }
                    }
                    if (ColorScheme.getInstance().theme != null && bg.length() == 0) {
                        if (ColorScheme.getInstance().isDarkTheme && DARK_FG_SUBSTITUTIONS.containsKey(fg))
                            fg = DARK_FG_SUBSTITUTIONS.get(fg);
                        if (Integer.toHexString(ColorScheme.getInstance().contentBackgroundColor)
                                .equalsIgnoreCase("ff" + fg)) {
                            int red = Integer.parseInt(fg.substring(0, 1), 16);
                            int blue = Integer.parseInt(fg.substring(2, 3), 16);
                            int green = Integer.parseInt(fg.substring(4, 5), 16);

                            red += 0x22;
                            if (red > 0xFF)
                                red = 0xFF;
                            green += 0x22;
                            if (green > 0xFF)
                                green = 0xFF;
                            blue += 0x22;
                            if (blue > 0xFF)
                                blue = 0xFF;

                            fg = String.format("%02x%02x%02x", red, green, blue);
                        }
                    }
                    if (fg.length() > 0)
                        html += "<font color=\"#" + fg + "\">";
                }
                builder.insert(pos, html);
            }
        } else {
            pos++;
        }
    }
    if (fg.length() > 0) {
        builder.append("</font>");
    }
    if (bg.length() > 0) {
        builder.append("</_bg").append(bg).append(">");
    }
    if (bold)
        builder.append("</b>");
    if (underline)
        builder.append("</u>");
    if (italics)
        builder.append("</i>");

    builder.append("</irc>");
    return builder.toString();
}

From source file:be.jacobsvanroy.springsqlunit.util.ScriptUtils.java

/**
 * Split an SQL script into separate statements delimited by the provided
 * separator string. Each individual statement will be added to the provided
 * {@code List}.//  ww w  . ja v a2s.  co  m
 * <p>Within the script, the provided {@code commentPrefix} will be honored:
 * any text beginning with the comment prefix and extending to the end of the
 * line will be omitted from the output. Similarly, the provided
 * {@code blockCommentStartDelimiter} and {@code blockCommentEndDelimiter}
 * delimiters will be honored: any text enclosed in a block comment will be
 * omitted from the output. In addition, multiple adjacent whitespace characters
 * will be collapsed into a single space.
 *
 * @param resource                   the resource from which the script was read
 * @param script                     the SQL script; never {@code null} or empty
 * @param separator                  text separating each statement &mdash; typically a ';' or
 *                                   newline character; never {@code null}
 * @param commentPrefix              the prefix that identifies SQL line comments &mdash;
 *                                   typically "--"; never {@code null} or empty
 * @param blockCommentStartDelimiter the <em>start</em> block comment delimiter;
 *                                   never {@code null} or empty
 * @param blockCommentEndDelimiter   the <em>end</em> block comment delimiter;
 *                                   never {@code null} or empty
 * @param statements                 the list that will contain the individual statements
 */
public static void splitSqlScript(EncodedResource resource, String script, String separator,
        String commentPrefix, String blockCommentStartDelimiter, String blockCommentEndDelimiter,
        List<String> statements) {

    Assert.hasText(script, "script must not be null or empty");
    Assert.notNull(separator, "separator must not be null");
    Assert.hasText(commentPrefix, "commentPrefix must not be null or empty");
    Assert.hasText(blockCommentStartDelimiter, "blockCommentStartDelimiter must not be null or empty");
    Assert.hasText(blockCommentEndDelimiter, "blockCommentEndDelimiter must not be null or empty");

    StringBuilder sb = new StringBuilder();
    boolean inLiteral = false;
    boolean inEscape = false;
    char[] content = script.toCharArray();
    for (int i = 0; i < script.length(); i++) {
        char c = content[i];
        if (inEscape) {
            inEscape = false;
            sb.append(c);
            continue;
        }
        // MySQL style escapes
        if (c == '\\') {
            inEscape = true;
            sb.append(c);
            continue;
        }
        if (c == '\'') {
            inLiteral = !inLiteral;
        }
        if (!inLiteral) {
            if (script.startsWith(separator, i)) {
                // we've reached the end of the current statement
                if (sb.length() > 0) {
                    statements.add(sb.toString());
                    sb = new StringBuilder();
                }
                i += separator.length() - 1;
                continue;
            } else if (script.startsWith(commentPrefix, i)) {
                // skip over any content from the start of the comment to the EOL
                int indexOfNextNewline = script.indexOf("\n", i);
                if (indexOfNextNewline > i) {
                    i = indexOfNextNewline;
                    continue;
                } else {
                    // if there's no EOL, we must be at the end
                    // of the script, so stop here.
                    break;
                }
            } else if (script.startsWith(blockCommentStartDelimiter, i)) {
                // skip over any block comments
                int indexOfCommentEnd = script.indexOf(blockCommentEndDelimiter, i);
                if (indexOfCommentEnd > i) {
                    i = indexOfCommentEnd + blockCommentEndDelimiter.length() - 1;
                    continue;
                } else {
                    throw new RuntimeException(
                            String.format("Missing block comment end delimiter [%s] for resource [%s].",
                                    blockCommentEndDelimiter, resource.toString()));
                }
            } else if (c == ' ' || c == '\n' || c == '\t') {
                // avoid multiple adjacent whitespace characters
                if (sb.length() > 0 && sb.charAt(sb.length() - 1) != ' ') {
                    c = ' ';
                } else {
                    continue;
                }
            }
        }
        sb.append(c);
    }
    if (StringUtils.hasText(sb)) {
        statements.add(sb.toString());
    }
}

From source file:jp.aegif.alfresco.online_webdav.WebDAVHelper.java

public String getUrlPathPrefix(HttpServletRequest request) {
    StringBuilder urlStr = null;
    if (StringUtils.hasText(m_urlPathPrefix)) {
        // A specific prefix has been configured in, so use it.
        urlStr = new StringBuilder(m_urlPathPrefix);
    } else {//from w ww .  ja v a 2  s  . co m
        // Extract the path prefix from the request, using the servlet path as a guide.
        // e.g. "/preamble/servlet-mapping/folder/file.txt"
        // with a servlet path of "/servlet-mapping"
        // would result in a path prefix of "/preamble/servlet-mapping" being discovered.
        urlStr = new StringBuilder(request.getRequestURI());
        String servletPath = request.getServletPath();

        int rootPos = urlStr.indexOf(servletPath);
        if (rootPos != -1) {
            urlStr.setLength(rootPos + servletPath.length());
        }
    }

    // Ensure the prefix ends in the path separator.
    if (urlStr.length() == 0 || urlStr.charAt(urlStr.length() - 1) != PathSeperatorChar) {
        urlStr.append(PathSeperator);
    }

    return urlStr.toString();
}