Example usage for org.apache.commons.lang3 StringUtils replace

List of usage examples for org.apache.commons.lang3 StringUtils replace

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils replace.

Prototype

public static String replace(final String text, final String searchString, final String replacement) 

Source Link

Document

Replaces all occurrences of a String within another String.

A null reference passed to this method is a no-op.

 StringUtils.replace(null, *, *)        = null StringUtils.replace("", *, *)          = "" StringUtils.replace("any", null, *)    = "any" StringUtils.replace("any", *, null)    = "any" StringUtils.replace("any", "", *)      = "any" StringUtils.replace("aba", "a", null)  = "aba" StringUtils.replace("aba", "a", "")    = "b" StringUtils.replace("aba", "a", "z")   = "zbz" 

Usage

From source file:com.nridge.ds.solr.SolrTransform.java

/**
 * Applies HTML highlight substitution logic to document fields
 * in the response table./*w  w w . j a  va2 s  . co m*/
 *
 * @param aSolrDocument Solr document instance.
 */
public void applyHTMLHighlights(Document aSolrDocument) {
    String fieldValue, begValue, endValue;
    Logger appLogger = mAppMgr.getLogger(this, "applyHTMLHighlights");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    String begToken = getCfgString("highlight_beg_token");
    String endToken = getCfgString("highlight_end_token");
    if ((StringUtils.isNotEmpty(begToken)) && (StringUtils.isNotEmpty(endToken))) {
        String begHTML = getCfgString("highlight_beg_html");
        String endHTML = getCfgString("highlight_end_html");
        String[] fieldNames = getCfgStrings("highlight_field_name");
        if ((StringUtils.isNotEmpty(begHTML)) && (StringUtils.isNotEmpty(endHTML)) && (fieldNames.length > 0)) {
            if (Solr.isResponsePopulated(aSolrDocument)) {
                if (Solr.isHeaderPopulated(aSolrDocument)) {
                    DataBag headerBag = Solr.getHeader(aSolrDocument);
                    if (headerBag.isValueTrue("is_highlighted")) {
                        DataTable docTable = Solr.getResponse(aSolrDocument);
                        int rowCount = docTable.rowCount();
                        for (int row = 0; row < rowCount; row++) {
                            for (String fieldName : fieldNames) {
                                fieldValue = docTable.getValueByName(row, fieldName);
                                begValue = StringUtils.replace(fieldValue, begToken, begHTML);
                                endValue = StringUtils.replace(begValue, endToken, endHTML);
                                docTable.setValueByName(row, fieldName, endValue);
                            }
                        }
                    }
                }
            }
        }
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:de.micromata.genome.gwiki.page.GWikiContext.java

/**
 * Gets the page id from title./*www .  ja v  a  2  s  .c  o m*/
 *
 * @param title the title
 * @return the page id from title
 */
public static String getPageIdFromTitle(String title) {
    String id = StringUtils.replace(StringUtils.replace(StringUtils.replace(title, "\t", "_"), " ", "_"), "\\",
            "/");
    id = NormalizeUtils.normalizeToPath(id);
    return id;
}

From source file:de.micromata.genome.logging.spi.ifiles.IndexedWriter.java

private void writeLongValue(String value) throws IOException {

    String rest = StringUtils.replace(value, "\r", "");
    int nlidx = rest.indexOf('\n');
    if (nlidx == -1) {
        logWriter.write(value);//  ww w .j  a v a  2 s . c  om
        logWriter.write("\n");
        return;
    }
    boolean firstLine = true;
    while (nlidx != -1) {
        String left = rest.substring(0, nlidx + 1);
        if (firstLine == false) {
            logWriter.write('\t');
        }
        logWriter.write(left);
        rest = rest.substring(nlidx + 1);
        nlidx = rest.indexOf('\n');
        firstLine = false;
    }
    if (rest.length() > 0) {
        logWriter.write('\t');
        logWriter.write(rest);
        logWriter.write('\n');
    }
}

From source file:com.github.binlee1990.spider.video.spider.PersonCrawler.java

private void setVideoScore(Document doc, Video video) {
    Elements sElements = doc.select("div#video_review td.text span.score");
    if (CollectionUtils.isNotEmpty(sElements)) {
        String score = sElements.first().text().toString();
        score = StringUtils.replace(score, "(", "");
        score = StringUtils.replace(score, ")", "");
        if (StringUtils.isNotBlank(score)) {
            try {
                video.setScore(Float.valueOf(score));
            } catch (Exception e) {
            }/*from  w w w  . ja  v a2s. c  om*/
        }
    }
}

From source file:io.wcm.tooling.commons.contentpackagebuilder.ContentPackage.java

/**
 * Read template file from classpath, replace variables and store it in the zip stream.
 * @param path Path//www .j av a2s. c  om
 * @throws IOException
 */
private void buildTemplatedMetadataFile(String path) throws IOException {
    try (InputStream is = getClass().getResourceAsStream("/content-package-template/" + path)) {
        String xmlContent = IOUtils.toString(is);
        for (Map.Entry<String, Object> entry : metadata.getVars().entrySet()) {
            xmlContent = StringUtils.replace(xmlContent, "{{" + entry.getKey() + "}}",
                    StringEscapeUtils.escapeXml(entry.getValue().toString()));
        }
        zip.putNextEntry(new ZipEntry(path));
        try {
            zip.write(xmlContent.getBytes(Charsets.UTF_8));
        } finally {
            zip.closeEntry();
        }
    }
}

From source file:com.sonicle.webtop.mail.SaxHTMLMailParser.java

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException {
    if (lastComment != null) {
        pwriter.print("<!--" + lastComment + "-->");
        lastComment = null;/* ww  w  .  j a v  a 2 s . c  o  m*/
    }

    if (qName.equalsIgnoreCase("html")) {
        inhtml = true;
        return;
    }
    if (!inhtml) {
        return;
    }

    //store body attributes
    if (qName.equalsIgnoreCase("body")) {
        body.setData(attributes);

    }

    //filter out any script element
    if (qName.equalsIgnoreCase("script")) {
        isscript = true;
        return;
    }

    if (!isbody) {
        /*if(!isscript&&qName.equalsIgnoreCase("script")) {
        isscript=true;
        }*/
        if (baseUrl == null && qName.equalsIgnoreCase("base")) {
            baseUrl = attributes.getValue("href");
            if (baseUrl != null) {
                if (baseUrl.toLowerCase().startsWith("file:")) {
                    baseUrl = null;
                    return;
                } else if (baseUrl.charAt(baseUrl.length() - 1) != '/') {
                    int bx = baseUrl.lastIndexOf('/');
                    int dx = baseUrl.lastIndexOf('.');
                    if (dx > bx) {
                        baseUrl = baseUrl.substring(0, bx + 1); //take off any wrong file spec at the end
                    } else {
                        baseUrl += "/"; //or append a slash
                    }
                }
            }
        }
    }

    if (justBody) {
        if (!isbody) {
            if (qName.equalsIgnoreCase("body")) {
                isbody = true;
                return;
            } else if (qName.equalsIgnoreCase("style")) {
                isstyle = true;
            } else {
                return;
            }
        }
    } else if (qName.equalsIgnoreCase("style")) {
        isstyle = true;
    }

    boolean islink = false;
    boolean ismailto = false;
    boolean changedTarget = false;
    String mailtoParams = null;
    if (qName.equalsIgnoreCase("a")) {
        islink = true;

    }
    pwriter.print("<" + qName);
    int len = attributes.getLength();
    for (int i = 0; i < len; ++i) {
        String aqname = attributes.getQName(i);
        String avalue = attributes.getValue(i);
        String laqname = aqname.toLowerCase();
        boolean isdataimg = laqname.equals("src") && (avalue.startsWith("data:") || avalue.startsWith("DATA:"));
        if (!isdataimg) {
            String lavalue = avalue.toLowerCase();
            if (laqname.endsWith("src") || laqname.equals("background")) {
                //clear any source calling /
                if (avalue.startsWith("#")) {
                    avalue = "";
                } else if (avalue.toLowerCase().startsWith("cid:")) {
                    avalue = evaluateCid(avalue);
                } else {
                    avalue = evaluateUrl(avalue);
                }
            } else if (laqname.equals("target")) {
                avalue = "_new";
                changedTarget = true;
            } else if (laqname.equals("href") && lavalue.startsWith("mailto:")) {
                mailtoParams = lavalue.substring(7);
                avalue = "#";
                ismailto = true;
            }
        }
        pwriter.print(" " + aqname + "=\"" + StringUtils.replace(avalue, "\"", "&quot;") + "\"");
    }
    if (ismailto) {
        String email = mailtoParams;
        String sparams = "\"" + email + "\"";
        int ix = mailtoParams.indexOf("?");
        if (ix > 0) {
            email = mailtoParams.substring(0, ix);
            mailtoParams = mailtoParams.substring(ix + 1);
            Map<String, String> params = getQueryMap(mailtoParams);
            String subject = params.get("subject");
            String body = params.get("body");
            if (subject == null)
                subject = "";
            if (body == null)
                body = "";
            sparams = "\"" + email + "\",\"" + subject + "\",\"" + body + "\"";
        }
        pwriter.print(" onclick='parent.WT.handleMailAddress(" + sparams + "); return false;'");
    } else if (islink && !changedTarget) {
        pwriter.print(" target=_new");
    }
    pwriter.print(">");
    pwriter.flush();
}

From source file:net.ontopia.topicmaps.nav.context.ThemeCategorizer.java

/**
 * Generate a ordered list of theme classes.
 * Use template strings to render result string, this approach
 * is used by the navigator framework 2nd generation.
 * Note: In every theme class there are at least one theme.
 *///from   w  w w  . j av a2 s.c  o  m
public String generateThemeList(HashMap themeClassMap, Collection selectedThemes, String templThemeClass,
        String templTheme, String templSelectedTheme) {
    if (themeClassMap == null || templThemeClass == null || templTheme == null)
        return "";
    if (templSelectedTheme == null)
        templSelectedTheme = "";

    StringBuilder strBuf = new StringBuilder();

    // ----- loop over all themes classes
    List themeClassList = new ArrayList(themeClassMap.keySet());
    Collections.sort(themeClassList, lexicalComparator);
    Iterator itThemeClasses = themeClassList.iterator();
    String actThemeClass;

    HashSet actSet;
    List themeList;
    Iterator itRelThemes;
    TopicIF actTheme;
    String tmp;

    while (itThemeClasses.hasNext()) {
        actThemeClass = (String) itThemeClasses.next();
        actSet = (HashSet) themeClassMap.get(actThemeClass);

        // only proceed if category name has related themes
        if (actSet.size() > 0) {
            // -- append string representation for theme class
            strBuf.append(StringUtils.replace(templThemeClass, "%className%", actThemeClass));

            themeList = new ArrayList(actSet);
            Collections.sort(themeList, topicComparator);
            itRelThemes = themeList.iterator();
            while (itRelThemes.hasNext()) {
                actTheme = (TopicIF) itRelThemes.next();
                // a: replace theme name
                tmp = StringUtils.replace(templTheme, "%themeName%", stringifier.toString(actTheme));
                // b: replace theme id
                tmp = StringUtils.replace(tmp, "%themeId%", actTheme.getObjectId());
                // c: if selected, replace selected template
                if (selectedThemes != null && selectedThemes.contains(actTheme))
                    tmp = StringUtils.replace(tmp, "%selected%", templSelectedTheme);
                else
                    tmp = StringUtils.replace(tmp, "%selected%", "");

                // -- append string representation for theme
                strBuf.append(tmp);

            } // while itRelThemes
        }

    } // while itThemeClasses

    return strBuf.toString();
}

From source file:de.ks.file.FileViewController.java

@Override
public void duringSave(FileContainer<?> model) {
    fileReferences.keySet().retainAll(files);
    if (this.fileReferences.isEmpty()) {
        log.info("No files to save for {}", model);
    }/* ww w . j  a va 2  s  .co m*/
    this.fileReferences.entrySet().forEach(entry -> {
        try {
            File file = entry.getKey();
            CompletableFuture<FileReference> cf = entry.getValue();
            FileReference fileReference = cf.get();
            model.getFiles().remove(fileReference);
            model.addFileReference(PersistentWork.reload(fileReference));//ensure it is saved
            if (fileReference.getId() > 0) {
                return;
            }
            fileStore.scheduleCopy(fileReference, file);

            String search = "file:///" + file.getAbsolutePath();
            String replacement = FileReference.FILESTORE_VAR + fileReference.getMd5Sum() + File.separator
                    + file.getName();
            String newDescription = StringUtils.replace(model.getDescription(), search, replacement);
            model.setDescription(newDescription);
            log.info("Adding file reference {}", fileReference);

            PersistentWork.persist(fileReference);
        } catch (InterruptedException | ExecutionException e) {
            log.error("Could not get fileReference for file {}", entry.getKey());
            throw new RuntimeException(e);
        }
    });
}

From source file:io.kahu.hawaii.util.call.sql.DbRequestBuilderRepository.java

private DbRequestPrototype createPrototype(String directory, String name) {
    try {/*from   w w  w  .jav  a  2  s.  c  o m*/
        String n = StringUtils.replace(name, ".sql", "");
        String sql = queryService.getSqlQuery(directory, n);
        String system = directory.substring("/sql/".length());
        system = system.replaceAll("/", "");
        RequestContext context = new RequestContext(system, n);
        return new DbRequestPrototype(prototype.getRequestDispatcher(), context, null, prototype.getLogger(),
                prototype.getDataSource(), getCallType(sql), sql);
    } catch (ServerException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.thruzero.common.core.infonode.builder.utils.SampleNodeBuilderUtils.java

public static String normalize(String elements) {
    StringBuilder result = new StringBuilder();
    elements = StringUtils.replace(elements, "\r", "");
    elements = StringUtils.replace(elements, "\n", "");
    StringTokenizer st = new StringTokenizer(elements, " ");

    while (st.hasMoreTokens()) {
        String token = st.nextToken();

        result.append(StringUtils.trimToEmpty(token));
    }//from   w w  w .  j av  a2s  .  c  om

    return result.toString();
}