Example usage for org.apache.commons.lang StringUtils replaceOnce

List of usage examples for org.apache.commons.lang StringUtils replaceOnce

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils replaceOnce.

Prototype

public static String replaceOnce(String text, String searchString, String replacement) 

Source Link

Document

Replaces a String with another String inside a larger String, once.

Usage

From source file:org.sonar.api.utils.log.ConsoleFormatter.java

static String format(String pattern, Object... args) {
    String result = pattern;/* w ww .j a va2s .  c  om*/
    for (Object arg : args) {
        result = StringUtils.replaceOnce(result, "{}", Objects.toString(arg));
    }
    return result;
}

From source file:org.structr.core.script.Scripting.java

public static String replaceVariables(final ActionContext actionContext, final GraphObject entity,
        final Object rawValue) throws FrameworkException {

    if (rawValue == null) {

        return null;
    }/*from   w w w .j a v  a2 s  . com*/

    String value;

    if (rawValue instanceof String) {

        value = (String) rawValue;

        if (!actionContext.returnRawValue()) {

            final List<Tuple> replacements = new LinkedList<>();

            for (final String expression : extractScripts(value)) {

                final Object extractedValue = evaluate(actionContext, entity, expression);
                String partValue = extractedValue != null ? formatToDefaultDateOrString(extractedValue) : "";

                if (partValue != null) {

                    replacements.add(new Tuple(expression, partValue));

                } else {

                    // If the whole expression should be replaced, and partValue is null
                    // replace it by null to make it possible for HTML attributes to not be rendered
                    // and avoid something like ... selected="" ... which is interpreted as selected==true by
                    // all browsers
                    if (!value.equals(expression)) {
                        replacements.add(new Tuple(expression, ""));
                    }
                }
            }

            // apply replacements
            for (final Tuple tuple : replacements) {

                // only replace a single occurrence at a time!
                value = StringUtils.replaceOnce(value, tuple.key, tuple.value);
            }
        }

    } else if (rawValue instanceof Boolean) {

        value = Boolean.toString((Boolean) rawValue);

    } else {

        value = rawValue.toString();

    }

    // return literal null
    if (Functions.NULL_STRING.equals(value)) {
        return null;
    }

    return value;
}

From source file:org.twinkql.context.TwinkqlContextFactory.java

/**
 * Replace markers.//ww w . j  a v a  2 s. c  o  m
 *
 * @param adder the adder
 * @param clazz the clazz
 * @param select the select
 * @param xmlStart the xml start
 * @param xmlEnd the xml end
 * @param marker the marker
 */
private void replaceMarkers(AddToSelectItem adder, Class<?> clazz, Select select, String xmlStart,
        String xmlEnd, String marker) {
    String content = select.getContent();

    String[] newContents = StringUtils.substringsBetween(content, marker, marker);

    if (newContents != null) {
        for (String newContent : newContents) {
            String excapedContent = this.excapeInnerXml(newContent);

            String adjustedContent = xmlStart + excapedContent + xmlEnd;

            Object obj;
            try {
                obj = Unmarshaller.unmarshal(clazz, new StringReader(adjustedContent));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            SelectItem newSelectItem = new SelectItem();
            adder.addToSelectItem(obj, newSelectItem);
            select.addSelectItem(newSelectItem);

            String uuid = "{" + UUID.randomUUID().toString() + "}";

            content = StringUtils.replaceOnce(content, marker + newContent + marker, uuid);
            adder.setId(obj, uuid);
        }

        select.setContent(content);
    }
}

From source file:org.twinkql.template.TwinkqlTemplate.java

/**
 * Replace marker./*from  w ww  .  ja v a2  s  . co m*/
 *
 * @param id the id
 * @param query the query
 * @param replacement the replacement
 * @return the string
 */
private String replaceMarker(String id, String query, String replacement) {
    return StringUtils.replaceOnce(query, id, replacement);
}

From source file:pl.betoncraft.betonquest.config.ConfigUpdater.java

@SuppressWarnings("unused")
private void update_from_v28() {
    String globalName = "global";
    try {/*from   w  w w .j  av a2 s .c o  m*/
        HashMap<String, ArrayList<String>> tags = new HashMap<>();
        HashMap<String, ArrayList<String>> points = new HashMap<>();
        // this will ensure that there is no "global" package already
        // defined
        int i = 1;
        while (Config.getPackages().get(globalName) != null) {
            i++;
            globalName = "global-" + i;
        }
        Debug.info("Global package will be called '" + globalName + "'");
        // create lists for tags/points that are duplicated across multiple
        // packages
        // these will be "global", the rest will be converted to their local
        // packages
        ArrayList<String> globalTagList = new ArrayList<>();
        ArrayList<String> globalPointList = new ArrayList<>();
        tags.put(globalName, globalTagList);
        points.put(globalName, globalPointList);
        ArrayList<ConfigPackage> packages = new ArrayList<>();
        for (ConfigPackage pack : Config.getPackages().values()) {
            String packName = pack.getName();
            Debug.info("  Checking '" + packName + "' package");
            // skip packages that already use prefixes
            String prefixOption = pack.getString("main.tag_point_prefix");
            if (prefixOption != null && prefixOption.equalsIgnoreCase("true"))
                continue;
            Debug.info("  - It's outdated, extracting tags and points from events");
            packages.add(pack);
            // create array lists
            ArrayList<String> tagList = new ArrayList<>();
            ArrayList<String> pointList = new ArrayList<>();
            tags.put(packName, tagList);
            points.put(packName, pointList);
            // handle all tags/points in events
            for (String key : pack.getEvents().getConfig().getKeys(false)) {
                Debug.info("    Checking '" + key + "' event");
                String rawInstruction = pack.getEvents().getConfig().getString(key);
                ArrayList<String> instructions = new ArrayList<>();
                // run event also needs to be checked in case it contained
                // any tags
                if (rawInstruction.startsWith("run ")) {
                    Debug.info("    - It's \"run\" event, extracting additional instructions");
                    // this part is copied from run event
                    String[] parts = rawInstruction.substring(3).trim().split(" ");
                    StringBuilder builder = new StringBuilder();
                    for (String part : parts) {
                        if (part.startsWith("^")) {
                            if (builder.length() != 0) {
                                instructions.add(builder.toString().trim());
                                builder = new StringBuilder();
                            }
                            builder.append(part.substring(1) + " ");
                        } else {
                            builder.append(part + " ");
                        }
                    }
                    instructions.add(builder.toString().trim());
                } else {
                    // if it's not run event, add whole instruction string
                    instructions.add(rawInstruction);
                }
                // check every instruction that was specified
                for (String instruction : instructions) {
                    if (instruction.startsWith("tag ")) {
                        Debug.info("      Found tag event, extracting tag");
                        String[] parts = instruction.split(" ");
                        // check if it contains the tag, if not - continue
                        if (parts.length < 3) {
                            Debug.info("      - Could not find tags");
                            continue;
                        }
                        // add tag to the list if it does not contain a
                        // package
                        for (String tag : parts[2].split(",")) {
                            if (!tag.contains("."))
                                tagList.add(tag);
                        }
                    } else if (instruction.startsWith("point ")) {
                        Debug.info("      Found point event, extracting points");
                        String[] parts = instruction.split(" ");
                        // check if the point has defined a category
                        if (parts.length < 2) {
                            Debug.info("      - Could not find the category");
                            continue;
                        }
                        // add point to the list if it does not contain a
                        // package
                        if (!parts[1].contains("."))
                            pointList.add(parts[1]);
                    }
                }
                // done, all tags in events are extracted
            }
            Debug.info("  All tags and points extracted from events, moving to conditions");
            // handle all tags/points in conditions
            for (String key : pack.getConditions().getConfig().getKeys(false)) {
                Debug.info("    Checking '" + key + "' condition");
                String rawInstruction = pack.getConditions().getConfig().getString(key);
                ArrayList<String> instructions = new ArrayList<>();
                // check condition also needs to be checked in case it
                // contained any tags
                if (rawInstruction.startsWith("check ")) {
                    Debug.info("    - It's \"check\" condition, extracting additional instructions");
                    // this part is copied from run event
                    String[] parts = rawInstruction.substring(5).trim().split(" ");
                    StringBuilder builder = new StringBuilder();
                    for (String part : parts) {
                        if (part.startsWith("^")) {
                            if (builder.length() != 0) {
                                instructions.add(builder.toString().trim());
                                builder = new StringBuilder();
                            }
                            builder.append(part.substring(1) + " ");
                        } else {
                            builder.append(part + " ");
                        }
                    }
                    instructions.add(builder.toString().trim());
                } else {
                    // if it's not check condition, add whole instruction
                    // string
                    instructions.add(rawInstruction);
                }
                // check every instruction that was specified
                for (String instruction : instructions) {
                    if (instruction.startsWith("tag ")) {
                        Debug.info("      Found tag condition, extracting tag");
                        String[] parts = instruction.split(" ");
                        // check if it contains the tag, if not - continue
                        if (parts.length < 2) {
                            Debug.info("      - Could not find the tag");
                            continue;
                        }
                        // add tag to the list if it does not contain a
                        // package
                        if (!parts[1].contains("."))
                            tagList.add(parts[1]);
                    } else if (instruction.startsWith("point ")) {
                        Debug.info("      Found point condition, extracting points");
                        String[] parts = instruction.split(" ");
                        // check if the point has defined a category
                        if (parts.length < 2) {
                            Debug.info("      - Could not find the category");
                            continue;
                        }
                        // add point to the list if it does not contain a
                        // package
                        if (!parts[1].contains("."))
                            pointList.add(parts[1]);
                    }
                }
                // done, all tags in conditions are extracted
            }
            Debug.info("  All tags and points extracted from conditions");
            // done, events and conditions in package extracted
        }
        Debug.info("All tags and points in all packages extracted, checking tags for duplicates");
        // find tags/points that are duplicated in package hashMaps,
        // put them to global package and remove from those packages
        // first tags in each package
        for (int j = 0; j < packages.size(); j++) {
            Debug.info("  Checking list '" + packages.get(j).getName() + "'");
            // get a list
            ArrayList<String> list = tags.get(packages.get(j).getName());
            // and for each element
            for (int k = 0; k < list.size(); k++) {
                String checked = list.get(k);
                Debug.info("    Checking tag '" + checked + "'");
                // go to each next package
                for (int l = j + 1; l < packages.size(); l++) {
                    ArrayList<String> nextList = tags.get(packages.get(l).getName());
                    // and check if it contains that element
                    if (nextList.contains(checked)) {
                        Debug.info(
                                "    - list '" + packages.get(l).getName() + "' contains this tag, removing");
                        nextList.remove(checked);
                        if (!globalTagList.contains(checked)) {
                            globalTagList.add(checked);
                            Debug.info("      Tag was added to the global list");
                        }
                    }
                }
            }
        }
        Debug.info("List of global tags is filled, checking points");
        // now points in each package
        for (int j = 0; j < packages.size(); j++) {
            Debug.info("  Checking list '" + packages.get(j).getName() + "'");
            // get a list
            ArrayList<String> list = points.get(packages.get(j).getName());
            // and for each element
            for (int k = 0; k < list.size(); k++) {
                String checked = list.get(k);
                Debug.info("    Checking point '" + checked + "'");
                // go to each next package
                for (int l = j + 1; l < packages.size(); l++) {
                    ArrayList<String> nextList = points.get(packages.get(l).getName());
                    // and check if it contains that element
                    if (nextList.contains(checked)) {
                        Debug.info(
                                "    - list '" + packages.get(l).getName() + "' contains this point, removing");
                        nextList.remove(checked);
                        if (!globalPointList.contains(checked)) {
                            globalPointList.add(checked);
                            Debug.info("      Point was added to the global list");
                        }
                    }
                }
            }
        }
        Debug.info("List of global points is filled, now adding \"global\" prefix in configuration files");
        // done, global lists are filled
        for (ConfigPackage pack : packages) {
            Debug.info("  Replacing in '" + pack.getName() + "' package");
            // update tags/points in events
            for (String key : pack.getEvents().getConfig().getKeys(false)) {
                Debug.info("    Replacing tags/points in '" + key + "' event");
                String instruction = pack.getEvents().getConfig().getString(key);
                if (instruction.startsWith("tag ")) {
                    Debug.info("      Found tag event, replacing tags");
                    String[] parts = instruction.split(" ");
                    // check if it contains the tag, if not - continue
                    if (parts.length < 3) {
                        Debug.info("      - Could not find tags");
                        continue;
                    }
                    // replace tags
                    String[] localTags = parts[2].split(",");
                    for (int j = 0; j < localTags.length; j++)
                        if (globalTagList.contains(localTags[j])) {
                            String replaced = globalName + "." + localTags[j];
                            Debug.info("        Replacing '" + localTags[j] + "' with '" + replaced + "'");
                            localTags[j] = replaced;
                        }
                    pack.getEvents().getConfig().set(key,
                            instruction.replace(parts[2], StringUtils.join(Arrays.asList(localTags), ',')));
                } else if (instruction.startsWith("point ")) {
                    Debug.info("      Found point event, replacing points");
                    String[] parts = instruction.split(" ");
                    // check if the point has defined a category
                    if (parts.length < 2) {
                        Debug.info("      - Could not find the category");
                        continue;
                    }
                    // replace points category
                    if (globalPointList.contains(parts[1])) {
                        String replaced = globalName + "." + parts[1];
                        Debug.info("        Replacing '" + parts[1] + "' with '" + replaced + "'");
                        pack.getEvents().getConfig().set(key,
                                StringUtils.replaceOnce(instruction, parts[1], replaced));
                    }
                } else if (instruction.startsWith("run ")) {
                    Debug.info("      Found run event, looking for tags and points");
                    String[] parts = instruction.split(" ");
                    for (int j = 0; j < parts.length; j++) {
                        // if the part is beginning of the "tag" instruction
                        // and it contains a tag
                        if (parts[j].equals("^tag") && j + 2 < parts.length) {
                            Debug.info("        There is a tag event, replacing tags");
                            String[] localTags = parts[j + 2].split(",");
                            for (int k = 0; k < localTags.length; k++)
                                if (globalTagList.contains(localTags[k])) {
                                    String replaced = globalName + "." + localTags[k];
                                    Debug.info(
                                            "        Replacing '" + localTags[k] + "' with '" + replaced + "'");
                                    localTags[k] = replaced;
                                }
                            parts[j + 2] = StringUtils.join(Arrays.asList(localTags), ',');
                        } else if (parts[j].equals("^point") && j + 1 < parts.length) {
                            Debug.info("        There is a point event, replacing points");
                            if (globalTagList.contains(parts[j + 1])) {
                                String replaced = globalName + "." + parts[j + 1];
                                Debug.info("        Replacing '" + parts[j + 1] + "' with '" + replaced + "'");
                                parts[j + 1] = replaced;
                            }
                        }
                    }
                    pack.getEvents().getConfig().set(key, StringUtils.join(Arrays.asList(parts), ' '));
                }
            }
            pack.getEvents().saveConfig();
            Debug.info("  All tags/points replaced in all events");
            // done, everything replaced in events
            // replacing tags/points in conditions
            for (String key : pack.getConditions().getConfig().getKeys(false)) {
                Debug.info("    Replacing tags/points in '" + key + "' condition");
                String instruction = pack.getConditions().getConfig().getString(key);
                if (instruction.startsWith("tag ")) {
                    Debug.info("      Found tag condition, replacing the tag");
                    String[] parts = instruction.split(" ");
                    // check if it contains the tag, if not - continue
                    if (parts.length < 2) {
                        Debug.info("      - Could not find tags");
                        continue;
                    }
                    // replace tag
                    if (globalTagList.contains(parts[1])) {
                        String replaced = globalName + "." + parts[1];
                        Debug.info("        Replacing '" + parts[1] + "' with '" + replaced + "'");
                        pack.getConditions().getConfig().set(key,
                                StringUtils.replaceOnce(instruction, parts[1], replaced));
                    }

                } else if (instruction.startsWith("point ")) {
                    Debug.info("      Found point condition, replacing points");
                    String[] parts = instruction.split(" ");
                    // check if the point has defined a category
                    if (parts.length < 2) {
                        Debug.info("      - Could not find the category");
                        continue;
                    }
                    // replace points category
                    if (globalPointList.contains(parts[1])) {
                        String replaced = globalName + "." + parts[1];
                        Debug.info("        Replacing '" + parts[1] + "' with '" + replaced + "'");
                        pack.getConditions().getConfig().set(key,
                                StringUtils.replaceOnce(instruction, parts[1], replaced));
                    }
                } else if (instruction.startsWith("check ")) {
                    Debug.info("      Found check condition, looking for tags and points");
                    String[] parts = instruction.split(" ");
                    for (int j = 0; j < parts.length; j++) {
                        // if the part is beginning of the "tag" instruction
                        // and it contains a tag
                        if (parts[j].equals("^tag") && j + 1 < parts.length) {
                            Debug.info("        There is a tag condition, replacing tags");
                            if (globalTagList.contains(parts[j + 1])) {
                                String replaced = globalName + "." + parts[j + 1];
                                Debug.info("        Replacing '" + parts[j + 1] + "' with '" + replaced + "'");
                                parts[j + 1] = replaced;
                            }
                        } else if (parts[j].equals("^point") && j + 1 < parts.length) {
                            Debug.info("        There is a point condition, replacing points");
                            if (globalTagList.contains(parts[j + 1])) {
                                String replaced = globalName + "." + parts[j + 1];
                                Debug.info("        Replacing '" + parts[j + 1] + "' with '" + replaced + "'");
                                parts[j + 1] = replaced;
                            }
                        }
                    }
                    pack.getConditions().getConfig().set(key, StringUtils.join(Arrays.asList(parts), ' '));
                }
            }
            pack.getConditions().saveConfig();
            Debug.info("  All tags/points replaced in all conditions, time for quest cancelers");
            // done, everything replaced in conditions
            // time for quest cancelers
            for (String key : pack.getMain().getConfig().getConfigurationSection("cancel").getKeys(false)) {
                Debug.info("    Replacing tags/points in '" + key + "' canceler");
                String instruction = pack.getMain().getConfig().getString("cancel." + key);
                String[] parts = instruction.split(" ");
                for (int j = 0; j < parts.length; j++) {
                    if (parts[j].startsWith("tags:")) {
                        String[] localTags = parts[j].substring(5).split(",");
                        for (int k = 0; k < localTags.length; k++) {
                            if (globalTagList.contains(localTags[k])) {
                                String replaced = globalName + "." + localTags[k];
                                Debug.info("      Replaced  tag '" + localTags[k] + "' to '" + replaced + "'");
                                localTags[k] = replaced;
                            }
                        }
                        parts[j] = "tags:" + StringUtils.join(Arrays.asList(localTags), ',');
                    } else if (parts[j].startsWith("points:")) {
                        String[] localPoints = parts[j].substring(5).split(",");
                        for (int k = 0; k < localPoints.length; k++) {
                            if (globalPointList.contains(localPoints[k])) {
                                String replaced = globalName + "." + localPoints[k];
                                Debug.info(
                                        "      Replaced  point '" + localPoints[k] + "' to '" + replaced + "'");
                                localPoints[k] = replaced;
                            }
                        }
                        parts[j] = "points:" + StringUtils.join(Arrays.asList(localPoints), ',');
                    }
                }
                pack.getMain().getConfig().set("cancel." + key, StringUtils.join(Arrays.asList(parts), " "));
            }
            Debug.info("  All tags/points replaced in quest cancelers");
            pack.getMain().saveConfig();
        }
        // done, all packages have replaced tags and points
        Debug.info(
                "Done, all global tags and points are prefixed as global everywhere in every package. Updating the database.");
        for (String packName : tags.keySet()) {
            for (String tag : tags.get(packName)) {
                instance.getSaver().add(
                        new Record(UpdateType.RENAME_ALL_TAGS, new String[] { packName + "." + tag, tag }));
            }
        }
        for (String packName : points.keySet()) {
            for (String point : points.get(packName)) {
                instance.getSaver().add(new Record(UpdateType.RENAME_ALL_POINTS,
                        new String[] { packName + "." + point, point }));
            }
        }
        // remove "tag_point_prefix" option from main.yml files
        for (ConfigPackage pack : Config.getPackages().values()) {
            String packName = pack.getName();
            ConfigAccessor main = pack.getMain();
            main.getConfig().set("tag_point_prefix", null);
            main.saveConfig();
        }
        Debug.info("Done, all cross-package tags and points are now global, the rest is local.");
    } catch (Exception e) {
        e.printStackTrace();
        Debug.error(ERROR);
    }
    Debug.broadcast("Moved all package-less cross-package tags and points to \"" + globalName
            + "\" package (you probably won't notice this change)");
    config.set("version", "v29");
    instance.saveConfig();
}

From source file:pl.betoncraft.betonquest.conversation.InventoryConvIO.java

private ArrayList<String> stringToLines(String singleLine, String color, String prefix) {
     ArrayList<String> multiLine = new ArrayList<>();
     boolean firstLinePrefix = prefix != null;
     if (prefix == null)
         prefix = "";
     String[] lineBreaks = (prefix + singleLine).split("\n");
     for (String brokenLine : lineBreaks) {
         String[] arr = brokenLine.split(" ");
         StringBuilder line = new StringBuilder();
         for (int i = 0; i < arr.length; i++) {
             if (line.length() + arr[i].length() + 1 > 42) {
                 if (firstLinePrefix) {
                     firstLinePrefix = false;
                     multiLine.add(StringUtils.replaceOnce(line.toString().trim(), prefix, prefix + color));
                 } else {
                     multiLine.add(color + line.toString().trim());
                 }//  w  w w .j  av  a2 s. co m
                 line = new StringBuilder();
             }
             line.append(arr[i] + " ");
         }
         if (firstLinePrefix) {
             firstLinePrefix = false;
             multiLine.add(StringUtils.replaceOnce(line.toString().trim(), prefix, prefix + color));
         } else {
             multiLine.add(color + line.toString().trim());
         }
     }
     return multiLine;
 }

From source file:play.modules.accesslog.AccessLogPlugin.java

private synchronized void log() {
    if (!_shouldLog2Play && !_canLog) {
        return;//from  w w  w  .j a  v  a2  s.  c om
    }
    Http.Request request = Http.Request.current();
    Http.Response response = Http.Response.current();

    if (request == null || response == null) {
        return;
    }

    long requestProcessingTime = System.currentTimeMillis() - request.date.getTime();

    Http.Header referrer = request.headers.get(HttpHeaders.Names.REFERER.toLowerCase());
    Http.Header userAgent = request.headers.get(HttpHeaders.Names.USER_AGENT.toLowerCase());

    String bytes = "-";
    String status = "-";

    /* It seems as though the Response.current() is only valid when the request is handled by a controller
       Serving static files, static 404's and 500's etc don't populate the same Response.current()
       This prevents us from getting the bytes sent and response status all of the time
     */
    if (request.action != null && response.out.size() > 0) {
        bytes = String.valueOf(response.out.size());
        status = response.status.toString();
    }

    String line = FORMAT;
    line = StringUtils.replaceOnce(line, "%v", request.host);
    line = StringUtils.replaceOnce(line, "%h", request.remoteAddress);
    line = StringUtils.replaceOnce(line, "%u", (StringUtils.isEmpty(request.user)) ? "-" : request.user);
    line = StringUtils.replaceOnce(line, "%t", request.date.toString());
    line = StringUtils.replaceOnce(line, "%r", request.url);
    line = StringUtils.replaceOnce(line, "%s", status);
    line = StringUtils.replaceOnce(line, "%b", bytes);
    line = StringUtils.replaceOnce(line, "%ref", (referrer != null) ? referrer.value() : "");
    line = StringUtils.replaceOnce(line, "%ua", (userAgent != null) ? userAgent.value() : "");
    line = StringUtils.replaceOnce(line, "%rt", String.valueOf(requestProcessingTime));

    if (_shouldLogPost && request.method.equals("POST")) {
        String body = request.params.get("body");

        if (StringUtils.isNotEmpty(body)) {
            line = StringUtils.replaceOnce(line, "%post", body);
        } else {
            // leave quotes in the logged string to show it was an empty POST request
            line = StringUtils.remove(line, "%post");
        }
    } else {
        line = StringUtils.remove(line, "\"%post\"");
    }

    line = StringUtils.trim(line);

    if (_canLog) {
        _writer.println(line);
    }

    if (_shouldLog2Play) {
        play.Logger.info(line);
    }
}

From source file:tds.itemrenderer.processing.ITSDocumentHelper.java

/**
 * Get manual path replacement (used mostly for local dev work)
 * //  w  w w . ja  va 2s  .  com
 * @param filePath
 * @return
 */
public static String getReplacementPath(String filePath) {
    ReplacementPathElement replacementPath = ITSConfig.getReplacementPath();

    if (replacementPath != null && !StringUtils.isEmpty(replacementPath.getMatch())
            && !StringUtils.isEmpty(replacementPath.getReplacement())) {
        // replace only in the begining. this works because we are using
        // replaceOnce
        if (filePath.startsWith(replacementPath.getMatch()))
            filePath = StringUtils.replaceOnce(filePath, replacementPath.getMatch(),
                    replacementPath.getReplacement());
    }

    return filePath;
}

From source file:util.program.ProgramTextCreator.java

private static void addEntry(ExtendedHTMLDocument doc, StringBuilder buffer, Program prog,
        ProgramFieldType fieldType, boolean createLinks, boolean showHelpLinks, boolean showPersonLinks) {

    try {// w  ww . java 2s .co m
        String text = null;
        String name = fieldType.getLocalizedName();
        int blank = name.indexOf(' ', 16);
        if (blank > 0) {
            name = name.substring(0, blank) + "<br>" + name.substring(blank + 1);
        }
        if (fieldType.getFormat() == ProgramFieldType.TEXT_FORMAT) {
            text = prog.getTextField(fieldType);
            if (ProgramFieldType.SHORT_DESCRIPTION_TYPE == fieldType) {
                text = checkDescription(text);
            }

            // Lazily add short description, but only if it differs from description
            if (fieldType == ProgramFieldType.DESCRIPTION_TYPE) {
                String description = checkDescription(prog.getDescription());
                text = description;

                if (prog.getShortInfo() != null) {
                    StringBuilder shortInfo = new StringBuilder(checkDescription(prog.getShortInfo()).trim());

                    // delete "..." at the end, but only for duplication check, not for display
                    while (shortInfo.toString().endsWith(".")) {
                        shortInfo.deleteCharAt(shortInfo.length() - 1);
                    }

                    if (!description.trim().startsWith(shortInfo.toString())) {
                        addEntry(doc, buffer, prog, ProgramFieldType.SHORT_DESCRIPTION_TYPE, true,
                                showHelpLinks);
                    }
                }
                text = text.replace("\\-", ""); // replace conditional dashes
                text = removeArtificialLineBreaks(text);
                text = HTMLTextHelper.convertTextToHtml(text, createLinks);
                // scan for moderation in beginning of description
                String[] lines = text.split("<br>");
                String[] tags = { "von und mit", "prsentiert von", "mit", "film von", "moderation",
                        "zu gast" };
                for (int i = 0; i < 2; i++) {
                    if (lines.length > i && lines[i].length() < 60) {
                        String line = lines[i];
                        for (String tag : tags) {
                            if (line.toLowerCase().startsWith(tag)
                                    || line.toLowerCase().startsWith(tag + ':')) {
                                String personsString = line.substring(tag.length(), line.length()).trim();
                                if (personsString.startsWith(":")) {
                                    personsString = personsString.substring(1).trim();
                                }
                                if (personsString.endsWith(".")) {
                                    personsString = personsString.substring(0, personsString.length() - 1)
                                            .trim();
                                }
                                String[] persons = personsString.split(" und ");
                                boolean doLink = true;
                                for (String person : persons) {
                                    if (person.isEmpty() || !Character.isLetter(person.charAt(0))
                                            || Character.isLowerCase(person.charAt(0))) {
                                        doLink = false;
                                        break;
                                    }
                                }
                                if (doLink) {
                                    for (String person : persons) {
                                        String[] names = person.split(" ");
                                        int partCount = names.length;
                                        if (partCount >= 2 && partCount < 4) {
                                            for (String n : names) {
                                                if (!StringUtils.isAlpha(n)) {
                                                    doLink = false;
                                                }
                                            }
                                            if (doLink) {
                                                text = StringUtils.replaceOnce(text, person,
                                                        addSearchLink(person));
                                            }
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
            }

        } else if (fieldType.getFormat() == ProgramFieldType.TIME_FORMAT) {
            text = prog.getTimeFieldAsString(fieldType);
        } else if (fieldType.getFormat() == ProgramFieldType.INT_FORMAT) {
            if (fieldType == ProgramFieldType.RATING_TYPE) {
                int value = prog.getIntField(fieldType);
                if (value > -1) {
                    text = new DecimalFormat("##.#").format((double) prog.getIntField(fieldType) / 10) + "/10";
                }
            } else {
                text = prog.getIntFieldAsString(fieldType);
                if (text == null && fieldType == ProgramFieldType.AGE_LIMIT_TYPE) {
                    final String ageRating = prog.getTextField(ProgramFieldType.AGE_RATING_TYPE);
                    if (ageRating != null && !ageRating.isEmpty()) {
                        int age = ProgramUtilities.getAgeLimit(ageRating);
                        if (age >= 0) {
                            text = Integer.toString(age);
                        }
                    }
                }
            }
        }

        if (fieldType == ProgramFieldType.ORIGIN_TYPE) {
            String temp = prog.getIntFieldAsString(ProgramFieldType.PRODUCTION_YEAR_TYPE);
            if (temp != null && temp.trim().length() > 0) {
                if (text == null || text.trim().length() < 1) {
                    name = ProgramFieldType.PRODUCTION_YEAR_TYPE.getLocalizedName();
                    text = temp;
                } else {
                    name += "/<br>" + ProgramFieldType.PRODUCTION_YEAR_TYPE.getLocalizedName();
                    text += " " + temp;
                }
            }
            temp = prog.getIntFieldAsString(ProgramFieldType.LAST_PRODUCTION_YEAR_TYPE);
            if (temp != null && temp.trim().length() > 0) {
                if (text == null || text.trim().length() < 1) {
                    name = ProgramFieldType.LAST_PRODUCTION_YEAR_TYPE.getLocalizedName();
                    text = temp;
                } else {

                    text += " - " + temp;
                }
            }
        }

        if (text == null || text.trim().length() < 1) {
            if (ProgramFieldType.CUSTOM_TYPE == fieldType) {
                text = mLocalizer.msg("noCustom", "No custom information ");
            } else {
                return;
            }
        }

        startInfoSection(buffer, name);

        // add person links
        if (ProgramFieldType.DIRECTOR_TYPE == fieldType || ProgramFieldType.SCRIPT_TYPE == fieldType
                || ProgramFieldType.CAMERA_TYPE == fieldType || ProgramFieldType.CUTTER_TYPE == fieldType
                || ProgramFieldType.MUSIC_TYPE == fieldType || ProgramFieldType.MODERATION_TYPE == fieldType
                || ProgramFieldType.ADDITIONAL_PERSONS_TYPE == fieldType
                || ProgramFieldType.PRODUCER_TYPE == fieldType) {
            if (showPersonLinks && text.length() < 200) {
                // if field is longer, this is probably not a list of names
                if (text.endsWith(".")) {
                    text = text.substring(0, text.length() - 1);
                }
                String[] persons = splitPersons(text);
                for (int i = 0; i < persons.length; i++) {
                    // remove duplicate entries
                    boolean duplicate = false;
                    if (i < persons.length - 1) {
                        for (int j = i + 1; j < persons.length; j++) {
                            if (persons[i].equalsIgnoreCase(persons[j])) {
                                duplicate = true;
                                break;
                            }
                        }
                    }
                    if (duplicate) {
                        text = text.replaceFirst(Pattern.quote(persons[i]), "").trim();
                        if (text.startsWith(",")) {
                            text = text.substring(1).trim();
                        }
                        text = text.replaceAll(",\\s*,", ",");
                        continue;
                    }
                    // a name shall not have more name parts
                    if (persons[i].trim().split(" ").length <= 3) {
                        String link;
                        if (persons[i].contains("(")) {
                            int index = persons[i].indexOf('(');
                            String topic = persons[i].substring(0, index).trim();
                            link = addSearchLink(topic) + " " + persons[i].substring(index).trim();
                        } else {
                            link = addSearchLink(persons[i]);
                        }
                        text = text.replace(persons[i], link);
                    }
                }
            }
            buffer.append(text);
        } else if (ProgramFieldType.DESCRIPTION_TYPE == fieldType) {
            buffer.append(text);
        } else {
            buffer.append(HTMLTextHelper.convertTextToHtml(text, createLinks));
        }

        if ((ProgramFieldType.CUSTOM_TYPE == fieldType) && (showHelpLinks)) {
            buffer.append(" (<a href=\"").append(
                    mLocalizer.msg("customInfo", "http://enwiki.tvbrowser.org/index.php/CustomInformation"))
                    .append("\">?</a>)");
        }
        if ((ProgramFieldType.AGE_RATING_TYPE == fieldType) && (showHelpLinks)) {
            addHelpLink(buffer,
                    mLocalizer.msg("ratingInfo", "http://en.wikipedia.org/wiki/Motion_picture_rating_system"));
        }

        buffer.append("</td></tr>");

        addSeparator(doc, buffer);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}