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:de.micromata.genome.gdbfs.FileSystemUtils.java

/**
 * Normalize zip name.//from ww w. j  a v  a  2  s .c  o  m
 *
 * @param name the name
 * @return the string
 */
public static String normalizeZipName(String name) {
    String s = StringUtils.replace(name, "\\", "/");
    if (s.startsWith("/") == true) {
        return s.substring(1);
    }
    return s;
}

From source file:io.gs2.AbstractGs2Client.java

/**
 * DELETE?/* w  w  w.jav a 2  s .c o m*/
 * 
 * @param url URL
 * @param credential ?
 * @param service 
 * @param module 
 * @param function 
 * @return 
 */
protected HttpDelete createHttpDelete(String url, IGs2Credential credential, String service, String module,
        String function) {
    Long timestamp = System.currentTimeMillis() / 1000;
    url = StringUtils.replace(url, "{service}", service);
    url = StringUtils.replace(url, "{region}", region.getName());
    HttpDelete delete = new HttpDelete(url);
    delete.setHeader("Content-Type", "application/json");
    credential.authorized(delete, service, module, function, timestamp);
    return delete;
}

From source file:de.micromata.genome.gwiki.controls.GWikiTreeChildrenActionBean.java

private JsonObject buildNodeInfo(GWikiElementInfo ei, SearchType searchType) {
    if (wikiContext.getWikiWeb().getAuthorization().isAllowToView(wikiContext, ei) == false) {
        return null;
    }//from  w  w  w .ja va2 s  . c o m
    JsonObject ret = new JsonObject();

    String title = ei.getTitle();
    if (ei.getTitle().startsWith("I{") == true) {
        title = wikiContext.getTranslatedProp(title);
    }
    if (StringUtils.isBlank(title) == true) {
        return null;
    }
    List<GWikiElementInfo> childs = wikiContext.getElementFinder().getAllDirectChildsSorted(ei);

    JsonArray childNodes = JsonBuilder.array();
    for (GWikiElementInfo sid : childs) {
        JsonObject subnode = buildNodeInfo(sid, searchType);
        if (subnode != null) {
            childNodes.add(subnode);
        }
    }
    SearchType st = SearchType.fromElementInfo(wikiContext, ei);
    boolean match = searchType.matches(st);
    if (match == false && childNodes.size() == 0) {
        return null;
    }

    ret.add("children", childNodes);
    JsonObject data = new JsonObject();
    ret.add("data", data);
    if (!match) {
        ret.add("state", JsonBuilder.map("disabled", "true"));
    }
    data.add("url", ei.getId());
    ret.add("id", StringUtils.replace(ei.getId(), "/", "_"));
    //    ret.add("id", ei.getId());
    String targetLink = wikiContext.localUrl(ei.getId());

    //    data.add("url", targetLink);
    String eltype = st.getElmentJsonType();
    data.add("type", eltype);
    ret.add("type", eltype);
    data.add("matchtype", match);

    data.add("title", title);
    ret.add("text", title);
    return ret;
}

From source file:com.mirth.connect.plugins.datatypes.hl7v2.ER7Serializer.java

@Override
public String transformWithoutSerializing(String message, MessageSerializer outboundSerializer)
        throws MessageSerializerException {
    try {//  w ww  .  ja  v a  2  s  .  c  o m
        boolean transformed = false;
        ER7Serializer serializer = (ER7Serializer) outboundSerializer;
        String outputSegmentDelimiter = serializer.getDeserializationSegmentDelimiter();

        if (serializationProperties.isConvertLineBreaks()) {
            if (skipIntermediateDelimiter) {
                /*
                 * When convert line breaks is on and transform without serializing is called,
                 * ordinarily line breaks would be converted to the serialization delimiter,
                 * then the
                 * serialization delimiter would be converted to the deserialization delimiter.
                 * In this
                 * case, we can skip a step by simply converting line breaks to the
                 * deserialization
                 * delimiter if the serialization delimiter is also a line break.
                 */
                return StringUtil.convertLineBreaks(message, outputSegmentDelimiter);
            }

            message = StringUtil.convertLineBreaks(message, serializationSegmentDelimiter);
            transformed = true;
        }

        if (!serializationSegmentDelimiter.equals(outputSegmentDelimiter)) {
            message = StringUtils.replace(message, serializationSegmentDelimiter, outputSegmentDelimiter);
            transformed = true;
        }

        if (transformed) {
            return message;
        }
    } catch (Exception e) {
        throw new MessageSerializerException("Error transforming ER7", e, ErrorMessageBuilder
                .buildErrorMessage(this.getClass().getSimpleName(), "Error transforming ER7", e));
    }

    return null;
}

From source file:de.ks.text.AsciiDocParser.java

private String copyFiles(String parse, File dataDir) throws IOException {
    Pattern pattern = Pattern.compile("\"file:.*\"");
    Matcher matcher = pattern.matcher(parse);
    int bodyTag = parse.indexOf("<body");
    Map<String, String> replacements = new HashMap<>();
    while (matcher.find()) {
        int start = matcher.start();
        if (start < bodyTag) {
            continue;
        }//from w w w . j  a  v a  2s.c o  m
        int end = matcher.end();

        String fileReference = parse.substring(start + 1, end - 1);
        end = fileReference.indexOf("\"");
        fileReference = fileReference.substring(0, end);

        log.debug("Found file reference {}", fileReference);

        URI uri = URI.create(fileReference.replace('\\', '/'));
        File sourceFile = new File(uri);
        File targetFile = new File(dataDir, sourceFile.getName());
        java.nio.file.Files.copy(sourceFile.toPath(), targetFile.toPath());

        replacements.put(fileReference, dataDir.getName() + "/" + targetFile.getName());
    }

    for (Map.Entry<String, String> entry : replacements.entrySet()) {
        String original = entry.getKey();
        String replacement = entry.getValue();
        parse = StringUtils.replace(parse, original, replacement);
    }
    return parse;
}

From source file:de.micromata.genome.gwiki.page.search.expr.SearchUtils.java

private static String enrich(String text, List<String> words) {
    text = WebUtils.escapeHtml(text);//  www.  j  av a  2  s.c  o  m
    text = StringUtils.replace(text, "\n", "<br/>\n");
    for (String w : words) {
        text = enrichFoundWord(text, w);
        // text = StringUtils.replace(text, w, "<b><strong><big>" + w + "</big></strong></b>");
    }
    return text;
}

From source file:com.zextras.modules.chat.server.operations.XmppSASLAuthentication.java

protected void parseAuthString(String encodeAuthString, XmppSession session) {
    byte[] auth;//  w  w  w  .j a v  a2 s. c om
    try {
        auth = Base64.decodeBase64(encodeAuthString.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    String plainSaslAuth = new String(auth);
    plainSaslAuth = StringUtils.replace(plainSaslAuth, "\\40", "@");
    String[] tokens = StringUtils.split(plainSaslAuth, '\0');

    if (tokens.length < 3) {
        mUsername = tokens[0];
        mPassword = tokens[1];
    } else {
        mUsername = tokens[1];
        mPassword = tokens[2];
    }

    if (!mUsername.contains("@")) {
        mUsername += '@' + session.getDomain();
    }
}

From source file:com.norconex.commons.lang.url.URLNormalizer.java

/**
 * Create a new <code>URLNormalizer</code> instance.
 * @param url the url to normalize/*from  w w  w .  j a  v a 2s . c  om*/
 */
public URLNormalizer(String url) {
    super();
    // make sure URL is valid
    String fixedURL = url;
    try {
        if (StringUtils.contains(fixedURL, " ")) {
            LOG.warn("URL syntax is invalid as it contains space "
                    + "character(s). Replacing them with %20. URL: " + url);
            fixedURL = StringUtils.replace(fixedURL, " ", "%20");
        }
        new URI(fixedURL);
    } catch (URISyntaxException e) {
        throw new URLException("Invalid URL syntax: " + url, e);
    }
    if (!CharEncoding.isSupported(CharEncoding.UTF_8)) {
        throw new URLException("UTF-8 is not supported by your system.");
    }
    this.url = fixedURL.trim();
}

From source file:com.google.dart.java2dart.util.JavaUtils.java

/**
 * @return the JDT signature type name for given "human" type name.
 *//*w  w  w  .  ja va 2s . co m*/
public static String getJdtTypeName(String name) {
    if ("boolean".equals(name)) {
        return "Z";
    }
    if ("byte".equals(name)) {
        return "B";
    }
    if ("char".equals(name)) {
        return "C";
    }
    if ("double".equals(name)) {
        return "D";
    }
    if ("float".equals(name)) {
        return "F";
    }
    if ("int".equals(name)) {
        return "I";
    }
    if ("long".equals(name)) {
        return "J";
    }
    if ("short".equals(name)) {
        return "S";
    }
    if ("void".equals(name)) {
        return "V";
    }
    return "L" + StringUtils.replace(name, ".", "/") + ";";
}

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

@Override
public void visit(Page page) {
    int docid = page.getWebURL().getDocid();
    String url = page.getWebURL().getURL();

    logger.info(url);//  w w w.j  av  a  2 s .  co m
    if (!url.startsWith("http://www.javlibrary.com/cn/?v=jav")) {
        return;
    }

    if (page.getParseData() instanceof HtmlParseData) {
        HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
        String html = htmlParseData.getHtml();

        Document doc = Jsoup.parse(html);

        String videoIdentificationCode = doc.select("div#video_id td.text").first().text().toString();
        Video queryVideo = new Video();
        queryVideo.setIdentificationCode(videoIdentificationCode);
        Video video = videoMapper.queryByVideo(queryVideo);

        if (null != video) {
            return;
        }

        video = new Video();
        video.setUrl(url);

        Date now = new Date();
        video.setCreateTime(now);
        video.setUpdateTime(now);

        String title = doc.select("div#video_title a").first().text().toString();
        video.setTitle(title);

        video.setIdentificationCode(videoIdentificationCode);

        Elements rdElements = doc.select("div#video_date td.text");
        if (CollectionUtils.isNotEmpty(rdElements)) {
            String releaseDate = rdElements.first().text().toString();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date = sdf.parse(releaseDate);
                video.setReleaseDate(date);
            } catch (ParseException e) {
            }
        }

        Elements dmElements = doc.select("div#video_length span.text");
        if (CollectionUtils.isNotEmpty(dmElements)) {
            String durationMinutes = dmElements.first().text().toString();
            video.setDurationMinutes(Integer.valueOf(durationMinutes));
        }

        Elements dElements = doc.select("div#video_director td.text");
        if (CollectionUtils.isNotEmpty(dElements)) {
            String director = dElements.first().text().toString();
            video.setDirector(director);
        }

        Elements pElements = doc.select("div#video_maker td.text");
        if (CollectionUtils.isNotEmpty(pElements)) {
            String producer = pElements.first().text().toString();
            video.setProducer(producer);
        }

        Elements disElements = doc.select("div#video_label td.text");
        if (CollectionUtils.isNotEmpty(disElements)) {
            String distributor = disElements.first().text().toString();
            video.setDistributor(distributor);
        }

        Elements countElements = doc.select("div#video_favorite_edit span");
        if (CollectionUtils.isNotEmpty(countElements)) {
            Elements countWantedElements = countElements.select("#subscribed a");
            if (CollectionUtils.isNotEmpty(countWantedElements)) {
                String countWanted = countWantedElements.first().text();
                try {
                    video.setCountWanted(Integer.valueOf(countWanted));
                } catch (Exception e) {
                }
            }

            Elements countWatchedElements = countElements.select("#watched a");
            if (CollectionUtils.isNotEmpty(countWatchedElements)) {
                String countWatched = countWatchedElements.first().text();
                try {
                    video.setCountWatched(Integer.valueOf(countWatched));
                } catch (Exception e) {
                }
            }

            Elements countOwnedElements = countElements.select("#owned a");
            if (CollectionUtils.isNotEmpty(countOwnedElements)) {
                String countOwned = countOwnedElements.first().text();
                try {
                    video.setCountOwned(Integer.valueOf(countOwned));
                } catch (Exception e) {
                }
            }
        }

        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) {
                }
            }
        }

        Elements actressElements = doc.select("div#video_cast span.star");
        if (CollectionUtils.isNotEmpty(actressElements)) {
            if (actressElements.size() <= 1) {
                video.setSingleFemaleFlag(true);
            } else {
                video.setSingleFemaleFlag(false);
            }
        }

        videoMapper.insertSelective(video);
        int videoId = videoMapper.queryByVideo(video).getId();

        logger.info("handle " + videoId + "\n" + JSON.toJSONString(video));

        if (CollectionUtils.isNotEmpty(actressElements)) {
            actressElements.stream().forEach(a -> {
                String aName = a.text().toString().trim();

                if (StringUtils.isNotBlank(aName)) {
                    Actress queryActress = new Actress();
                    queryActress.setName(aName);
                    Actress actress = actressMapper.queryByActress(queryActress);
                    if (null != actress) {
                        VideoActress va = new VideoActress();
                        va.setActressCode(actress.getCode());
                        va.setVideoId(videoId);
                        videoActressMapper.insertSelective(va);
                    } else {
                        actress = new Actress();
                        actress.setName(aName);
                        actressMapper.insertSelective(actress);
                        int actressId = actressMapper.queryByActress(actress).getId();

                        VideoActress va = new VideoActress();
                        va.setActressCode(actress.getCode());
                        va.setVideoId(videoId);
                        videoActressMapper.insertSelective(va);
                    }
                }
            });
        }

        Elements categoryElements = doc.select("div#video_genres span.genre");
        if (CollectionUtils.isNotEmpty(categoryElements)) {
            categoryElements.stream().forEach(c -> {
                String cDescription = c.text().toString().trim();

                if (StringUtils.isNotBlank(cDescription)) {
                    Category queryCategory = new Category();
                    queryCategory.setSubtype(cDescription);
                    Category category = categoryMapper.queryByCategory(queryCategory);
                    if (null != category) {
                        VideoCategory vc = new VideoCategory();
                        vc.setCategoryId(category.getId());
                        vc.setCategoryDescription(category.getSubtype());
                        vc.setVideoId(videoId);
                        videoCategoryMapper.insertSelective(vc);
                    } else {
                        category = new Category();
                        category.setSubtype(cDescription);
                        categoryMapper.insertSelective(category);
                        int categoryId = categoryMapper.queryByCategory(category).getId();

                        VideoCategory vc = new VideoCategory();
                        vc.setCategoryId(categoryId);
                        vc.setCategoryDescription(category.getSubtype());
                        vc.setVideoId(videoId);
                        videoCategoryMapper.insertSelective(vc);
                    }
                }
            });
        }
    }
}