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.hbc.api.trade.order.service.OrderLogService.java

public List<OrderLog> getMisOrderLog(String orderNo) {
    OrderLogExample example = new OrderLogExample();
    Criteria criteria = example.createCriteria();
    criteria.andOrderNoEqualTo(orderNo);
    criteria.andLogTypeNotEqualTo(LogType.ADD_COMMENTS_MANUALLY.value);
    List<OrderLog> orderLogList = orderLogMapper.selectByExample(example);
    OrderBean orderBean = orderQueryService.getOrderByNo(orderNo);
    for (OrderLog orderLog : orderLogList) {
        if (StringUtils.isNoneBlank(orderLog.getContent())
                && StringUtils.isNoneBlank(orderBean.getGuideName())) {
            String content = StringUtils.replace(orderLog.getContent(), "", orderBean.getGuideName());
            orderLog.setContent(content);
        }//from w  ww .j a  va  2s  .c o  m
    }
    return orderLogList;
}

From source file:io.wcm.handler.url.impl.Externalizer.java

/**
 * Externalizes an URL by applying Sling Mapping. Hostname and scheme are not added because they are added by the
 * link handler depending on site URL configuration and secure/non-secure mode. URLs that are already externalized
 * remain untouched.//from ww  w  .  j  a  v  a2s.  c  om
 * @param url Unexternalized URL (without scheme or hostname)
 * @param resolver Resource resolver
 * @param request Request
 * @return Exernalized URL without scheme or hostname, but with short URLs (if configured in Sling Mapping is
 *         configured), and the path is URL-encoded if it contains special chars.
 */
public static String externalizeUrl(String url, ResourceResolver resolver, SlingHttpServletRequest request) {

    // apply externalization only path part
    String path = url;

    // split off query string or fragment that may be appended to the URL
    String urlRemainder = null;
    int urlRemainderPos = StringUtils.indexOfAny(path, '?', '#');
    if (urlRemainderPos >= 0) {
        urlRemainder = path.substring(urlRemainderPos);
        path = path.substring(0, urlRemainderPos);
    }

    // apply reverse mapping based on current sling mapping configuration for current request
    // e.g. to support a host-based prefix stripping mapping configuration configured at /etc/map

    // please note: the sling map method does a lot of things:
    // 1. applies reverse mapping depending on the sling mapping configuration
    // (this can even add a hostname if defined in sling mapping configuration)
    // 2. applies namespace mangling (e.g. replace jcr: with _jcr_)
    // 3. adds webapp context path if required
    // 4. url-encodes the whole url
    if (request != null) {
        path = resolver.map(request, path);
    } else {
        path = resolver.map(path);
    }

    // remove scheme and hostname (probably added by sling mapping), but leave path in escaped form
    try {
        path = new URI(path).getRawPath();
        // replace %2F back to / for better readability
        path = StringUtils.replace(path, "%2F", "/");
    } catch (URISyntaxException ex) {
        throw new RuntimeException("Sling map method returned invalid URI: " + path, ex);
    }

    // build full URL again
    return path + (urlRemainder != null ? urlRemainder : "");
}

From source file:com.impetus.ankush.common.scripting.impl.ReplaceText.java

public ReplaceText(String targetText, String replacementText, String filePath, boolean createBackUpFile,
        String password) {//from   www  .j a va2  s .c o  m
    this.targetText = StringUtils.replace(targetText, "/", "\\/");
    this.replacementText = StringUtils.replace(replacementText, "/", "\\/");
    this.filePath = filePath;
    this.createBackUpFile = createBackUpFile;
    this.password = password;
    this.addSudoOption = false;
}

From source file:br.com.asisprojetos.email.SendEmail.java

public void enviar(String toEmail[], String subject, String templateFile, List<String> fileNames, String mes,
        int codContrato) {

    try {/*  w w w . j  av a 2 s .  co  m*/

        String htmlFileTemplate = loadHtmlFile(templateFile);

        for (String to : toEmail) {

            String htmlFile = htmlFileTemplate;

            // Create the email message
            HtmlEmail email = new HtmlEmail();
            email.setHostName(config.getHostname());
            email.setSmtpPort(config.getPort());
            email.setFrom(config.getFrom(), config.getFromName()); // remetente
            email.setAuthenticator(
                    new DefaultAuthenticator(config.getAuthenticatorUser(), config.getAuthenticatorPassword()));
            email.setSSL(true);
            email.setSubject(subject); //Assunto

            email.addTo(to);//para

            logger.debug("Enviando Email para : [{}] ", to);

            int i = 1;

            for (String fileName : fileNames) {

                String cid;

                if (fileName.startsWith("diagnostico")) {
                    try {
                        cid = email.embed(new File(String.format("%s/%s", config.getOutDirectory(), fileName)));
                        htmlFile = StringUtils.replace(htmlFile, "$codGraph24$",
                                "<img src=\"cid:" + cid + "\">");
                    } catch (EmailException ex) {
                        logger.error("Arquivo de diagnostico nao encontrado.");
                    }
                } else if (fileName.startsWith("recorrencia")) {
                    try {
                        cid = email.embed(new File(String.format("%s/%s", config.getOutDirectory(), fileName)));
                        htmlFile = StringUtils.replace(htmlFile, "$codGraph25$",
                                "<img src=\"cid:" + cid + "\">");
                    } catch (EmailException ex) {
                        logger.error("Arquivo de recorrencia nao encontrado.");
                    }
                } else {
                    cid = email.embed(new File(String.format("%s/%s", config.getOutDirectory(), fileName)));
                    htmlFile = StringUtils.replace(htmlFile, "$codGraph" + i + "$",
                            "<img src=\"cid:" + cid + "\">");
                    i++;
                }

            }

            //apaga $codGraph$ no usado do template
            for (int t = i; t <= 25; t++) {
                htmlFile = StringUtils.replace(htmlFile, "$codGraph" + t + "$", " ");
            }

            htmlFile = StringUtils.replace(htmlFile, "$MES$", mes);
            htmlFile = StringUtils.replace(htmlFile, "$MAIL$", to);
            htmlFile = StringUtils.replace(htmlFile, "$CONTRATO$", Integer.toString(codContrato));

            email.setHtmlMsg(htmlFile);

            // set the alternative message
            email.setTextMsg("Your email client does not support HTML messages");

            // send the email
            email.send();

        }

        logger.debug("Email enviado com sucesso......");

    } catch (FileNotFoundException ex) {
        logger.error("Arquivo [{}/{}] nao encontrado para leitura.", config.getHtmlDirectory(), templateFile);
    } catch (Exception ex) {
        logger.error("Erro ao Enviar email : {}", ex);
    }

}

From source file:com.sonicle.webtop.core.util.IdentifierUtils.java

/**
 * @deprecated use com.sonicle.commons.IdentifierUtils.getUUIDTimeBased instead
 * @return/*  ww w .j a  va  2  s . co  m*/
 */
@Deprecated
public static synchronized String getUUIDTimeBased(boolean noDashes) {
    final String uuid = Generators.timeBasedGenerator().generate().toString();
    return (noDashes) ? StringUtils.replace(uuid, "-", "") : uuid;
}

From source file:io.wcm.handler.richtext.util.RichTextUtil.java

/**
 * Check if the given formatted text block is empty.
 * A text block containing only one paragraph element and whitespaces is considered as empty.
 * A text block with more than pTreshold characters (raw data) is never considered as empty.
 * @param text XHTML text string (root element not needed)
 * @param treshold Treshold value - only strings with less than this number of characters are checked.
 * @return true if text block is empty/*from   w w  w.j  ava2  s .  c  om*/
 */
public static boolean isEmpty(String text, int treshold) {

    // check if text block is really empty
    if (StringUtils.isEmpty(text)) {
        return true;
    }

    // check if text block has more than 20 chars
    if (text.length() > treshold) {
        return false;
    }

    // replace all whitespaces and nbsp's
    String cleanedText = StringUtils.replace(text, " ", "");
    cleanedText = StringUtils.replace(cleanedText, "&#160;", "");
    cleanedText = StringUtils.replace(cleanedText, "&nbsp;", "");
    cleanedText = StringUtils.replace(cleanedText, "\n", "");
    cleanedText = StringUtils.replace(cleanedText, "\r", "");
    return StringUtils.isEmpty(cleanedText) || "<p></p>".equals(cleanedText);
}

From source file:com.thinkbiganalytics.feedmgr.rest.support.SystemNamingService.java

public static String generateSystemName(String name) {
    //first trim it
    String systemName = StringUtils.trimToEmpty(name);
    if (StringUtils.isBlank(systemName)) {
        return systemName;
    }/*from  w w  w .j a va  2 s .  c om*/
    systemName = systemName.replaceAll(" +", "_");
    systemName = systemName.replaceAll("[^\\w_]", "");

    int i = 0;

    StringBuilder s = new StringBuilder();
    CharacterIterator itr = new StringCharacterIterator(systemName);
    for (char c = itr.first(); c != CharacterIterator.DONE; c = itr.next()) {
        if (Character.isUpperCase(c)) {
            //if it is upper, not at the start and not at the end check to see if i am surrounded by upper then lower it.
            if (i > 0 && i != systemName.length() - 1) {
                char prevChar = systemName.charAt(i - 1);
                char nextChar = systemName.charAt(i + 1);

                if (Character.isUpperCase(prevChar) && (Character.isUpperCase(nextChar)
                        || CharUtils.isAsciiNumeric(nextChar) || '_' == nextChar || '-' == nextChar)) {
                    char lowerChar = Character.toLowerCase(systemName.charAt(i));
                    s.append(lowerChar);
                } else {
                    s.append(c);
                }
            } else if (i > 0 && i == systemName.length() - 1) {
                char prevChar = systemName.charAt(i - 1);
                if (Character.isUpperCase(prevChar) && !CharUtils.isAsciiNumeric(systemName.charAt(i))) {
                    char lowerChar = Character.toLowerCase(systemName.charAt(i));
                    s.append(lowerChar);
                } else {
                    s.append(c);
                }
            } else {
                s.append(c);
            }
        } else {
            s.append(c);
        }

        i++;
    }

    systemName = s.toString();
    systemName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, systemName);
    systemName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_UNDERSCORE, systemName);
    systemName = StringUtils.replace(systemName, "__", "_");
    // Truncate length if exceeds Hive limit
    systemName = (systemName.length() > 128 ? systemName.substring(0, 127) : systemName);
    return systemName;
}

From source file:com.norconex.importer.ImporterTest.java

@Before
public void setUp() throws Exception {
    ImporterConfig config = new ImporterConfig();
    config.setPostParseHandlers(new IDocumentTransformer[] { new IDocumentTransformer() {
        @Override//from   w w w. ja va2  s.c  om
        public void transformDocument(String reference, InputStream input, OutputStream output,
                ImporterMetadata metadata, boolean parsed) throws ImporterHandlerException {
            try {
                // Clean up what we know is extra noise for a given format
                Pattern pattern = Pattern.compile("[^a-zA-Z ]", Pattern.MULTILINE);
                String txt = IOUtils.toString(input);
                txt = pattern.matcher(txt).replaceAll("");
                txt = txt.replaceAll("DowntheRabbitHole", "");
                txt = StringUtils.replace(txt, " ", "");
                txt = StringUtils.replace(txt, "httppdfreebooksorg", "");
                IOUtils.write(txt, output);
            } catch (IOException e) {
                throw new ImporterHandlerException(e);
            }
        }
    } });
    importer = new Importer(config);
}

From source file:cn.vlabs.clb.api.io.impl.ServletOutputStream.java

public void setFileName(String fname) {
    String suffix = MimeType.getSuffix(fname);
    // response.setCharacterEncoding("UTF-8");
    // //  w w  w  .  ja  va 2 s. co m
    response.setContentType(MimeType.getContentType(suffix));
    try {
        // ???
        if (isFirefox(agent))
            fname = javax.mail.internet.MimeUtility.encodeText(fname, "UTF-8", "B");
        else if (isIE(agent)) {
            String codedFname = URLEncoder.encode(fname, "UTF-8");
            codedFname = StringUtils.replace(codedFname, "+", "%20");
            if (codedFname.length() > 150) {
                codedFname = new String(fname.getBytes("GBK"), "ISO8859-1");
            }
            fname = codedFname;
        } else
            fname = URLEncoder.encode(fname, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fname + "\"");
    } catch (UnsupportedEncodingException e) {
    }
}

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

/**
 * Resolve skin link./*from www . j a  v a 2  s  .  c om*/
 *
 * @param wikiContext the wiki context
 * @param path the path
 * @return the string
 */
public static String resolveSkinLink(GWikiContext wikiContext, String path) {
    int idx = path.indexOf("{SKIN}/");
    if (idx == -1) {
        return path;
    }
    String skin = wikiContext.getSkin();
    String rurl = StringUtils.replace(path, "{SKIN}", skin);
    if (rurl.startsWith("/") == true) {
        rurl = rurl.substring(1);
    }
    if (rurl.startsWith("static/") == true) {
        if (GWikiServlet.INSTANCE == null) {
            return rurl;
        }
        if (GWikiServlet.INSTANCE.hasStaticResource(rurl, wikiContext) == true) {
            return rurl;
        }
        rurl = StringUtils.replace(path, "{SKIN}/", "");
        return rurl;
    } else {
        if (wikiContext.getWikiWeb().findElementInfo(rurl) != null) {
            return rurl;
        }
        rurl = StringUtils.replace(path, "{SKIN}/", "");
        return rurl;
    }
}