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

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

Introduction

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

Prototype

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

Source Link

Document

Replaces all occurrences of a String within another String.

Usage

From source file:gov.va.med.pharmacy.peps.presentation.common.displaytag.CsvView.java

/**
 * Escaping for csv format./* w w w.j a v  a  2  s  .c o  m*/
 * <ul>
 * <li>Quotes inside quoted strings are escaped with a /</li>
 * <li>Fields containings newlines or , are surrounded by "</li>
 * </ul>
 * Note this is the standard CVS format and it's not handled well by excel.
 * @param value the value 
 * @return The appropriate escape value
 * @see org.displaytag.export.BaseExportView#escapeColumnValue(java.lang.Object)
 */
protected String escapeColumnValue(Object value) {
    String stringValue = StringUtils.trim(value.toString());
    String cleanStringValue = "";

    //        String cleanStringValue = stringValue.replaceAll("\\<.*?>", "");

    try {
        cleanStringValue = extractText(stringValue);
    } catch (IOException e) {
        LOG.debug(e.getMessage());
    }

    if (!StringUtils.containsNone(cleanStringValue, new char[] { '\n', ',' })) {
        return "\"" + //$NON-NLS-1$
                StringUtils.replace(cleanStringValue, "\"", "\\\"") + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    }

    return cleanStringValue;
}

From source file:com.npower.dm.util.SyncMLCanonizer4Test.java

/**
 * Replace into message, into the tag <Data> amd if it isn't a CDATA:
 * <ui>// ww  w . java  2s  .  c  om
 * <li>'&' with '&amp;amp;'
 *      (if the character isn't the fisrt char of &amp;amp; or &amp;lt; or &amp;gt; or &amp;quot;)
 * <li>'<' with '&amp;lt;'
 * <li>'>' with '&amp;gt;'
 * <li>'"' with '&amp;quot;'
 * </ui>
 * @param message the original message xml
 *
 * @return message the message updated
 */
private String replaceEntity(String msg) {

    int s = 0;
    int e = 0;

    StringBuffer response = new StringBuffer();
    while ((e = msg.indexOf("<Data>", s)) >= 0) {

        // 6 = length of <Data>
        response = response.append(msg.substring(s, e + 6));

        int a = msg.indexOf("</Data>", e);
        String data = msg.substring(e + 6, a);

        if (data.startsWith("<![CDATA[")) {
            // not replace nothing
        } else if (data.trim().startsWith("<SyncML xmlns=\"syncml:dmddf1.2\">")) {
            // The data contains a MgmtTree
        } else {
            data = XMLTools.replaceAmp(data);
            data = StringUtils.replace(data, "<", "&lt;");
            data = StringUtils.replace(data, ">", "&gt;");
            data = StringUtils.replace(data, "\"", "&quot;");
        }
        s = a + 7; // length of </Data>
        response.append(data).append("</Data>");
    }
    response.append(msg.substring(s, msg.length()));

    return response.toString();
}

From source file:info.magnolia.cms.util.ClasspathResourcesUtil.java

/**
 * Load resources from jars or directories
 *
 * @param resources found resources will be added to this collection
 * @param jarOrDir  a File, can be a jar or a directory
 * @param filter    used to filter resources
 *//*w  w  w . j av  a  2s.c  o  m*/
private static void collectFiles(Collection resources, File jarOrDir, Filter filter) {

    if (!jarOrDir.exists()) {
        log.warn("missing file: {}", jarOrDir.getAbsolutePath());
        return;
    }

    if (jarOrDir.isDirectory()) {
        if (log.isDebugEnabled())
            log.debug("looking in dir {}", jarOrDir.getAbsolutePath());

        Collection files = FileUtils.listFiles(jarOrDir, new TrueFileFilter() {
        }, new TrueFileFilter() {
        });
        for (Iterator iter = files.iterator(); iter.hasNext();) {
            File file = (File) iter.next();
            String name = StringUtils.substringAfter(file.getPath(), jarOrDir.getPath());

            // please, be kind to Windows!!!
            name = StringUtils.replace(name, "\\", "/");
            if (!name.startsWith("/")) {
                name = "/" + name;
            }

            if (filter.accept(name)) {
                resources.add(name);
            }
        }
    } else if (jarOrDir.getName().endsWith(".jar")) {
        if (log.isDebugEnabled())
            log.debug("looking in jar {}", jarOrDir.getAbsolutePath());
        JarFile jar;
        try {
            jar = new JarFile(jarOrDir);
        } catch (IOException e) {
            log.error("IOException opening file {}, skipping", jarOrDir.getAbsolutePath());
            return;
        }
        for (Enumeration em = jar.entries(); em.hasMoreElements();) {
            JarEntry entry = (JarEntry) em.nextElement();
            if (!entry.isDirectory()) {
                if (filter.accept("/" + entry.getName())) {
                    resources.add("/" + entry.getName());
                }
            }
        }
    } else {
        if (log.isDebugEnabled())
            log.debug("Unknown (not jar) file in classpath: {}, skipping.", jarOrDir.getName());
    }

}

From source file:edu.ku.brc.specify.toycode.mexconabio.FMPCreateTable.java

public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) {
    buffer.setLength(0);//from w w w.  j  av a 2s. com

    if (localName.equals("FIELD")) {
        FieldDef fldDef = new FieldDef();
        fields.add(fldDef);

        for (int i = 0; i < attrs.getLength(); i++) {
            String attr = attrs.getLocalName(i);
            String value = attrs.getValue(i);
            if (attr.equals("EMPTYOK")) {
                fldDef.setNullable(value.equals("YES"));

            } else if (attr.equals("NAME")) {
                value = StringUtils.capitalize(value.trim());
                value = StringUtils.deleteWhitespace(value);
                value = StringUtils.replace(value, "_", "");

                if ((value.charAt(0) >= '0' && value.charAt(0) <= '9') || value.equalsIgnoreCase("New")
                        || value.equalsIgnoreCase("Group")) {
                    value = "Fld" + value;
                }

                String fixedStr = convertFromTwoByteUTF8(value);
                fixedStr = StringUtils.replace(fixedStr, ".", "");
                fixedStr = StringUtils.replace(fixedStr, ":", "");
                fixedStr = StringUtils.replace(fixedStr, "/", "_");
                fldDef.setName(fixedStr);
                fldDef.setOrigName(value);

            } else if (attr.equals("TYPE")) {
                if (value.equals("TEXT")) {
                    fldDef.setType(DataType.eText);

                } else if (value.equals("NUMBER")) {
                    fldDef.setType(DataType.eNumber);

                } else if (value.equals("DATE")) {
                    fldDef.setType(DataType.eDate);

                } else if (value.equals("TIME")) {
                    fldDef.setType(DataType.eTime);
                } else {
                    System.err.println("Unknown Type[" + value + "]");
                }
            }
        }
    }
}

From source file:com.flexive.tests.embedded.jsf.bean.MessageBeanTest.java

@Test
public void getMessageArgsEscapedString() {
    String message = (String) messageBean.get(KEY_1 + ",'random string, with comma'");
    String expected = StringUtils.replace(MSG_1, "{0}", "random string, with comma");
    Assert.assertTrue(expected.equals(message), "Expected: " + expected + ", got: " + message);
}

From source file:gool.generator.xml.XmlCodePrinter.java

@Override
public List<File> print(ClassDef pclass) throws FileNotFoundException {
    Document document = null;/*  w ww  .jav a 2 s  . com*/
    DocumentBuilderFactory fabrique = null;
    List<File> result = new ArrayList<File>();
    // Debugging info
    // nbNode = 0;

    try {
        // creat document structure
        fabrique = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = fabrique.newDocumentBuilder();
        document = builder.newDocument();
        Element racine = (Element) document.createElement("file");
        Element el = NodeToElement(pclass, document);
        if (el != null)
            racine.appendChild(el);
        document.appendChild(racine);

        // file separator is just a slash in Unix
        // so the second argument to File() is just the directory
        // that corresponds to the package name
        // the first argument is the default output directory of the
        // platform
        // so the directory name ends up being something like
        // GOOLOUPTUTTARGET/pack/age
        File dir = new File(getOutputDir().getAbsolutePath(),
                StringUtils.replace(pclass.getPackageName(), ".", File.separator));
        // Typically the outputdir was created before, but not the package
        // subdirs
        dir.mkdirs();
        // Create the file for the class, fill it in, close it
        File classFile = new File(dir, getFileName(pclass.getName()));
        Log.i(String.format("Writing to file %s", classFile));

        // Create formating output
        OutputFormat format = new OutputFormat(document);
        format.setEncoding("UTF-8");
        format.setLineWidth(80);
        format.setIndenting(true);
        format.setIndent(4);

        // save to output file
        Writer out = new PrintWriter(classFile);
        XMLSerializer serializer = new XMLSerializer(out, format);
        serializer.serialize(document);

        // Remember that you did the generation for this one abstract GOOL
        // class
        printedClasses.add(pclass);
        result.add(classFile);
        classdefok = true;
    } catch (Exception e) {
        Log.e(e);
        System.exit(1);
    }

    return result;
}

From source file:com.prowidesoftware.swift.model.field.Field257Test.java

@Test
public void testGetValue2() {
    Field257 f = new Field257();
    String v = EXAMPLE2_FIELD_257;
    f = new Field257(v);
    assertEquals(StringUtils.replace(v, "\n", FINWriterVisitor.SWIFT_EOL), f.getValue());
}

From source file:co.marcin.novaguilds.yaml.YamlEnumTest.java

@Test
public void testMessages() throws Exception {
    System.out.println();//from  w w w . j av a2s  .c o m
    System.out.println("Testing message enums...");
    File motherFile = new File(YamlParseTest.resourcesDirectory, "lang/en-en.yml");
    YamlConfiguration motherConfiguration = Lang.loadConfiguration(motherFile);
    List<String> messageEnumNames = new ArrayList<>();
    for (Message v : Message.values()) {
        messageEnumNames.add(v.name());
    }

    int missingCount = 0;
    for (String key : motherConfiguration.getKeys(true)) {
        if (!motherConfiguration.isConfigurationSection(key)) {
            String name = StringUtils.replace(key, ".", "_").toUpperCase();
            if (!messageEnumNames.contains(name)) {
                if (missingCount == 0) {
                    System.out.println("Missing keys:");
                }

                System.out.println(name + ",");
                missingCount++;
            }
        }
    }

    if (missingCount == 0) {
        System.out.println("All values are present in Message enum");
    } else {
        throw new Exception("Found " + missingCount + " missing Message enums");
    }
}

From source file:edu.ku.brc.specify.dbsupport.cleanuptools.FirstLastVerifier.java

/**
 * @param fieldName//from w  w w  .j a va2  s.com
 * @param searchText
 * @return
 */
private boolean search(final String fieldName, final String searchText) {
    if (parser == null) {
        initLuceneforReading(fieldName);
    }
    try {
        String srchTxt = StringUtils.replace(searchText, ")", "");
        srchTxt = StringUtils.replace(srchTxt, "(", "");
        srchTxt = StringUtils.replace(srchTxt, ":", "");
        srchTxt = StringUtils.replace(srchTxt, "?", "");

        Query query = parser.parse(fieldName + ":" + srchTxt.toUpperCase());
        int hitsPerPage = 10;
        TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);
        searcher.search(query, collector);
        ScoreDoc[] hits = collector.topDocs().scoreDocs;

        //System.out.println("Hits: "+(hits != null ? hits.length : 0));

        return hits.length > 0;

    } catch (Exception e) {
        System.err.println(e.getMessage());
        //e.printStackTrace();
    }
    return false;
}

From source file:de.thischwa.pmcms.view.renderer.VelocityUtils.java

/**
 * Replace the img-tag and a-tag with the equivalent velocity macro. Mainly used before saving a field value to the database.
 * //from   w w w  .ja va2s .c o  m
 * @throws RenderingException
 *             If any exception was thrown while replacing the tags.
 */
@SuppressWarnings("unchecked")
public static String replaceTags(final Site site, final String oldValue) throws RenderingException {
    if (StringUtils.isBlank(oldValue))
        return null;

    // 1. add a root element (to have a proper xml) and replace the ampersand
    String newValue = String.format("<dummytag>\n%s\n</dummytag>",
            StringUtils.replace(oldValue, "&", ampReplacer));
    Map<String, String> replacements = new HashMap<String, String>();

    try {
        Document dom = DocumentHelper.parseText(newValue);
        dom.setXMLEncoding(Constants.STANDARD_ENCODING);

        // 2. Collect the keys, identify the img-tags.
        List<Node> imgs = dom.selectNodes("//img", ".");
        for (Node node : imgs) {
            Element element = (Element) node;
            if (element.attributeValue("src").startsWith("/")) // only internal links have to replaced with a velocity macro
                replacements.put(node.asXML(),
                        generateVelocityImageToolCall(site, element.attributeIterator()));
        }

        // 3. Collect the keys, identify the a-tags
        List<Node> links = dom.selectNodes("//a", ".");
        for (Node node : links) {
            Element element = (Element) node;
            if (element.attributeValue("href").startsWith("/")) // only internal links have to replaced with a velocity macro
                replacements.put(element.asXML(), generateVelocityLinkToolCall(site, element));
        }

        // 4. Replace the tags with the velomacro.
        StringWriter stringWriter = new StringWriter();
        XMLWriter writer = new XMLWriter(stringWriter, sourceFormat);
        writer.write(dom.selectSingleNode("dummytag"));
        writer.close();
        newValue = stringWriter.toString();
        for (String stringToReplace : replacements.keySet())
            newValue = StringUtils.replace(newValue, stringToReplace, replacements.get(stringToReplace));
        newValue = StringUtils.replace(newValue, "<dummytag>", "");
        newValue = StringUtils.replace(newValue, "</dummytag>", "");

    } catch (Exception e) {
        throw new RenderingException("While preprocessing the field value: " + e.getMessage(), e);
    }

    return StringUtils.replace(newValue, ampReplacer, "&");
}