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.sonicle.webtop.vfs.VfsServiceSettings.java

public String getStoreFileBasepath(StoreFileBasepathTemplateValues tpl) {
    String value = getString(STORE_FILE_BASEPATH, null);
    value = StringUtils.replace(value, "{SERVICE_ID}", tpl.SERVICE_ID);
    value = StringUtils.replace(value, "{DOMAIN_ID}", tpl.DOMAIN_ID);
    return PathUtils.ensureTrailingSeparator(value);
}

From source file:com.monarchapis.driver.jaxrs.common.Swagger12DocumentationResource.java

/**
 * Attempts to load the pre-generated resource listings file, set the base
 * URI, and return the JSON as a string.
 * /*from   ww w .j a v  a 2s.  com*/
 * @param version
 *            The version from the path
 * @param uriInfo
 *            The URI info for determining the base URI
 * @return the resource listing JSON.
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getResourceListing(@PathParam("version") String version, @Context UriInfo uriInfo) {
    try {
        InputStream is = getClass().getResourceAsStream(SWAGGER_DOC_ROOT + version + "/resource-listing.json");

        if (is == null) {
            throw new NotFoundException();
        }

        String json = IOUtils.toString(is);
        json = StringUtils.replace(json, "${apiBasePath}", getBaseUri(uriInfo));
        json = insertEndpoints(json);

        return json;
    } catch (Exception e) {
        log.error("Could not get swagger documentation.", e);
        throw new NotFoundException();
    }
}

From source file:com.thruzero.common.core.strategy.KeyValuePairSubstitutionStrategy.java

/**
 * Using the provided list of name/value pairs, search and replace all matching substitution variables, in the given
 * {@code source} string, with their associated values.
 *///from w w w  .ja v a  2 s  .c om
@Override
public String replaceAll(final String source) {
    String result = source;

    for (KeyValuePair keyValuePair : substitutionSpecs) {
        result = StringUtils.replace(result, namePrefix + keyValuePair.getKey() + nameSuffix,
                keyValuePair.getValueAsString());
    }

    return result;
}

From source file:egovframework.com.utl.wed.filter.DefaultFileSaveManager.java

@Override
public String saveFile(FileItem fileItem, String imageBaseDir, String imageDomain) {
    String originalFileName = FilenameUtils.getName(fileItem.getName());
    String relUrl;//from  ww  w .  ja  va2  s  .  c  om
    // filename
    String subDir = File.separator + DirectoryPathManager
            .getDirectoryPathByDateType(DirectoryPathManager.DIR_DATE_TYPE.DATE_POLICY_YYYY_MM);
    String fileName = RandomStringUtils.randomAlphanumeric(20) + "."
            + StringUtils.lowerCase(StringUtils.substringAfterLast(originalFileName, "."));

    File newFile = new File(imageBaseDir + subDir + fileName);
    File fileToSave = DirectoryPathManager.getUniqueFile(newFile.getAbsoluteFile());

    try {
        FileUtils.writeByteArrayToFile(fileToSave, fileItem.get());
    } catch (IOException e) {
        e.printStackTrace();
    }

    String savedFileName = FilenameUtils.getName(fileToSave.getAbsolutePath());
    relUrl = StringUtils.replace(subDir, "\\", "/") + savedFileName;

    return imageDomain + relUrl;
}

From source file:com.epam.dlab.core.parser.ConditionEvaluate.java

/** Instantiate the engine to evaluate condition. 
 * @param columnNames the list of column names.
 * @param condition condition for filtering data.
 * @throws InitializationException/*from   www. j  a  va 2s  .com*/
 */
public ConditionEvaluate(List<String> columnNames, String condition) throws InitializationException {
    //Replace : to . in column names
    List<String> colNames = new ArrayList<>(columnNames.size());
    for (int i = 0; i < columnNames.size(); i++) {
        String name = columnNames.get(i);
        if (name.indexOf(':') > -1 && condition.indexOf(name) > -1) {
            String newName = StringUtils.replaceChars(name, ':', '.');
            colNames.add(newName);
            condition = StringUtils.replace(condition, name, newName);
        } else {
            colNames.add(name);
        }
    }

    try {
        JexlEngine engine = new JexlBuilder().strict(true).silent(false).debug(true).create();
        expression = (Script) engine.createExpression(condition);
        jexlContext = new MapContext();
    } catch (Exception e) {
        throw new InitializationException(
                "Cannot initialize JEXL engine for condition: " + condition + ". " + e.getLocalizedMessage(),
                e);
    }

    // Create mapping of columns for evaluations. 
    List<String> names = new ArrayList<>();
    List<Integer> indexes = new ArrayList<>();
    for (List<String> variableList : expression.getVariables()) {
        String columnName = StringUtils.join(variableList, '.');
        int index = getColumnIndex(colNames, columnName);
        if (index == -1) {
            throw new InitializationException("Unknow source column name \"" + columnName + "\" in condition: "
                    + expression.getSourceText() + ". Known column names: "
                    + StringUtils.join(columnNames, ", ") + ".");
        }
        names.add(columnName);
        indexes.add(index);
    }

    this.columnNames = new String[names.size()];
    this.columnIndexes = new int[indexes.size()];
    for (int i = 0; i < indexes.size(); i++) {
        this.columnNames[i] = names.get(i);
        this.columnIndexes[i] = indexes.get(i);
    }
}

From source file:de.ks.idnadrev.information.view.InformationOverviewDS.java

@Override
public List<InformationPreviewItem> loadModel(Consumer<List<InformationPreviewItem>> furtherProcessing) {
    List<Class<? extends Information<?>>> classes = new ArrayList<>(
            Arrays.asList(TextInfo.class, ChartInfo.class, UmlDiagramInfo.class));
    if (loadingHint.getType() != null) {
        classes.clear();/*from   w  w  w  . j a v  a  2  s .co m*/
        classes.add(loadingHint.getType());
    }
    String name = "%" + StringUtils.replace(loadingHint.getName(), "*", "%") + "%";
    List<String> tags = loadingHint.getTags();
    Category category = loadingHint.getCategory();

    List<InformationPreviewItem> retval = PersistentWork.read(em -> {
        CriteriaBuilder builder = em.getCriteriaBuilder();

        List<InformationPreviewItem> items = new ArrayList<>();

        for (Class<? extends Information<?>> clazz : classes) {
            List<InformationPreviewItem> results = getResults(name, tags, category, em, builder, clazz);
            results.forEach(r -> r.setType(clazz));
            items.addAll(results);
        }
        furtherProcessing.accept(items);
        return items;
    });

    return retval;
}

From source file:de.vandermeer.skb.interfaces.transformers.textformat.Text_To_WrappedFormat.java

@Override
default Pair<ArrayList<String>, ArrayList<String>> transform(String input) {
    Validate.notBlank(input);/*from   ww  w  . j a  v a  2 s  .c  o m*/
    Validate.isTrue(this.getWidth() > 0);

    ArrayList<String> topList = new ArrayList<>();
    ArrayList<String> bottomList = new ArrayList<>();

    //an emergency break, counting loops to avoid endless loops
    int count;

    String text = StringUtils.replacePattern(input, "\\r\\n|\\r|\\n", LINEBREAK);
    text = StringUtils.replace(text, "<br>", LINEBREAK);
    text = StringUtils.replace(text, "<br/>", LINEBREAK);

    StrBuilder sb = new StrBuilder(text);
    if (this.getTopSettings() != null) {
        //we have a top request, do that one first
        Validate.notNull(this.getTopSettings().getLeft());
        Validate.notNull(this.getTopSettings().getRight());
        Validate.isTrue(this.getTopSettings().getLeft() > 0);
        Validate.isTrue(this.getTopSettings().getRight() > 0);

        int topLines = this.getTopSettings().getLeft();
        int topWidth = this.getTopSettings().getRight();
        count = 0;

        while (sb.size() > 0 && topLines > 0 && count++ < 200) {
            if (sb.startsWith(LINEBREAK)) {
                sb.replaceFirst(LINEBREAK, "");
            }
            String s = null;
            boolean wln = false;
            if (sb.indexOf(LINEBREAK) > 0) {
                s = sb.substring(0, sb.indexOf(LINEBREAK));
                wln = true;
                //sb.replace(0, sb.indexOf(LINEBREAK) + LINEBREAK.length(), "");
            } else {
                s = sb.toString();
                //sb.clear();
            }
            String wrap = WordUtils.wrap(s, topWidth, LINEBREAK, true);
            StrTokenizer tok = new StrTokenizer(wrap, LINEBREAK).setIgnoreEmptyTokens(false);
            String[] ar = tok.getTokenArray();
            if (ar.length <= topLines) {
                //all lines done, cleanup
                for (String str : ar) {
                    topList.add(str.trim());
                }
                if (wln == true) {
                    //if we had a conditional linebreak there might be more text, remove the line we processed
                    sb.replace(0, sb.indexOf(LINEBREAK) + LINEBREAK.length(), "");
                } else {
                    //no conditional line break, clean builder
                    sb.clear();
                }
                topLines = 0;
            } else {
                //we have more lines than we need, so remove the text we have from the builder and copy processed lines
                StrBuilder replace = new StrBuilder();
                for (int i = 0; i < topLines; i++) {
                    topList.add(ar[i].trim());
                    replace.appendSeparator(' ').append(ar[i]);
                }
                if (wln == true) {
                    replace.append(LINEBREAK);
                }
                sb.replaceFirst(replace.toString(), "");
                topLines = 0;
            }
        }
    }

    //no top, simple wrapping with recognition of conditional line breaks
    count = 0;
    while (sb.size() > 0 && count++ < 200) {
        if (sb.startsWith(LINEBREAK)) {
            sb.replaceFirst(LINEBREAK, "");
        }
        String s = null;
        if (sb.indexOf(LINEBREAK) > 0) {
            s = sb.substring(0, sb.indexOf(LINEBREAK));
            sb.replace(0, sb.indexOf(LINEBREAK) + LINEBREAK.length(), "");
        } else {
            s = sb.toString();
            sb.clear();
        }
        s = WordUtils.wrap(s, this.getWidth(), LINEBREAK, true);
        StrTokenizer tok = new StrTokenizer(s, LINEBREAK).setIgnoreEmptyTokens(false);
        for (String str : tok.getTokenArray()) {
            bottomList.add(str.trim());
        }
    }

    return Pair.of(topList, bottomList);
}

From source file:io.wcm.devops.conga.plugins.aem.tooling.crypto.cli.AnsibleVaultTest.java

@Test
public void testEncryptDecryptWithCarriageReturns() throws Exception {
    FileUtils.write(testFile, TEST_CONTENT, StandardCharsets.UTF_8);

    // encrypt file
    AnsibleVault.encrypt(testFile);//from w  w  w  .  j  av a2 s. c  o  m
    String content = FileUtils.readFileToString(testFile, StandardCharsets.UTF_8);
    assertNotEquals(TEST_CONTENT, content);

    // replace \n with \r\n to simulate new lines on windows file systems
    content = StringUtils.replace(content, "\n", "\r\n");
    FileUtils.write(testFile, content, StandardCharsets.UTF_8);

    // decrypt file
    AnsibleVault.decrypt(testFile);
    content = FileUtils.readFileToString(testFile, StandardCharsets.UTF_8);
    assertEquals(TEST_CONTENT, content);
}

From source file:com.mirth.connect.donkey.server.data.jdbc.XmlQuerySource.java

@Override
public String getQuery(String queryName, Map<String, Object> values) {
    String query = queries.get(queryName);

    if (query == null) {
        return null;
    }//w  w w  .j  a  v a 2s  .  c  o m

    if (values != null) {
        for (Entry<String, Object> entry : values.entrySet()) {
            query = StringUtils.replace(query, "${" + entry.getKey() + "}", entry.getValue().toString());
        }
    }

    logger.debug(query);
    return query;
}

From source file:de.vandermeer.skb.interfaces.transformers.String_To_ConditionalBreak.java

/**
 * Transforms a String to a String[] processing conditional line breaks.
 * Conditional line breaks are CR LF, CR, LF, &lt;br&gt;, and &lt;br/&gt;.
 * /*from   w w w  .j a  va  2  s  .co m*/
 * The method proceeds as follows:
 * 
 *     . replace all line breaks (CR LF, CR, LF) into HTML4 line break entity &lt;br&gt;
 *     . replace all HTML4 line break entities to HTML5 entities (as in self-closing &lt;br/&gt; entity).
 *     . use a `tokenizer` to process the resulting string (not ignoring empty tokens, since they mark required line breaks).
 *     . return the array of the `tokenizer`
 * 
 * As a result, a string containing 1 line break will be converted into an array length 2:
 * ----
 * String: "paragraph 1\nparagraph 2"
 * Array:  {paragraph 1,paragraph 2}
 * ----
 * 
 * A string containing 2 line breaks will be converted into a string array with 3 entries (first paragraph, additional line break, second paragraph):
 * ----
 * String: "paragraph 1\n\nparagraph 2"
 * Array: {paragraph 1,,paragraph 2}
 * ----
 * 
 * @param s input string
 * @return array with conditional line breaks converted to empty entries, `null` if `s` was `null`
 */
@Override
default String[] transform(String s) {
    IsTransformer.super.transform(s);
    if ("".equals(s)) {
        return new String[] { "" };
    }

    String lfRep = StringUtils.replacePattern(s.toString(), "\\r\\n|\\r|\\n", "<br>");
    lfRep = StringUtils.replace(lfRep, "<br>", "<br/>");
    lfRep = StringUtils.replace(lfRep, "<br/>", "<br />");
    StrTokenizer tok = new StrTokenizer(lfRep, "<br />").setIgnoreEmptyTokens(false);
    return tok.getTokenArray();
}