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.auraframework.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   ww  w  .  j a v a  2 s.c  o m
 * 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;"
            + String.format("var func = new Function('arguments', \"%s\");\n", escapedJavascript) + "try\n{"
            + " ret = func.call(this, arguments);\n" + "}\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 {
        @SuppressWarnings("unchecked")
        List<Object> wrapResult = (List<Object>) getRawEval(wrapper, args);
        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);
    }
}

From source file:org.eclipse.winery.repository.rest.resources.servicetemplates.boundarydefinitions.BoundaryDefinitionsJSPData.java

public String getDefinedPropertiesAsJSONString() {
    String s = this.getDefinedProperties();
    s = StringEscapeUtils.escapeEcmaScript(s);
    return s;
}

From source file:org.efaps.esjp.admin.common.systemconfiguration.SystemConf_Base.java

/**
 * Update field4 key./*from  w  w  w  .  ja va2 s  . co m*/
 *
 * @param _parameter the _parameter
 * @return the return
 * @throws EFapsException on error
 */
public Return updateFields4Key(final Parameter _parameter) throws EFapsException {
    final boolean isLink = "true".equalsIgnoreCase(getProperty(_parameter, "SysConfLink"));

    final PrintQuery print = new PrintQuery(_parameter.getCallInstance());
    final SelectBuilder sel;
    if (_parameter.getCallInstance().getType().isCIType(CIAdminCommon.SystemConfiguration)) {
        sel = SelectBuilder.get().attribute(CIAdminCommon.SystemConfiguration.UUID);
    } else {
        sel = SelectBuilder.get().linkto(CIAdminCommon.SystemConfigurationAttribute.AbstractLink)
                .attribute(CIAdminCommon.SystemConfiguration.UUID);
    }
    print.addSelect(sel);
    print.execute();
    final String uuid = print.getSelect(sel);

    final String key = _parameter.getParameterValue("key");

    ISysConfAttribute attr = isLink ? SysConfResourceConfig.getResourceConfig().getLink(uuid, key)
            : SysConfResourceConfig.getResourceConfig().getAttribute(uuid, key);
    if (attr == null && StringUtils.isNumeric(key.substring(key.length() - 2, key.length()))) {
        attr = isLink
                ? SysConfResourceConfig.getResourceConfig().getLink(uuid, key.substring(0, key.length() - 2))
                : SysConfResourceConfig.getResourceConfig().getAttribute(uuid,
                        key.substring(0, key.length() - 2));
    }

    final Map<String, Object> map = new HashMap<>();
    final String fieldName = _parameter.getParameters().containsKey("value") ? "value" : "value4edit";
    final CharSequence node;
    if (attr == null) {
        node = StringEscapeUtils.escapeEcmaScript(
                new PropertiesSysConfAttribute().getHtml(_parameter, null, fieldName).toString());
    } else {
        node = StringEscapeUtils.escapeEcmaScript(attr.getHtml(_parameter, null, fieldName).toString());
        if (attr instanceof AbstractSysConfAttribute_Base) {
            map.put("description", StringEscapeUtils
                    .escapeEcmaScript(((AbstractSysConfAttribute_Base<?, ?>) attr).getDescription()));
        }
    }

    final Return ret = new Return();
    final List<Map<String, Object>> values = new ArrayList<>();

    values.add(map);
    final StringBuilder js = new StringBuilder()
            .append("require(['dojo/query', 'dojo/dom-construct'], function (query, domConstruct) {")
            .append("var first = true;").append("query('[name=value],[tag=rem]').forEach(function (node) {")
            .append("if (first) {").append("first = false;").append("var newNode = '").append(node).append("';")
            .append("domConstruct.place(newNode, node, 'replace');").append("} else {")
            .append("domConstruct.destroy(node);").append("}").append("});").append("});");
    map.put("eFapsFieldUpdateJS", js.toString());
    ret.put(ReturnValues.VALUES, values);
    return ret;
}

From source file:org.efaps.esjp.ui.html.dojo.charting.AbstractChart_Base.java

/**
 * Gets the title js.//from   ww w.  j  ava 2s  .  c  o m
 *
 * @return the title js
 */
protected CharSequence getTitleJS() {
    final StringBuilder ret = new StringBuilder();
    final String titleTmp = getTitle();
    if (titleTmp != null) {
        ret.append("title: \"").append(StringEscapeUtils.escapeEcmaScript(titleTmp)).append("\",")
                .append("titlePos: \"").append(getTitlePos()).append("\",")
                .append("titleFont: \"bold 8pt Tahoma\"");
    }
    //titleGap: 25,

    //titleFontColor: "orange"
    return ret;
}

From source file:org.efaps.esjp.ui.html.dojo.charting.AbstractData_Base.java

public CharSequence getConfigJS() {
    if (getTooltip() != null) {
        this.configMap.put("tooltip", "\"" + StringEscapeUtils.escapeEcmaScript(getTooltip()) + "\"");
    }//from w w w.j a  v  a2 s . c o m
    return Util.mapToObjectList(this.configMap);
}

From source file:org.efaps.esjp.ui.html.dojo.charting.PieData_Base.java

@Override
public CharSequence getJavaScript() {
    addConfig("x", 1);
    addConfig("y", getYValue());
    if (getText() != null) {
        addConfig("text", "\"" + StringEscapeUtils.escapeEcmaScript(getText()) + "\"");
    }//from  www.  j a v  a 2  s .  c  o m
    if (getLegend() != null) {
        addConfig("legend", "\"" + StringEscapeUtils.escapeEcmaScript(getLegend()) + "\"");
    }
    return getConfigJS();
}

From source file:org.efaps.ui.wicket.behaviors.dojo.AutoCompleteBehavior.java

@Override
public void renderHead(final Component _component, final IHeaderResponse _response) {
    super.renderHead(_component, _response);
    // add wicket ajax to be sure that is is included
    CoreLibrariesContributor.contributeAjax(this.component.getApplication(), _response);

    final CharSequence ajaxBaseUrl = Strings
            .escapeMarkup(this.component.getRequestCycle().getUrlRenderer().getBaseUrl().toString());
    _response.render(JavaScriptHeaderItem.forScript("Wicket.Ajax.baseUrl=\"" + ajaxBaseUrl + "\";",
            "wicket-ajax-base-url"));

    _response.render(AbstractEFapsHeaderItem.forCss(AutoCompleteBehavior.CSS));

    final String comboBoxId = "cb" + _component.getMarkupId();
    final StringBuilder js = new StringBuilder().append("var ").append(comboBoxId);

    switch (this.settings.getAutoType()) {
    case SUGGESTION:
        js.append(" = new AutoSuggestion({");
        break;/*from www.jav  a2  s .  co m*/
    case TOKEN:
        js.append(" = new AutoTokenInput({");
        break;
    default:
        js.append(" = new AutoComplete({");
        break;
    }

    js.append("id:\"").append(_component.getMarkupId()).append("\",").append("name:\"")
            .append(this.settings.getFieldName()).append("\",").append("placeHolder:ph,").append("store: as,")
            .append("value: \"\",").append("callbackUrl:\"" + getCallbackUrl() + "\",");

    switch (this.settings.getAutoType()) {
    case TOKEN:
        break;
    default:
        final String id = ((AutoCompleteField) _component).getItemValue();
        final String label = ((AutoCompleteField) _component).getItemLabel();
        // only if both value are valid it makes sence to add it
        if (StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(label)) {
            js.append("item: { id:\"").append(id).append("\", name:\"").append(label).append("\", label:\"")
                    .append(label).append("\"},");
        }
        break;
    }

    if (this.settings.getFieldConfiguration().hasProperty(UIFormFieldProperty.WIDTH)
            && !this.settings.getFieldConfiguration().isTableField()) {
        js.append("style:\"width:").append(this.settings.getFieldConfiguration().getWidth()).append("\",");
    }
    if (!this.settings.isHasDownArrow()) {
        js.append("hasDownArrow:").append(this.settings.isHasDownArrow()).append(",");
    }
    if (this.settings.getMinInputLength() > 1) {
        js.append("minInputLength:").append(this.settings.getMinInputLength()).append(",");
    }
    if (this.settings.getSearchDelay() != 500) {
        js.append("searchDelay:").append(this.settings.getSearchDelay()).append(",");
    }

    if (!"p".equals(this.settings.getParamName())) {
        js.append("paramName:\"").append(this.settings.getParamName()).append("\",");
    }

    if (!this.settings.getExtraParameters().isEmpty()) {
        js.append("extraParameters:[");
        boolean first = true;
        for (final String ep : this.settings.getExtraParameters()) {
            if (first) {
                first = false;
            } else {
                js.append(",");
            }
            js.append("\"").append(ep).append("\"");
        }
        js.append("],");
    }
    if (Type.SUGGESTION.equals(this.settings.getAutoType())) {
        js.append("labelAttr: \"label\",");
    }

    js.append("searchAttr: \"name\"}, \"").append(_component.getMarkupId()).append("\");\n");

    if (this.settings.isRequired() && !Type.TOKEN.equals(this.settings.getAutoType())) {
        js.append("on(").append(comboBoxId).append(", 'change', function() {").append("var label=")
                .append(comboBoxId).append(".item.label;")
                .append("if (!(label === undefined || label === null)) {").append(comboBoxId)
                .append(".item.name=label;").append(comboBoxId).append(".set(\"item\",").append(comboBoxId)
                .append(".item);").append("}");
        if (this.fieldUpdate != null) {
            js.append(this.fieldUpdate.getCallbackScript4Dojo());
        }
        js.append("});\n");
    } else if (this.fieldUpdate != null) {
        js.append("on(").append(comboBoxId).append(", 'change', function() {")
                .append(this.fieldUpdate.getCallbackScript4Dojo()).append("});\n");
    }

    if (!_component.getBehaviors(SetSelectedRowBehavior.class).isEmpty()) {
        js.append("on(").append(comboBoxId).append(", 'focus', function() {").append(
                _component.getBehaviors(SetSelectedRowBehavior.class).get(0).getJavaScript("this.valueNode"))
                .append("});\n");
    }
    if (Type.TOKEN.equals(this.settings.getAutoType())) {
        final List<IOption> tokens = ((AutoCompleteField) _component).getTokens();
        for (final IOption token : tokens) {
            js.append(comboBoxId).append(".addToken(\"")
                    .append(StringEscapeUtils.escapeEcmaScript(token.getValue().toString())).append("\",\"")
                    .append(StringEscapeUtils.escapeEcmaScript(token.getLabel())).append("\");\n");
        }
    }
    _response.render(AutoCompleteHeaderItem.forScript(js.toString(), EnumSet.of(this.settings.getAutoType())));
}

From source file:org.efaps.ui.wicket.behaviors.SetMessageStatusBehavior.java

/**
 *
 * @return script//from  w  w w  .j  av a2 s . c o  m
 * @throws EFapsException on error
 */
private static String getScript() throws EFapsException {
    final StringBuilder js = new StringBuilder();
    final long usrId = Context.getThreadContext().getPersonId();
    if (MessageStatusHolder.hasUnreadMsg(usrId) || MessageStatusHolder.hasReadMsg(usrId)) {
        js.append("top.postMessage('")
                .append(StringEscapeUtils.escapeEcmaScript(SetMessageStatusBehavior.getLabel(
                        MessageStatusHolder.getUnReadCount(usrId), MessageStatusHolder.getReadCount(usrId))))
                .append("', '*');");
    } else {
        js.append("top.postMessage('").append("', '*');");
    }
    return js.toString();
}

From source file:org.efaps.ui.wicket.components.gridx.GridXComponent.java

protected CharSequence getSubMenu(final AbstractMenu _menu, final String _parent) {
    final String var = RandomStringUtils.randomAlphabetic(4);
    final StringBuilder js = new StringBuilder();
    js.append("var ").append(var).append(" = new DropDownMenu({});\n");

    for (final AbstractCommand child : _menu.getCommands()) {
        if (child instanceof AbstractMenu) {
            js.append(getSubMenu((AbstractMenu) child, var));
        } else {// w ww.  j  a va 2s  .c o  m
            js.append(var).append(".addChild(").append(getMenuItem(child, false)).append(");\n");
        }
    }
    js.append(_parent).append(".addChild(new PopupMenuBarItem({\n").append("label: \"")
            .append(StringEscapeUtils.escapeEcmaScript(_menu.getLabelProperty())).append("\",\n")
            .append(" popup: ").append(var).append("\n").append(" }));\n");
    return js;
}

From source file:org.efaps.ui.wicket.components.gridx.GridXComponent.java

protected CharSequence getMenuItem(final AbstractCommand _cmd, final boolean _menuBar) {
    final UIGrid uiGrid = (UIGrid) getDefaultModelObject();
    final String rid = uiGrid.getRandom4ID(_cmd.getId());
    final StringBuilder js = new StringBuilder();
    if (_menuBar) {
        js.append("new MenuBarItem({\n");
    } else {/* ww w  .  j a  va 2 s. c om*/
        js.append("new MenuItem({\n");
    }
    js.append(" label: \"").append(StringEscapeUtils.escapeEcmaScript(_cmd.getLabelProperty())).append("\",\n")
            .append("onClick: function(event) {\n").append("var rid = \"").append(rid).append("\";\n");

    final GridXPanel panel = (GridXPanel) getParent();
    panel.visitChildren(MenuItem.class, new IVisitor<MenuItem, Void>() {

        @Override
        public void component(final MenuItem _item, final IVisit<Void> visit) {
            if (Target.MODAL.equals(_cmd.getTarget())) {
                if (_cmd.isSubmit()) {
                    js.append(_item.getBehaviors(SubmitModalBehavior.class).get(0)
                            .getCallbackFunctionBody(CallbackParameter.explicit("rid")));
                } else {
                    js.append(_item.getBehaviors(OpenModalBehavior.class).get(0)
                            .getCallbackFunctionBody(CallbackParameter.explicit("rid")));
                }
            } else if (_cmd.isSubmit()) {
                js.append(_item.getBehaviors(SubmitBehavior.class).get(0)
                        .getCallbackFunctionBody(CallbackParameter.explicit("rid")));
            }
        }
    });
    js.append("}\n").append("})\n");
    return js;
}