Example usage for org.apache.commons.lang3 StringEscapeUtils escapeEcmaScript

List of usage examples for org.apache.commons.lang3 StringEscapeUtils escapeEcmaScript

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringEscapeUtils escapeEcmaScript.

Prototype

public static final String escapeEcmaScript(final String input) 

Source Link

Document

Escapes the characters in a String using EcmaScript String rules.

Escapes any values it finds into their EcmaScript String form.

Usage

From source file:org.apache.struts2.showcase.model.Skill.java

public String getDescription() {
    return StringEscapeUtils.escapeEcmaScript(StringEscapeUtils.escapeHtml4(description));
}

From source file:org.apache.struts2.util.TextProviderHelper.java

/**
 * <p>Get a message from the first TextProvider encountered in the stack.
 * If the first TextProvider doesn't provide the message the default message is returned.</p>
 * <p>The search for a TextProvider is iterative from the root of the stack.</p>
 * <p>This method was refactored from  {@link org.apache.struts2.components.Text} to use a
 * consistent implementation across UIBean components.</p>
 * @param key             the message key in the resource bundle
 * @param defaultMessage  the message to return if not found (evaluated for OGNL)
 * @param args            an array args to be used in a {@link java.text.MessageFormat} message
 * @param stack           the value stack to use for finding the text
 * @param searchStack     search stack for the key
 *
 * @return the message if found, otherwise the defaultMessage
 *//*ww w . j a v a2  s  .  com*/
public static String getText(String key, String defaultMessage, List<Object> args, ValueStack stack,
        boolean searchStack) {
    String msg = null;
    TextProvider tp = null;

    for (Object o : stack.getRoot()) {
        if (o instanceof TextProvider) {
            tp = (TextProvider) o;
            msg = tp.getText(key, null, args, stack);

            break;
        }
    }

    if (msg == null) {
        // evaluate the defaultMessage as an OGNL expression
        if (searchStack)
            msg = stack.findString(defaultMessage);

        if (msg == null) {
            // use the defaultMessage literal value
            msg = defaultMessage;
            msg = StringEscapeUtils.escapeEcmaScript(msg);
            msg = StringEscapeUtils.escapeHtml4(msg);
            LOG.debug("Message for key '{}' is null, returns escaped default message [{}]", key, msg);
        }

        if (LOG.isWarnEnabled()) {
            if (tp != null) {
                LOG.warn(
                        "The first TextProvider in the ValueStack ({}) could not locate the message resource with key '{}'",
                        tp.getClass().getName(), key);
            } else {
                LOG.warn(
                        "Could not locate the message resource '{}' as there is no TextProvider in the ValueStack.",
                        key);
            }
            if (defaultMessage.equals(msg)) {
                LOG.warn(
                        "The default value expression '{}' was evaluated and did not match a property. The literal value '{}' will be used.",
                        defaultMessage, defaultMessage);
            } else {
                LOG.warn("The default value expression '{}' evaluated to '{}'", defaultMessage, msg);
            }
        }
    }
    return msg;
}

From source file:org.apache.struts2.views.util.DefaultUrlHelper.java

public String buildUrl(String action, HttpServletRequest request, HttpServletResponse response,
        Map<String, Object> params, String scheme, boolean includeContext, boolean encodeResult,
        boolean forceAddSchemeHostAndPort, boolean escapeAmp) {
    StringBuilder link = new StringBuilder();

    boolean changedScheme = false;

    // FIXME: temporary hack until class is made a properly injected bean
    Container cont = ActionContext.getContext().getContainer();
    int httpPort = Integer.parseInt(cont.getInstance(String.class, StrutsConstants.STRUTS_URL_HTTP_PORT));
    int httpsPort = Integer.parseInt(cont.getInstance(String.class, StrutsConstants.STRUTS_URL_HTTPS_PORT));

    // only append scheme if it is different to the current scheme *OR*
    // if we explicity want it to be appended by having forceAddSchemeHostAndPort = true
    if (forceAddSchemeHostAndPort) {
        String reqScheme = request.getScheme();
        changedScheme = true;/*ww w .  j  a  v  a 2  s.  c  o m*/
        link.append(scheme != null ? scheme : reqScheme);
        link.append("://");
        link.append(request.getServerName());

        if (scheme != null) {
            // If switching schemes, use the configured port for the particular scheme.
            if (!scheme.equals(reqScheme)) {
                if ((scheme.equals("http") && (httpPort != DEFAULT_HTTP_PORT))
                        || (scheme.equals("https") && httpsPort != DEFAULT_HTTPS_PORT)) {
                    link.append(":");
                    link.append(scheme.equals("http") ? httpPort : httpsPort);
                }
                // Else use the port from the current request.
            } else {
                int reqPort = request.getServerPort();

                if ((scheme.equals("http") && (reqPort != DEFAULT_HTTP_PORT))
                        || (scheme.equals("https") && reqPort != DEFAULT_HTTPS_PORT)) {
                    link.append(":");
                    link.append(reqPort);
                }
            }
        }
    } else if ((scheme != null) && !scheme.equals(request.getScheme())) {
        changedScheme = true;
        link.append(scheme);
        link.append("://");
        link.append(request.getServerName());

        if ((scheme.equals("http") && (httpPort != DEFAULT_HTTP_PORT))
                || (scheme.equals("https") && httpsPort != DEFAULT_HTTPS_PORT)) {
            link.append(":");
            link.append(scheme.equals("http") ? httpPort : httpsPort);
        }
    }

    if (action != null) {
        // Check if context path needs to be added
        // Add path to absolute links
        if (action.startsWith("/") && includeContext) {
            String contextPath = request.getContextPath();
            if (!contextPath.equals("/")) {
                link.append(contextPath);
            }
        } else if (changedScheme) {

            // (Applicable to Servlet 2.4 containers)
            // If the request was forwarded, the attribute below will be set with the original URL
            String uri = (String) request.getAttribute("javax.servlet.forward.request_uri");

            // If the attribute wasn't found, default to the value in the request object
            if (uri == null) {
                uri = request.getRequestURI();
            }

            link.append(uri.substring(0, uri.lastIndexOf('/') + 1));
        }

        // Add page
        link.append(action);
    } else {
        // Go to "same page"
        String requestURI = (String) request.getAttribute("struts.request_uri");

        // (Applicable to Servlet 2.4 containers)
        // If the request was forwarded, the attribute below will be set with the original URL
        if (requestURI == null) {
            requestURI = (String) request.getAttribute("javax.servlet.forward.request_uri");
        }

        // If neither request attributes were found, default to the value in the request object
        if (requestURI == null) {
            requestURI = request.getRequestURI();
        }

        link.append(requestURI);
    }

    //if the action was not explicitly set grab the params from the request
    if (escapeAmp) {
        buildParametersString(params, link, AMP);
    } else {
        buildParametersString(params, link, "&");
    }

    String result = link.toString();

    if (StringUtils.containsIgnoreCase(result, "<script")) {
        result = StringEscapeUtils.escapeEcmaScript(result);
    }
    try {
        result = encodeResult ? response.encodeURL(result) : result;
    } catch (Exception ex) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Could not encode the URL for some reason, use it unchanged", ex);
        }
        result = link.toString();
    }

    return result;
}

From source file:org.apereo.portal.security.xslt.XalanMessageHelperBean.java

@Override
public String getMessageForEmacsScript(String code, String language) {
    return StringEscapeUtils.escapeEcmaScript(this.getMessage(code, language));
}

From source file:org.apereo.portal.security.xslt.XalanMessageHelperBean.java

@Override
public String getMessageForEmacsScript(String code, String language, String arg1) {
    return StringEscapeUtils.escapeEcmaScript(this.getMessage(code, language, arg1));
}

From source file:org.apereo.portal.security.xslt.XalanMessageHelperBean.java

@Override
public String getMessageForEmacsScript(String code, String language, String arg1, String arg2) {
    return StringEscapeUtils.escapeEcmaScript(this.getMessage(code, language, arg1, arg2));
}

From source file:org.apereo.portal.security.xslt.XalanMessageHelperBean.java

@Override
public String getMessageForEmacsScript(String code, String language, String arg1, String arg2, String arg3) {
    return StringEscapeUtils.escapeEcmaScript(this.getMessage(code, language, arg1, arg2, arg3));
}

From source file:org.auraframework.modules.impl.ModulesCompilerJ2V8.java

@Override
public ModulesCompilerData compile(String entry, Map<String, String> sources) throws Exception {
    String options = "{ format: 'aura', mapNamespaceFromPath: true,\n" + "sources : {\n";

    String sourceClass = null;//from ww w  . j a  v  a2  s .c  om

    // add entries for all files in the bundle
    for (Entry<String, String> sourceEntry : sources.entrySet()) {
        String name = sourceEntry.getKey();
        String source = StringEscapeUtils.escapeEcmaScript(sourceEntry.getValue());

        options += '"' + name + "\": ";
        options += '"' + source + '"';
        options += ",\n";

        if (entry.endsWith(name.substring(1))) {
            sourceClass = source;
        }
    }

    if (sourceClass == null) {
        throw new IllegalArgumentException("could not find entry in sources: " + entry);
    }

    // add entry for sourceClass .js
    options += '"' + entry + "\": ";
    options += '"' + sourceClass + '"';
    options += "}}";

    return compile(entry, options);
}

From source file:org.auraframework.modules.impl.ModulesCompilerJ2V8.java

@Override
public ModulesCompilerData compile(String entry, String sourceTemplate, String sourceClass) throws Exception {
    sourceTemplate = StringEscapeUtils.escapeEcmaScript(sourceTemplate);
    sourceClass = StringEscapeUtils.escapeEcmaScript(sourceClass);

    String options = "{ sourceTemplate: \"" + sourceTemplate + "\"\n, sourceClass: \"" + sourceClass + "\"\n"
            + ", format: 'aura', mapNamespaceFromPath: true }";
    return compile(entry, options);
}

From source file:org.auraframework.test.util.AuraUITestingUtil.java

/**
 * Evaluate the given javascript in the current window. Upon completion, if the framework has loaded and is in a
 * test mode, then assert that there are no uncaught javascript errors.
 * <p>//from w  w  w  .ja v a2s  .  com
 * As an implementation detail, we accomplish this by wrapping the given javascript so that we can perform the error
 * check on each evaluation without doing a round-trip to the browser (which might be long in cases of remote test
 * runs).
 * 
 * @return the result of calling {@link JavascriptExecutor#executeScript(String, Object...) with the given
 *         javascript and args.
 */
public Object getEval(final String javascript, Object... args) {
    /**
     * Wrapping the javascript on the native Android browser is broken. By not using the wrapper we won't catch any
     * javascript errors here, but on passing cases this should behave the same functionally. See W-1481593.
     */
    if (driver instanceof RemoteWebDriver
            && "android".equals(((RemoteWebDriver) driver).getCapabilities().getBrowserName())) {
        return getRawEval(javascript, args);
    }

    /**
     * Wrap the given javascript to evaluate and then check for any collected errors. Then, return the result and
     * errors back to the WebDriver. We must return as an array because
     * {@link JavascriptExecutor#executeScript(String, Object...)} cannot handle Objects as return values."
     */
    String escapedJavascript = StringEscapeUtils.escapeEcmaScript(javascript);
    String wrapper = "var ret,scriptExecException;\n" + "try {\n"
            + String.format("var func = new Function('arguments', \"%s\");\n", escapedJavascript)
            + "  ret = func.call(this, arguments);\n" + "} catch(e){\n"
            + "  scriptExecException = e.message || e.toString();\n" + "}\n"
            + "var jstesterrors = (window.$A && window.$A.test) ? window.$A.test.getErrors() : '';\n"
            + "return [ret, jstesterrors, scriptExecException];";

    try {
        Object obj = getRawEval(wrapper, args);
        Assert.assertTrue(
                "Expecting an instance of list, but get " + obj + ", when running: " + escapedJavascript,
                obj instanceof List);
        @SuppressWarnings("unchecked")
        List<Object> wrapResult = (List<Object>) obj;
        Assert.assertEquals("Wrapped javsascript execution expects an array of exactly 3 elements", 3,
                wrapResult.size());
        Object exception = wrapResult.get(2);
        Assert.assertNull(
                "Following JS Exception occured while evaluating provided script:\n" + exception + "\n"
                        + "Arguments: (" + Arrays.toString(args) + ")\n" + "Script:\n" + javascript + "\n",
                exception);
        String errors = (String) wrapResult.get(1);
        assertJsTestErrors(errors);
        rerunCount = 0;
        return wrapResult.get(0);
    } catch (WebDriverException e) {
        // shouldn't come here that often as we are also wrapping the js
        // script being passed to us in try/catch above
        Assert.fail("Script execution failed.\n" + "Exception type: " + e.getClass().getName() + "\n"
                + "Failure Message: " + e.getMessage() + "\n" + "Arguments: (" + Arrays.toString(args) + ")\n"
                + "Script:\n" + javascript + "\n");
        throw e;
    } catch (NullPointerException npe) {
        // Although it should never happen, ios-driver is occasionally returning null when trying to execute the
        // wrapped javascript. Re-run the script a couple more times before failing.
        if (++rerunCount > 2) {
            Assert.fail("Script execution failed.\n" + "Failure Message: " + npe.getMessage() + "\n"
                    + "Arguments: (" + Arrays.toString(args) + ")\n" + "Script:\n" + javascript + "\n");
        }
        return getEval(javascript, args);
    }
}