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:edu.cornell.med.icb.util.ICBStringUtils.java

/**
 * Fix the incoming string to be safe for HTML <input>, etc..
 * @param inval The incoming String to be fixed. Passing
 * in a null or an empty string will return an empty string.
 * @return String that is safe to use for Javascript strings
 *///from  w w w. j av a 2s  .  c  o  m
public static String xmlFix(final String inval) {
    if (StringUtils.isBlank(inval)) {
        return StringUtils.EMPTY;
    }
    String outval = StringUtils.replace(inval, "&", HTML_AMP);
    outval = StringUtils.replace(outval, "\"", HTML_DOUBLE_QUOTE);
    outval = StringUtils.replace(outval, "<", HTML_LESS_THAN);
    outval = StringUtils.replace(outval, ">", HTML_GREATER_THAN);
    outval = StringUtils.replace(outval, "\n", XML_NEWLINE);
    outval = StringUtils.replace(outval, "\r", XML_CR);
    return outval;
}

From source file:net.jforum.formatters.BBConfigFormatter.java

/**
 * Formats only the [code] tag//from  w ww.j  a  v a2s  .  co  m
 *
 * @param text the text to format
 * @return the formatted text
 */
private String processCodeTag(String text) {
    for (BBCode bb : this.bbTags.values()) {
        // There is "code" and "code-highlight"
        if (bb.getTagName().startsWith("code")) {
            Matcher matcher = Pattern.compile(bb.getRegex()).matcher(text);
            StringBuilder sb = new StringBuilder(text);

            while (matcher.find()) {
                String lang = null;
                String contents = null;

                if ("code".equals(bb.getTagName())) {
                    contents = matcher.group(1);
                } else {
                    lang = matcher.group(1);
                    contents = matcher.group(2);
                }

                contents = StringUtils.replace(contents, "<br/> ", "\n");

                // XML-like tags
                contents = StringUtils.replace(contents, "<", "&lt;");
                contents = StringUtils.replace(contents, ">", "&gt;");

                // Note: there is no replacing for spaces and tabs as
                // we are relying on the Javascript SyntaxHighlighter library
                // to do it for us

                StringBuilder replace = new StringBuilder(bb.getReplace());
                int index = replace.indexOf("$1");

                if ("code".equals(bb.getTagName())) {
                    if (index > -1) {
                        replace.replace(index, index + 2, contents.toString());
                    }

                    index = sb.indexOf("[code]");
                } else {
                    if (index > -1) {
                        replace.replace(index, index + 2, lang.toString());
                    }

                    index = replace.indexOf("$2");

                    if (index > -1) {
                        replace.replace(index, index + 2, contents.toString());
                    }

                    index = sb.indexOf("[code=");
                }

                int lastIndex = sb.indexOf("[/code]", index) + "[/code]".length();

                if (lastIndex > index) {
                    sb.replace(index, lastIndex, replace.toString());
                }
            }

            text = sb.toString();
        }
    }

    return text;
}

From source file:com.sfs.dao.LdapAuthenticationDAOImpl.java

/**
 * Load the UserBean./* www.j  a va 2  s . c  o  m*/
 *
 * @param userNameVal the user name
 * @param request the servlet request
 *
 * @return the user bean
 *
 * @throws SFSDaoException the SFS dao exception
 */
@SuppressWarnings("unchecked")
public final UserBean load(final String userNameVal, final HttpServletRequest request) throws SFSDaoException {
    // Loads user details into bean using a supplied username
    if (userNameVal == null) {
        throw new SFSDaoException("Username cannot be null");
    }
    if (userNameVal.compareTo("") == 0) {
        throw new SFSDaoException("Username cannot be an empty string");
    }

    UserBean user = null;

    final String base = this.searchBase;
    final String filter = StringUtils.replace(this.searchFilter, "%u", userNameVal);

    final LdapTemplate ldapTemplate = new LdapTemplate(contextSource);

    Collection<UserBean> users = ldapTemplate.search(base, filter, new ContextMapper() {
        public Object mapFromContext(final Object ctx) {
            DirContextAdapter adapter = (DirContextAdapter) ctx;
            return loadDetails(adapter);
        }
    });

    for (UserBean loadedUser : users) {
        user = loadedUser;
    }

    if (user == null) {
        throw new SFSDaoException("A user object for this username " + "was not found");
    }
    return user;
}

From source file:com.sfs.dao.bugreport.JiraBugReportHandler.java

/**
 * Submit the bug report./*from w w w  . j a va2 s .  co m*/
 *
 * @param bugReport the bug report to submit
 *
 * @throws SFSDaoException the sfs dao exception
 */
public final void submitReport(final BugReportBean bugReport) throws SFSDaoException {
    if (bugReport == null) {
        throw new SFSDaoException("BugReportBean cannot be null");
    }
    if (jiraBaseUrl == null) {
        throw new SFSDaoException("The Jira base url cannot be null");
    }
    if (jiraUsername == null) {
        throw new SFSDaoException("The Jira username cannot be null");
    }
    if (jiraPassword == null) {
        throw new SFSDaoException("The Jira password cannot be null");
    }
    if (bugReport.getUser() == null) {
        throw new SFSDaoException("Submission of a bug report requires a valid user object");
    }
    if (bugReport.getReportClass() == null) {
        throw new SFSDaoException("The bug report class cannot be null");
    }

    final String jiraReportUrl = buildUrl(XMLRPC_ENDPOINT);

    Hashtable<String, String> issue = new Hashtable<String, String>();

    /** Set the bug report type url parameters **/
    String bugTypeParameters = "";
    try {
        ObjectTypeBean objectType = this.objectTypeDAO.load("Bug Report Type", bugReport.getReportType(),
                bugReport.getReportClass());
        bugTypeParameters = StringUtils.replace(objectType.getAbbreviation(), "&amp;", "&");
    } catch (SFSDaoException sde) {
        throw new SFSDaoException("Error submitting Jira report: " + sde.getMessage());
    }
    // Convert this string of bug report parameters to the array
    if (StringUtils.isNotBlank(bugTypeParameters)) {
        StringTokenizer st = new StringTokenizer(bugTypeParameters, "&");

        while (st.hasMoreElements()) {
            final String option = st.nextToken();
            final String parameter = option.substring(0, option.indexOf("="));
            final String value = option.substring(option.indexOf("=") + 1, option.length());

            logger.debug("Parameter: " + parameter + ", value: " + value);
            issue.put(parameter, value);
        }
    }

    /** Set the bug priority url parameters **/
    String priority = "";
    try {
        ObjectTypeBean objectType = this.objectTypeDAO.load("Bug Report Priority", "", bugReport.getPriority());
        priority = StringUtils.replace(objectType.getAbbreviation(), "&amp;", "&");
    } catch (SFSDaoException sde) {
        throw new SFSDaoException("Error submitting Jira report: " + sde.getMessage());
    }
    issue.put("priority", priority);

    /** Set the summary **/
    if (StringUtils.isBlank(bugReport.getTitle())) {
        bugReport.setTitle("Untitled issue");
    }
    issue.put("summary", bugReport.getTitle());

    /** Set the description **/
    issue.put("description", bugReport.getDescription());

    /** The username of the reporter **/
    issue.put("reporter", bugReport.getUser().getUserName().toLowerCase());

    /** Set the assignee - if none default set to automatic **/
    if (StringUtils.isNotBlank(this.jiraAssignee)) {
        issue.put("assignee", this.jiraAssignee);
    } else {
        // Set to automatic (-1 in Jira)
        issue.put("assignee", "-1");
    }

    if (!debugMode) {
        /** Post the bug report to Jira **/
        try {
            logger.info("Jira Report - submitting");
            logger.info("Jira URL: " + jiraReportUrl.toString());
            logger.info("Jira Parameters: " + issue.toString());

            final String response = this.performRestRequest(jiraReportUrl.toString(), issue);

            logger.info("Jira response: " + response);

        } catch (XmlRpcException xre) {
            throw new SFSDaoException("Error submitting Jira report via XMLRPC: " + xre.getMessage());
        } catch (MalformedURLException mue) {
            throw new SFSDaoException("Error with the Jira XMLRPC URL: " + mue.getMessage());
        }
    } else {
        logger.debug("Jira Report - debug mode");
        logger.debug("Jira URL: " + jiraReportUrl.toString());
        logger.debug("Jira Parameters: " + issue.toString());
    }
}

From source file:com.haulmont.cuba.web.log.LogWindow.java

private String writeLog() {
    StringBuilder sb = new StringBuilder();
    List<LogItem> items = App.getInstance().getAppLog().getItems();
    for (LogItem item : items) {
        sb.append("<b>");
        sb.append(DateFormatUtils.format(item.getTimestamp(), DATE_FORMAT));
        sb.append(" ");
        sb.append(item.getLevel().name());
        sb.append("</b>&nbsp;");
        sb.append(StringEscapeUtils.escapeHtml(item.getMessage()));
        if (item.getStacktrace() != null) {
            sb.append(" ");

            String htmlMessage = StringEscapeUtils.escapeHtml(item.getStacktrace());
            htmlMessage = StringUtils.replace(htmlMessage, "\n", "<br/>");
            htmlMessage = StringUtils.replace(htmlMessage, " ", "&nbsp;");
            htmlMessage = StringUtils.replace(htmlMessage, "\t", "&nbsp;&nbsp;&nbsp;&nbsp;");

            sb.append(htmlMessage);//from w  w  w . j  a  v a2 s . co m
        }
        sb.append("<br/>");
    }
    return sb.toString();
}

From source file:net.di2e.ecdr.search.transform.atom.response.AtomResponseTransformerTest.java

private SourceResponse getTransformResponse(final String LOCATION_XML) throws Exception {
    AtomSearchResponseTransformerConfig config = mock(AtomSearchResponseTransformerConfig.class);
    QueryRequest request = mock(QueryRequest.class);
    AtomResponseTransformer transformer = new AtomResponseTransformer(config);
    String atomXML = IOUtils.toString(getClass().getResourceAsStream(ATOM_TEMPLATE_FILE));
    atomXML = StringUtils.replace(atomXML, LOCATION_MARKER, LOCATION_XML);
    return transformer.processSearchResponse(IOUtils.toInputStream(atomXML), request, SITE_NAME);
}

From source file:info.magnolia.importexport.BootstrapUtil.java

/**
 * I.e. given a resource path like <code>/mgnl-bootstrap/foo/config.server.i18n.xml</code> it will return <code>config</code>.
 *///from ww w  . j a  v  a  2  s  .c  o m
public static String getWorkspaceNameFromResource(final String resourcePath) {
    String resourceName = StringUtils.replace(resourcePath, "\\", "/");

    String name = getFilenameFromResource(resourceName, ".xml");
    String fullPath = DataTransporter.revertExportPath(name);
    return StringUtils.substringBefore(fullPath, "/");
}

From source file:de.iritgo.nexim.tools.XStreamStore.java

private ConcurrentHashMap loadMap() {
    ConcurrentHashMap map = null;

    if (file.exists()) {
        try {/*  w  w  w  .  java  2s  .co m*/
            FileInputStream fis = new FileInputStream(file);
            String xmlData = IOUtils.toString(fis);

            fis.close();

            if (substituteFrom != null && substituteTo != null) {
                xmlData = StringUtils.replace(xmlData, substituteTo, substituteFrom);
            }

            map = new ConcurrentHashMap((Map) xstream.fromXML(xmlData));
        } catch (Exception e) {
            getLogger().error(e.getMessage(), e);
        }
    } else {
        System.out.println("No " + file + " => starting with void store");
        map = new ConcurrentHashMap();
    }

    return map;
}

From source file:er.extensions.formatters.ERXSimpleHTMLFormatter.java

/**
 * Converts an HTML string into an ASCII string.
 * @param inString HTML string//from w w  w. j  a v a  2 s. co m
 * @return ASCII-fied string
 */
@Override
public Object parseObject(String inString) throws java.text.ParseException {
    String newString;

    if (inString == null)
        return null;

    // Convert new-lines in the argument (which must be a String) to HTML breaks.
    newString = StringUtils.replace(inString, HTMLReturn, ASCIIReturn);
    // Convert tabs in the argument (which must be a String) to HTML spacers.
    return StringUtils.replace(newString, HTMLTab(), ASCIITab);
}

From source file:com.sfs.whichdoctor.xml.writer.PreferencesXmlWriter.java

/**
 * Save.//w ww.  jav a  2  s.  com
 *
 * @param preferences the preferences
 * @param user the user
 * @param internalUse the flag whether this is for internal use
 *
 * @return the xml string
 */
public static String save(final PreferencesBean preferences, final UserBean user, final boolean internalUse) {

    final XmlWriter xw = new XmlWriter();

    // Add preferences information
    xw.writeEntity("preferences");

    xw.writeEntity("company");
    xw.writeEntity("fullName").writeText(preferences.getOption("system", "companyname")).endEntity();
    xw.writeEntity("abbreviation").writeText(preferences.getOption("system", "companyabbrev")).endEntity();
    xw.endEntity();

    xw.writeEntity("gstNumber").writeText(preferences.getOption("finance", "gstnumber")).endEntity();
    xw.writeEntity("chequeName").writeText(preferences.getOption("finance", "chequename")).endEntity();
    xw.writeEntity("gst").writeText(preferences.getOption("finance", "gst")).endEntity();
    xw.writeEntity("paymentDue").writeText(preferences.getOption("finance", "paymentdue")).endEntity();

    xw.writeEntity("bank");
    xw.writeEntity("name").writeText(preferences.getOption("finance", "bankname")).endEntity();
    xw.writeEntity("branchNo").writeText(preferences.getOption("finance", "bankbranchno")).endEntity();
    xw.writeEntity("accountNo").writeText(preferences.getOption("finance", "bankaccountno")).endEntity();
    xw.endEntity();

    if (internalUse) {

        xw.writeEntity("credit");
        xw.writeEntity("receiptType").writeText(preferences.getOption("credit", "receipttype")).endEntity();
        xw.writeEntity("receiptClass").writeText(preferences.getOption("credit", "receiptclass")).endEntity();
        xw.writeEntity("processType").writeText(preferences.getOption("credit", "processtype")).endEntity();
        xw.endEntity();

        xw.writeEntity("specialty");
        xw.writeEntity("adult").writeText(preferences.getOption("specialty", "adult")).endEntity();
        xw.writeEntity("paediatric").writeText(preferences.getOption("specialty", "paediatric")).endEntity();
        xw.endEntity();

        xw.writeEntity("exam");
        xw.writeEntity("defaulttotalmarks").writeText(preferences.getOption("exam", "defaulttotalmarks"))
                .endEntity();
        xw.endEntity();
    }

    xw.writeEntity("mailingCountry").writeText(preferences.getOption("system", "mailingcountry")).endEntity();

    if (internalUse) {
        xw.writeEntity("membershipUpgrade").writeText(preferences.getOption("system", "membershipupgrade"))
                .endEntity();
        xw.writeEntity("addressVerification").writeText(preferences.getOption("system", "addressverification"))
                .endEntity();
    }

    xw.writeEntity("theme").writeText(preferences.getOption("system", "theme")).endEntity();

    if (internalUse) {
        xw.writeEntity("status").writeText(preferences.getOption("system", "status")).endEntity();
    }

    if (user != null) {
        xw.writeEntity("currentUser");
        xw.writeEntity("dn").writeText(user.getDN()).endEntity();
        xw.writeEntity("preferredName").writeText(user.getPreferredName()).endEntity();
        xw.writeEntity("lastName").writeText(user.getLastName()).endEntity();
        xw.endEntity();
    }

    final String currentDate = Formatter.convertDate(preferences.getCurrentDate());
    if (StringUtils.isNotBlank(currentDate)) {
        xw.writeEntity("currentDate").writeText(Formatter.convertDate(preferences.getCurrentDate()))
                .endEntity();
    }
    if (preferences.getOption("system", "webaddress").compareTo("") != 0) {
        xw.writeEntity("webAddress").writeText(preferences.getOption("system", "webaddress")).endEntity();
    }

    // Footer details
    xw.writeEntity("contact");
    xw.writeEntity("postal").writeText(preferences.getOption("contact", "postal")).endEntity();
    xw.writeEntity("physical").writeText(preferences.getOption("contact", "physical")).endEntity();
    xw.writeEntity("telephone").writeText(preferences.getOption("contact", "telephone")).endEntity();
    xw.writeEntity("fax").writeText(preferences.getOption("contact", "fax")).endEntity();
    xw.writeEntity("email").writeText(preferences.getOption("contact", "email")).endEntity();
    xw.writeEntity("web").writeText(preferences.getOption("contact", "web")).endEntity();
    xw.endEntity();

    if (internalUse) {
        String privacyHtml = DataFilter.getSafeXml(preferences.getOption("email", "privacy"));
        privacyHtml = StringUtils.replace(privacyHtml, "&lt;", "&#60;");
        privacyHtml = StringUtils.replace(privacyHtml, "&gt;", "&#62;");
        privacyHtml = StringUtils.replace(privacyHtml, "<", "&lt;");
        privacyHtml = StringUtils.replace(privacyHtml, ">", "&gt;");

        xw.writeEntity("email");
        xw.writeEntity("client").writeText(preferences.getOption("email", "client")).endEntity();
        xw.writeEntity("maxAttachments").writeText(preferences.getOption("email", "maxAttachments"))
                .endEntity();
        xw.writeEntity("stylesheet").writeText(preferences.getOption("email", "stylesheet")).endEntity();
        xw.writeEntity("logo").writeText(preferences.getOption("email", "logo")).endEntity();
        xw.writeEntity("privacy").writeXml(privacyHtml).endEntity();
        xw.endEntity();
    }

    if (StringUtils.isNotBlank(preferences.getExportTitle())) {
        xw.writeEntity("exportTitle").writeText(preferences.getExportTitle()).endEntity();
    }
    if (StringUtils.isNotBlank(preferences.getExportMessage())) {
        xw.writeEntity("exportMessage");
        xw.writeEntity("p").writeXml(StringUtils.replace(preferences.getExportMessage(), "\n", "</p><p>"))
                .endEntity();
        xw.endEntity();
    }

    xw.endEntity();

    return xw.getXml();
}