You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@myfaces.apache.org by lu...@apache.org on 2013/10/25 23:24:10 UTC
svn commit: r1535874 [2/9] - in /myfaces/shared/trunk/core/src:
main/java/org/apache/myfaces/shared/application/
main/java/org/apache/myfaces/shared/config/
main/java/org/apache/myfaces/shared/context/flash/
main/java/org/apache/myfaces/shared/renderki...
Modified: myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlJavaScriptUtils.java
URL: http://svn.apache.org/viewvc/myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlJavaScriptUtils.java?rev=1535874&r1=1535873&r2=1535874&view=diff
==============================================================================
--- myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlJavaScriptUtils.java (original)
+++ myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlJavaScriptUtils.java Fri Oct 25 21:24:09 2013
@@ -1,756 +1,763 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.myfaces.shared.renderkit.html;
-
-import java.io.IOException;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.logging.Logger;
-
-import javax.faces.component.UINamingContainer;
-import javax.faces.context.ExternalContext;
-import javax.faces.context.FacesContext;
-import javax.faces.context.ResponseWriter;
-
-import org.apache.myfaces.shared.config.MyfacesConfig;
-import org.apache.myfaces.shared.renderkit.html.HtmlRendererUtils.ScriptContext;
-import org.apache.myfaces.shared.renderkit.html.util.JavascriptUtils;
-import org.apache.myfaces.shared.renderkit.html.util.ResourceUtils;
-
-public final class HtmlJavaScriptUtils
-{
- private static final Logger log = Logger.getLogger(HtmlJavaScriptUtils.class
- .getName());
-
- private static final String AUTO_SCROLL_PARAM = "autoScroll";
- private static final String AUTO_SCROLL_FUNCTION = "getScrolling";
-
- private static final String SET_HIDDEN_INPUT_FN_NAME = "oamSetHiddenInput";
- private static final String SET_HIDDEN_INPUT_FN_NAME_JSF2 = "myfaces.oam.setHiddenInput";
-
- private static final String FIRST_SUBMIT_SCRIPT_ON_PAGE = "org.apache.MyFaces.FIRST_SUBMIT_SCRIPT_ON_PAGE";
- private static final String CLEAR_HIDDEN_INPUT_FN_NAME = "oamClearHiddenInput";
-
-
- @SuppressWarnings("unchecked")
- public static void renderFormSubmitScript(FacesContext facesContext)
- throws IOException
- {
-
- Map map = facesContext.getExternalContext().getRequestMap();
- Boolean firstScript = (Boolean) map.get(FIRST_SUBMIT_SCRIPT_ON_PAGE);
-
- if (firstScript == null || firstScript.equals(Boolean.TRUE))
- {
- map.put(FIRST_SUBMIT_SCRIPT_ON_PAGE, Boolean.FALSE);
- renderFormSubmitScriptIfNecessary(facesContext);
-
- //we have to render the config just in case
- renderConfigOptionsIfNecessary(facesContext);
- }
- }
-
- /**
- * @param facesContext
- * @throws IOException
- */
- private static void renderFormSubmitScriptIfNecessary(
- FacesContext facesContext) throws IOException
- {
- final ExternalContext externalContext = facesContext
- .getExternalContext();
- final MyfacesConfig currentInstance = MyfacesConfig
- .getCurrentInstance(externalContext);
- ResponseWriter writer = facesContext.getResponseWriter();
-
- if (currentInstance.isRenderFormSubmitScriptInline())
- {
- writer.startElement(HTML.SCRIPT_ELEM, null);
- writer.writeAttribute(HTML.TYPE_ATTR, "text/javascript", null);
-
- boolean autoScroll = currentInstance.isAutoScroll();
-
- ScriptContext context = new ScriptContext(
- currentInstance.isPrettyHtml());
- context.prettyLine();
- context.increaseIndent();
-
- prepareScript(facesContext, context, autoScroll);
-
- writer.writeText(context.toString(), null);
-
- writer.endElement(HTML.SCRIPT_ELEM);
- }
- else
- {
- ResourceUtils
- .renderMyfacesJSInlineIfNecessary(facesContext, writer);
- }
- }
-
- private static void renderConfigOptionsIfNecessary(FacesContext facesContext)
- throws IOException
- {
- ResponseWriter writer = facesContext.getResponseWriter();
- MyfacesConfig config = MyfacesConfig.getCurrentInstance(facesContext
- .getExternalContext());
- ScriptContext script = new ScriptContext(config.isPrettyHtml());
- boolean autoScroll = config.isAutoScroll();
- boolean autoSave = JavascriptUtils.isSaveFormSubmitLinkIE(facesContext
- .getExternalContext());
-
- if (autoScroll || autoSave)
- {
- script.prettyLine();
- script.increaseIndent();
- script.append("(!window.myfaces) ? window.myfaces = {} : null;");
- script.append("(!myfaces.core) ? myfaces.core = {} : null;");
- script.append("(!myfaces.core.config) ? myfaces.core.config = {} : null;");
- }
-
- if (autoScroll)
- {
- script.append("myfaces.core.config.autoScroll = true;");
- }
- if (autoSave)
- {
- script.append("myfaces.core.config.ieAutoSave = true;");
- }
- if (autoScroll || autoSave)
- {
- writer.startElement(HTML.SCRIPT_ELEM, null);
- writer.writeAttribute(HTML.TYPE_ATTR, "text/javascript", null);
- writer.writeText(script.toString(), null);
- writer.endElement(HTML.SCRIPT_ELEM);
- }
- }
- /**
- * @param facesContext
- * @param context
- * @param autoScroll
- */
- private static void prepareScript(FacesContext facesContext,
- ScriptContext context, boolean autoScroll)
- {
-
- final char separatorChar = UINamingContainer
- .getSeparatorChar(facesContext);
- context.prettyLine();
-
- //render a function to create a hidden input, if it doesn't exist
- context.append("function ");
- context.append(SET_HIDDEN_INPUT_FN_NAME).append(
- "(formname, name, value)");
- context.append("{");
- context.append("var form = document.forms[formname];");
- context.prettyLine();
- context.append("if (typeof form == 'undefined')");
- context.append("{");
- context.append("form = document.getElementById(formname);");
- context.append("}");
- context.prettyLine();
- context.append("if(typeof form.elements[name]!='undefined' && "+
- "(form.elements[name].nodeName=='INPUT' || form.elements[name].nodeName=='input'))");
- context.append("{");
- context.append("form.elements[name].value=value;");
- context.append("}");
- context.append("else");
- context.append("{");
- context.append("var newInput = document.createElement('input');");
- context.prettyLine();
- context.append("newInput.setAttribute('type','hidden');");
- context.prettyLine();
- context.append("newInput.setAttribute('id',name);"); // IE hack; See MYFACES-1805
- context.prettyLine();
- context.append("newInput.setAttribute('name',name);");
- context.prettyLine();
- context.append("newInput.setAttribute('value',value);");
- context.prettyLine();
- context.append("form.appendChild(newInput);");
- context.append("}");
-
- context.append("}");
-
- context.prettyLine();
-
- context.prettyLine();
-
- //render a function to clear a hidden input, if it exists
- context.append("function ");
- context.append(CLEAR_HIDDEN_INPUT_FN_NAME).append(
- "(formname, name, value)");
- context.append("{");
- context.append("var form = document.forms[formname];");
- context.prettyLine();
- context.append("if (typeof form == 'undefined')");
- context.append("{");
- context.append("form = document.getElementById(formname);");
- context.append("}");
- context.prettyLine();
- context.append("var hInput = form.elements[name];");
- context.prettyLine();
- context.append("if(typeof hInput !='undefined')");
- context.append("{");
- //context.append("form.elements[name].value=null;");
- context.append("form.removeChild(hInput);");
- context.append("}");
-
- context.append("}");
-
- context.prettyLine();
-
- context.append("function ");
- context.append(HtmlRendererUtils.SUBMIT_FORM_FN_NAME).append(
- "(formName, linkId, target, params)");
- context.append("{");
-
- //call the script to clear the form (clearFormHiddenParams_<formName>) method -
- //optionally, only necessary for IE5.5.
- //todo: if IE5.5. is ever desupported, we can get rid of this and instead rely on
- //the last part of this script to
- //clear the parameters
- appendClearHiddenCommandFormParamsFunctionCall(
- context, null);
-
- if (autoScroll)
- {
- appendAutoScrollAssignment(facesContext, context, null);
- }
-
- context.prettyLine();
-
- context.append("var form = document.forms[formName];");
- context.prettyLine();
- context.append("if (typeof form == 'undefined')");
- context.append("{");
- context.append("form = document.getElementById(formName);");
- context.append("}");
- context.prettyLine();
-
- if (JavascriptUtils.isSaveFormSubmitLinkIE(FacesContext
- .getCurrentInstance().getExternalContext()))
- {
- context.append("var agentString = navigator.userAgent.toLowerCase();");
- context.prettyLine();
- //context.append("var isIE = false;");
- context.prettyLine();
- context.append("if (agentString.indexOf('msie') != -1)");
-
- context.append("{");
- context.append("if (!(agentString.indexOf('ppc') != -1 &&"+
- " agentString.indexOf('windows ce') != -1 && version >= 4.0))");
- context.append("{");
- context.append("window.external.AutoCompleteSaveForm(form);");
- // context.append("isIE = false;");
- context.append("}");
- // context.append("else");
- // context.append("{");
- // context.append("isIE = true;");
- // context.prettyLine();
- // context.append("}");
-
- context.append("}");
-
- context.prettyLine();
- }
- //set the target (and save it). This should be done always,
- //and the default value of target is always valid.
- context.append("var oldTarget = form.target;");
- context.prettyLine();
- context.append("if(target != null)");
- context.append("{");
- context.prettyLine();
- context.append("form.target=target;");
- context.append("}");
-
- //set the submit parameters
-
- context.append("if((typeof params!='undefined') && params != null)");
- context.append("{");
- context.prettyLine();
- context.append("for(var i=0, param; (param = params[i]); i++)");
- context.append("{");
- context.append(SET_HIDDEN_INPUT_FN_NAME).append(
- "(formName,param[0], param[1]);");
- context.append("}");
- context.append("}");
-
- context.prettyLine();
-
- context.append(SET_HIDDEN_INPUT_FN_NAME);
- context.append("(formName,formName +'" + separatorChar + "'+'"
- + HtmlRendererUtils.HIDDEN_COMMANDLINK_FIELD_NAME
- + "',linkId);");
-
- context.prettyLine();
- context.prettyLine();
-
- //do the actual submit calls
-
- context.append("if(form.onsubmit)");
- context.append("{");
- context.append("var result=form.onsubmit();");
- context.prettyLine();
- context.append("if((typeof result=='undefined')||result)");
- context.append("{");
- context.append("try");
- context.append("{");
- context.append("form.submit();");
- context.append("}");
- context.append("catch(e){}");
- context.append("}");
- context.append("}");
- context.append("else ");
- context.append("{");
- context.append("try");
- context.append("{");
- context.append("form.submit();");
- context.append("}");
- context.append("catch(e){}");
- context.append("}");
-
- //reset the target
- context.prettyLine();
- //Restore the old target, no more questions asked
- context.append("form.target=oldTarget;");
- context.prettyLine();
-
- //clear the individual parameters - to make sure that even if the clear-function isn't called,
- // the back button/resubmit functionality will still work in all browsers except IE 5.5.
-
- context.append("if((typeof params!='undefined') && params != null)");
- context.append("{");
- context.prettyLine();
- context.append("for(var i=0, param; (param = params[i]); i++)");
- context.append("{");
- context.append(CLEAR_HIDDEN_INPUT_FN_NAME).append(
- "(formName,param[0], param[1]);");
- context.append("}");
- context.append("}");
-
- context.prettyLine();
-
- context.append(CLEAR_HIDDEN_INPUT_FN_NAME);
- context.append("(formName,formName +'" + separatorChar + "'+'"
- + HtmlRendererUtils.HIDDEN_COMMANDLINK_FIELD_NAME
- + "',linkId);");
-
- //return false, so that browser does not handle the click
- context.append("return false;");
- context.append("}");
-
- context.prettyLineDecreaseIndent();
- }
-
- public static void appendAutoScrollAssignment(StringBuilder onClickValue,
- String formName)
- {
- appendAutoScrollAssignment(FacesContext.getCurrentInstance(),
- new ScriptContext(onClickValue, false), formName);
- }
-
- /**
- * Adds the hidden form input value assignment that is necessary for the autoscroll
- * feature to an html link or button onclick attribute.
- */
- public static void appendAutoScrollAssignment(FacesContext context,
- StringBuilder onClickValue, String formName)
- {
- appendAutoScrollAssignment(context, new ScriptContext(onClickValue,
- false), formName);
- }
-
- private static void appendAutoScrollAssignment(FacesContext context,
- ScriptContext scriptContext, String formName)
- {
- String formNameStr = formName == null ? "formName" : (new StringBuilder(
- "'").append(formName).append("'").toString());
- String paramName = new StringBuilder().append("'")
- .append(AUTO_SCROLL_PARAM).append("'").toString();
- String value = new StringBuilder().append(AUTO_SCROLL_FUNCTION)
- .append("()").toString();
-
- scriptContext.prettyLine();
- scriptContext.append("if(typeof window." + AUTO_SCROLL_FUNCTION
- + "!='undefined')");
- scriptContext.append("{");
- if (MyfacesConfig.getCurrentInstance(context.getExternalContext())
- .isRenderFormSubmitScriptInline())
- {
- scriptContext.append(SET_HIDDEN_INPUT_FN_NAME);
- }
- else
- {
- scriptContext.append(SET_HIDDEN_INPUT_FN_NAME_JSF2);
- }
- scriptContext.append("(").append(formNameStr).append(",")
- .append(paramName).append(",").append(value).append(");");
- scriptContext.append("}");
-
- }
-
- public static String getAutoScrollFunction(FacesContext facesContext)
- {
- ScriptContext script = new ScriptContext(MyfacesConfig
- .getCurrentInstance(facesContext.getExternalContext())
- .isPrettyHtml());
-
- script.prettyLineIncreaseIndent();
-
- script.append("function ");
- script.append(AUTO_SCROLL_FUNCTION);
- script.append("()");
- script.append("{");
- script.append("var x = 0; var y = 0;");
- script.append("if (self.pageXOffset || self.pageYOffset)");
- script.append("{");
- script.append("x = self.pageXOffset;");
- script.prettyLine();
- script.append("y = self.pageYOffset;");
- script.append("}");
- script.append(" else if ((document.documentElement && document.documentElement.scrollLeft)||"+
- "(document.documentElement && document.documentElement.scrollTop))");
- script.append("{");
- script.append("x = document.documentElement.scrollLeft;");
- script.prettyLine();
- script.append("y = document.documentElement.scrollTop;");
- script.append("}");
- script.append(" else if (document.body) ");
- script.append("{");
- script.append("x = document.body.scrollLeft;");
- script.prettyLine();
- script.append("y = document.body.scrollTop;");
- script.append("}");
- script.append("return x + \",\" + y;");
- script.append("}");
-
- ExternalContext externalContext = facesContext.getExternalContext();
- String oldViewId = JavascriptUtils.getOldViewId(externalContext);
- if (oldViewId != null
- && oldViewId.equals(facesContext.getViewRoot().getViewId()))
- {
- //ok, we stayed on the same page, so let's scroll it to the former place
- String scrolling = (String) externalContext
- .getRequestParameterMap().get(AUTO_SCROLL_PARAM);
- if (scrolling != null && scrolling.length() > 0)
- {
- int x = 0;
- int y = 0;
- int comma = scrolling.indexOf(',');
- if (comma == -1)
- {
- log.warning("Illegal autoscroll request parameter: "
- + scrolling);
- }
- else
- {
- try
- {
- //we convert to int against XSS vulnerability
- x = Integer.parseInt(scrolling.substring(0, comma));
- }
- catch (NumberFormatException e)
- {
- log.warning("Error getting x offset for autoscroll feature. Bad param value: "
- + scrolling);
- x = 0; //ignore false numbers
- }
-
- try
- {
- //we convert to int against XSS vulnerability
- y = Integer.parseInt(scrolling.substring(comma + 1));
- }
- catch (NumberFormatException e)
- {
- log.warning("Error getting y offset for autoscroll feature. Bad param value: "
- + scrolling);
- y = 0; //ignore false numbers
- }
- }
- script.append("window.scrollTo(").append(x).append(",")
- .append(y).append(");\n");
- }
- }
-
- return script.toString();
- }
-
- /**
- * Renders the hidden form input that is necessary for the autoscroll feature.
- */
- public static void renderAutoScrollHiddenInput(FacesContext facesContext,
- ResponseWriter writer) throws IOException
- {
- HtmlRendererUtils.writePrettyLineSeparator(facesContext);
- writer.startElement(HTML.INPUT_ELEM, null);
- writer.writeAttribute(HTML.TYPE_ATTR, "hidden", null);
- writer.writeAttribute(HTML.NAME_ATTR, AUTO_SCROLL_PARAM, null);
- writer.endElement(HTML.INPUT_ELEM);
- HtmlRendererUtils.writePrettyLineSeparator(facesContext);
- }
-
- /**
- * Renders the autoscroll javascript function.
- */
- public static void renderAutoScrollFunction(FacesContext facesContext,
- ResponseWriter writer) throws IOException
- {
- HtmlRendererUtils.writePrettyLineSeparator(facesContext);
- writer.startElement(HTML.SCRIPT_ELEM, null);
- writer.writeAttribute(HTML.SCRIPT_TYPE_ATTR,
- HTML.SCRIPT_TYPE_TEXT_JAVASCRIPT, null);
- writer.writeText(getAutoScrollFunction(facesContext), null);
- writer.endElement(HTML.SCRIPT_ELEM);
- HtmlRendererUtils.writePrettyLineSeparator(facesContext);
- }
-
- public static void appendClearHiddenCommandFormParamsFunctionCall(
- StringBuilder buf, String formName)
- {
- appendClearHiddenCommandFormParamsFunctionCall(new ScriptContext(buf,
- false), formName);
- }
-
- private static void appendClearHiddenCommandFormParamsFunctionCall(
- ScriptContext context, String formName)
- {
- String functionName = HtmlRendererUtils
- .getClearHiddenCommandFormParamsFunctionName(formName);
- if (formName == null)
- {
- context.prettyLine();
- context.append("var clearFn = ");
- context.append(functionName);
- context.append(";");
- context.prettyLine();
- context.append("if(typeof window[clearFn] =='function')");
- context.append("{");
- context.append("window[clearFn](formName);");
- context.append("}");
- }
- else
- {
- context.prettyLine();
- context.append("if(typeof window.");
- context.append(functionName);
- context.append("=='function')");
- context.append("{");
- context.append(functionName).append("('").append(formName)
- .append("');");
- context.append("}");
- }
- }
-
- /**
- * Prefixes the given String with "clear_" and removes special characters
- *
- * @param formName
- * @return String
- */
- public static String getClearHiddenCommandFormParamsFunctionName(
- String formName)
- {
- final char separatorChar = UINamingContainer
- .getSeparatorChar(FacesContext.getCurrentInstance());
- if (formName == null)
- {
- return "'" + HtmlRendererUtils.CLEAR_HIDDEN_FIELD_FN_NAME
- + "_'+formName.replace(/-/g, '\\$" + separatorChar
- + "').replace(/" + separatorChar + "/g,'_')";
- }
-
- return JavascriptUtils
- .getValidJavascriptNameAsInRI(HtmlRendererUtils.CLEAR_HIDDEN_FIELD_FN_NAME + "_"
- + formName.replace(separatorChar, '_'));
- }
-
- public static String getClearHiddenCommandFormParamsFunctionNameMyfacesLegacy(
- String formName)
- {
- return "clear_"
- + JavascriptUtils.getValidJavascriptName(formName, false);
- }
-
- /**
- * Render the javascript function that is called on a click on a commandLink
- * to clear the hidden inputs. This is necessary because on a browser back,
- * each hidden input still has it's old value (browser cache!) and therefore
- * a new submit would cause the according action once more!
- *
- * @param writer
- * @param formName
- * @param dummyFormParams
- * @param formTarget
- * @throws IOException
- */
- public static void renderClearHiddenCommandFormParamsFunction(
- ResponseWriter writer, String formName, Set dummyFormParams,
- String formTarget) throws IOException
- {
- //render the clear hidden inputs javascript function
- String functionName = getClearHiddenCommandFormParamsFunctionName(formName);
- writer.startElement(HTML.SCRIPT_ELEM, null);
- writer.writeAttribute(HTML.TYPE_ATTR, "text/javascript", null);
-
- // Using writeComment instead of write with <!-- tag
- StringBuilder script = new StringBuilder();
- script.append("function ");
- script.append(functionName);
- script.append("() {");
- if (dummyFormParams != null)
- {
- script.append("\n var f = document.forms['");
- script.append(formName);
- script.append("'];");
- int i = 0;
- for (Iterator it = dummyFormParams.iterator(); it.hasNext();)
- {
- String elemVarName = "elem" + i;
- script.append("\n var ").append(elemVarName).append(" = ");
- script.append("f.elements['").append((String) it.next())
- .append("'];");
- script.append("\n if(typeof ").append(elemVarName)
- .append(" !='undefined' && ");
- script.append(elemVarName).append(".nodeName=='INPUT'){");
- script.append("\n if (").append(elemVarName)
- .append(".value != '') {");
- script.append("\n " + elemVarName + ".value='';");
- script.append("\n }");
- script.append("\n }");
- i++;
- }
- }
- // clear form target
- script.append("\n f.target=");
- if (formTarget == null || formTarget.length() == 0)
- {
- //Normally one would think that setting target to null has the
- //desired effect, but once again IE is different...
- //Setting target to null causes IE to open a new window!
- script.append("'';");
- }
- else
- {
- script.append("'");
- script.append(formTarget);
- script.append("';");
- }
- script.append("\n}");
-
- //Just to be sure we call this clear method on each load.
- //Otherwise in the case, that someone submits a form by pressing Enter
- //within a text input, the hidden inputs won't be cleared!
- script.append("\n");
- script.append(functionName);
- script.append("();");
-
- writer.writeText(script.toString(), null);
- writer.endElement(HTML.SCRIPT_ELEM);
- }
-
- /**
- * This function correctly escapes the given JavaScript code
- * for the use in the jsf.util.chain() JavaScript function.
- * It also handles double-escaping correclty.
- *
- * @param javaScript
- * @return
- */
- public static String escapeJavaScriptForChain(String javaScript)
- {
- // first replace \' with \\'
- //String escaped = StringUtils.replace(javaScript, "\\'", "\\\\'");
-
- // then replace ' with \'
- // (this will replace every \' in the original to \\\')
- //escaped = StringUtils.replace(escaped, '\'', "\\'");
-
- //return escaped;
-
- StringBuilder out = null;
- for (int pos = 0; pos < javaScript.length(); pos++)
- {
- char c = javaScript.charAt(pos);
-
- if (c == '\\' || c == '\'')
- {
- if (out == null)
- {
- out = new StringBuilder(javaScript.length() + 8);
- if (pos > 0)
- {
- out.append(javaScript, 0, pos);
- }
- }
- out.append('\\');
- }
- if (out != null)
- {
- out.append(c);
- }
- }
-
- if (out == null)
- {
- return javaScript;
- }
- else
- {
- return out.toString();
- }
- }
-
- public static void renderViewStateJavascript(FacesContext facesContext,
- String hiddenId, String serializedState) throws IOException
- {
- ResponseWriter writer = facesContext.getResponseWriter();
-
- writer.startElement(HTML.SCRIPT_ELEM, null);
- writer.writeAttribute(HTML.TYPE_ATTR, "text/javascript", null);
-
- final ExternalContext externalContext = facesContext
- .getExternalContext();
- final MyfacesConfig currentInstance = MyfacesConfig
- .getCurrentInstance(externalContext);
-
- ScriptContext context = new ScriptContext(
- currentInstance.isPrettyHtml());
- context.prettyLine();
- context.increaseIndent();
-
- context.append("function setViewState() {\n");
- context.append("\tvar state = '");
- context.append(serializedState);
- context.append("';\n");
- context.append("\tfor (var i = 0; i < document.forms.length; i++) {\n");
- context.append("\t\tdocument.forms[i]['" + hiddenId
- + "'].value = state;\n");
- context.append("\t}\n");
- context.append("}\n");
- context.append("setViewState();\n");
-
- context.decreaseIndent();
-
- writer.writeText(context.toString(), null);
-
- writer.endElement(HTML.SCRIPT_ELEM);
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.myfaces.shared.renderkit.html;
+
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.logging.Logger;
+
+import javax.faces.component.UINamingContainer;
+import javax.faces.context.ExternalContext;
+import javax.faces.context.FacesContext;
+import javax.faces.context.ResponseWriter;
+
+import org.apache.myfaces.shared.config.MyfacesConfig;
+import org.apache.myfaces.shared.renderkit.html.HtmlRendererUtils.ScriptContext;
+import org.apache.myfaces.shared.renderkit.html.util.JavascriptUtils;
+import org.apache.myfaces.shared.renderkit.html.util.ResourceUtils;
+
+public final class HtmlJavaScriptUtils
+{
+ private static final Logger log = Logger.getLogger(HtmlJavaScriptUtils.class
+ .getName());
+
+ private static final String AUTO_SCROLL_PARAM = "autoScroll";
+ private static final String AUTO_SCROLL_FUNCTION = "getScrolling";
+
+ private static final String SET_HIDDEN_INPUT_FN_NAME = "oamSetHiddenInput";
+ private static final String SET_HIDDEN_INPUT_FN_NAME_JSF2 = "myfaces.oam.setHiddenInput";
+
+ private static final String FIRST_SUBMIT_SCRIPT_ON_PAGE = "org.apache.MyFaces.FIRST_SUBMIT_SCRIPT_ON_PAGE";
+ private static final String CLEAR_HIDDEN_INPUT_FN_NAME = "oamClearHiddenInput";
+
+
+ @SuppressWarnings("unchecked")
+ public static void renderFormSubmitScript(FacesContext facesContext)
+ throws IOException
+ {
+ if (facesContext.getPartialViewContext() != null &&
+ (facesContext.getPartialViewContext().isPartialRequest() ||
+ facesContext.getPartialViewContext().isAjaxRequest() )
+ )
+ {
+ return;
+ }
+
+ Map map = facesContext.getExternalContext().getRequestMap();
+ Boolean firstScript = (Boolean) map.get(FIRST_SUBMIT_SCRIPT_ON_PAGE);
+
+ if (firstScript == null || firstScript.equals(Boolean.TRUE))
+ {
+ map.put(FIRST_SUBMIT_SCRIPT_ON_PAGE, Boolean.FALSE);
+ renderFormSubmitScriptIfNecessary(facesContext);
+
+ //we have to render the config just in case
+ renderConfigOptionsIfNecessary(facesContext);
+ }
+ }
+
+ /**
+ * @param facesContext
+ * @throws IOException
+ */
+ private static void renderFormSubmitScriptIfNecessary(
+ FacesContext facesContext) throws IOException
+ {
+ final ExternalContext externalContext = facesContext
+ .getExternalContext();
+ final MyfacesConfig currentInstance = MyfacesConfig
+ .getCurrentInstance(externalContext);
+ ResponseWriter writer = facesContext.getResponseWriter();
+
+ if (currentInstance.isRenderFormSubmitScriptInline())
+ {
+ writer.startElement(HTML.SCRIPT_ELEM, null);
+ writer.writeAttribute(HTML.TYPE_ATTR, "text/javascript", null);
+
+ boolean autoScroll = currentInstance.isAutoScroll();
+
+ ScriptContext context = new ScriptContext(
+ currentInstance.isPrettyHtml());
+ context.prettyLine();
+ context.increaseIndent();
+
+ prepareScript(facesContext, context, autoScroll);
+
+ writer.writeText(context.toString(), null);
+
+ writer.endElement(HTML.SCRIPT_ELEM);
+ }
+ else
+ {
+ ResourceUtils
+ .renderMyfacesJSInlineIfNecessary(facesContext, writer);
+ }
+ }
+
+ private static void renderConfigOptionsIfNecessary(FacesContext facesContext)
+ throws IOException
+ {
+ ResponseWriter writer = facesContext.getResponseWriter();
+ MyfacesConfig config = MyfacesConfig.getCurrentInstance(facesContext
+ .getExternalContext());
+ ScriptContext script = new ScriptContext(config.isPrettyHtml());
+ boolean autoScroll = config.isAutoScroll();
+ boolean autoSave = JavascriptUtils.isSaveFormSubmitLinkIE(facesContext
+ .getExternalContext());
+
+ if (autoScroll || autoSave)
+ {
+ script.prettyLine();
+ script.increaseIndent();
+ script.append("(!window.myfaces) ? window.myfaces = {} : null;");
+ script.append("(!myfaces.core) ? myfaces.core = {} : null;");
+ script.append("(!myfaces.core.config) ? myfaces.core.config = {} : null;");
+ }
+
+ if (autoScroll)
+ {
+ script.append("myfaces.core.config.autoScroll = true;");
+ }
+ if (autoSave)
+ {
+ script.append("myfaces.core.config.ieAutoSave = true;");
+ }
+ if (autoScroll || autoSave)
+ {
+ writer.startElement(HTML.SCRIPT_ELEM, null);
+ writer.writeAttribute(HTML.TYPE_ATTR, "text/javascript", null);
+ writer.writeText(script.toString(), null);
+ writer.endElement(HTML.SCRIPT_ELEM);
+ }
+ }
+ /**
+ * @param facesContext
+ * @param context
+ * @param autoScroll
+ */
+ private static void prepareScript(FacesContext facesContext,
+ ScriptContext context, boolean autoScroll)
+ {
+
+ final char separatorChar = UINamingContainer
+ .getSeparatorChar(facesContext);
+ context.prettyLine();
+
+ //render a function to create a hidden input, if it doesn't exist
+ context.append("function ");
+ context.append(SET_HIDDEN_INPUT_FN_NAME).append(
+ "(formname, name, value)");
+ context.append("{");
+ context.append("var form = document.forms[formname];");
+ context.prettyLine();
+ context.append("if (typeof form == 'undefined')");
+ context.append("{");
+ context.append("form = document.getElementById(formname);");
+ context.append("}");
+ context.prettyLine();
+ context.append("if(typeof form.elements[name]!='undefined' && "+
+ "(form.elements[name].nodeName=='INPUT' || form.elements[name].nodeName=='input'))");
+ context.append("{");
+ context.append("form.elements[name].value=value;");
+ context.append("}");
+ context.append("else");
+ context.append("{");
+ context.append("var newInput = document.createElement('input');");
+ context.prettyLine();
+ context.append("newInput.setAttribute('type','hidden');");
+ context.prettyLine();
+ context.append("newInput.setAttribute('id',name);"); // IE hack; See MYFACES-1805
+ context.prettyLine();
+ context.append("newInput.setAttribute('name',name);");
+ context.prettyLine();
+ context.append("newInput.setAttribute('value',value);");
+ context.prettyLine();
+ context.append("form.appendChild(newInput);");
+ context.append("}");
+
+ context.append("}");
+
+ context.prettyLine();
+
+ context.prettyLine();
+
+ //render a function to clear a hidden input, if it exists
+ context.append("function ");
+ context.append(CLEAR_HIDDEN_INPUT_FN_NAME).append(
+ "(formname, name, value)");
+ context.append("{");
+ context.append("var form = document.forms[formname];");
+ context.prettyLine();
+ context.append("if (typeof form == 'undefined')");
+ context.append("{");
+ context.append("form = document.getElementById(formname);");
+ context.append("}");
+ context.prettyLine();
+ context.append("var hInput = form.elements[name];");
+ context.prettyLine();
+ context.append("if(typeof hInput !='undefined')");
+ context.append("{");
+ //context.append("form.elements[name].value=null;");
+ context.append("form.removeChild(hInput);");
+ context.append("}");
+
+ context.append("}");
+
+ context.prettyLine();
+
+ context.append("function ");
+ context.append(HtmlRendererUtils.SUBMIT_FORM_FN_NAME).append(
+ "(formName, linkId, target, params)");
+ context.append("{");
+
+ //call the script to clear the form (clearFormHiddenParams_<formName>) method -
+ //optionally, only necessary for IE5.5.
+ //todo: if IE5.5. is ever desupported, we can get rid of this and instead rely on
+ //the last part of this script to
+ //clear the parameters
+ appendClearHiddenCommandFormParamsFunctionCall(
+ context, null);
+
+ if (autoScroll)
+ {
+ appendAutoScrollAssignment(facesContext, context, null);
+ }
+
+ context.prettyLine();
+
+ context.append("var form = document.forms[formName];");
+ context.prettyLine();
+ context.append("if (typeof form == 'undefined')");
+ context.append("{");
+ context.append("form = document.getElementById(formName);");
+ context.append("}");
+ context.prettyLine();
+
+ if (JavascriptUtils.isSaveFormSubmitLinkIE(FacesContext
+ .getCurrentInstance().getExternalContext()))
+ {
+ context.append("var agentString = navigator.userAgent.toLowerCase();");
+ context.prettyLine();
+ //context.append("var isIE = false;");
+ context.prettyLine();
+ context.append("if (agentString.indexOf('msie') != -1)");
+
+ context.append("{");
+ context.append("if (!(agentString.indexOf('ppc') != -1 &&"+
+ " agentString.indexOf('windows ce') != -1 && version >= 4.0))");
+ context.append("{");
+ context.append("window.external.AutoCompleteSaveForm(form);");
+ // context.append("isIE = false;");
+ context.append("}");
+ // context.append("else");
+ // context.append("{");
+ // context.append("isIE = true;");
+ // context.prettyLine();
+ // context.append("}");
+
+ context.append("}");
+
+ context.prettyLine();
+ }
+ //set the target (and save it). This should be done always,
+ //and the default value of target is always valid.
+ context.append("var oldTarget = form.target;");
+ context.prettyLine();
+ context.append("if(target != null)");
+ context.append("{");
+ context.prettyLine();
+ context.append("form.target=target;");
+ context.append("}");
+
+ //set the submit parameters
+
+ context.append("if((typeof params!='undefined') && params != null)");
+ context.append("{");
+ context.prettyLine();
+ context.append("for(var i=0, param; (param = params[i]); i++)");
+ context.append("{");
+ context.append(SET_HIDDEN_INPUT_FN_NAME).append(
+ "(formName,param[0], param[1]);");
+ context.append("}");
+ context.append("}");
+
+ context.prettyLine();
+
+ context.append(SET_HIDDEN_INPUT_FN_NAME);
+ context.append("(formName,formName +'" + separatorChar + "'+'"
+ + HtmlRendererUtils.HIDDEN_COMMANDLINK_FIELD_NAME
+ + "',linkId);");
+
+ context.prettyLine();
+ context.prettyLine();
+
+ //do the actual submit calls
+
+ context.append("if(form.onsubmit)");
+ context.append("{");
+ context.append("var result=form.onsubmit();");
+ context.prettyLine();
+ context.append("if((typeof result=='undefined')||result)");
+ context.append("{");
+ context.append("try");
+ context.append("{");
+ context.append("form.submit();");
+ context.append("}");
+ context.append("catch(e){}");
+ context.append("}");
+ context.append("}");
+ context.append("else ");
+ context.append("{");
+ context.append("try");
+ context.append("{");
+ context.append("form.submit();");
+ context.append("}");
+ context.append("catch(e){}");
+ context.append("}");
+
+ //reset the target
+ context.prettyLine();
+ //Restore the old target, no more questions asked
+ context.append("form.target=oldTarget;");
+ context.prettyLine();
+
+ //clear the individual parameters - to make sure that even if the clear-function isn't called,
+ // the back button/resubmit functionality will still work in all browsers except IE 5.5.
+
+ context.append("if((typeof params!='undefined') && params != null)");
+ context.append("{");
+ context.prettyLine();
+ context.append("for(var i=0, param; (param = params[i]); i++)");
+ context.append("{");
+ context.append(CLEAR_HIDDEN_INPUT_FN_NAME).append(
+ "(formName,param[0], param[1]);");
+ context.append("}");
+ context.append("}");
+
+ context.prettyLine();
+
+ context.append(CLEAR_HIDDEN_INPUT_FN_NAME);
+ context.append("(formName,formName +'" + separatorChar + "'+'"
+ + HtmlRendererUtils.HIDDEN_COMMANDLINK_FIELD_NAME
+ + "',linkId);");
+
+ //return false, so that browser does not handle the click
+ context.append("return false;");
+ context.append("}");
+
+ context.prettyLineDecreaseIndent();
+ }
+
+ public static void appendAutoScrollAssignment(StringBuilder onClickValue,
+ String formName)
+ {
+ appendAutoScrollAssignment(FacesContext.getCurrentInstance(),
+ new ScriptContext(onClickValue, false), formName);
+ }
+
+ /**
+ * Adds the hidden form input value assignment that is necessary for the autoscroll
+ * feature to an html link or button onclick attribute.
+ */
+ public static void appendAutoScrollAssignment(FacesContext context,
+ StringBuilder onClickValue, String formName)
+ {
+ appendAutoScrollAssignment(context, new ScriptContext(onClickValue,
+ false), formName);
+ }
+
+ private static void appendAutoScrollAssignment(FacesContext context,
+ ScriptContext scriptContext, String formName)
+ {
+ String formNameStr = formName == null ? "formName" : (new StringBuilder(
+ "'").append(formName).append("'").toString());
+ String paramName = new StringBuilder().append("'")
+ .append(AUTO_SCROLL_PARAM).append("'").toString();
+ String value = new StringBuilder().append(AUTO_SCROLL_FUNCTION)
+ .append("()").toString();
+
+ scriptContext.prettyLine();
+ scriptContext.append("if(typeof window." + AUTO_SCROLL_FUNCTION
+ + "!='undefined')");
+ scriptContext.append("{");
+ if (MyfacesConfig.getCurrentInstance(context.getExternalContext())
+ .isRenderFormSubmitScriptInline())
+ {
+ scriptContext.append(SET_HIDDEN_INPUT_FN_NAME);
+ }
+ else
+ {
+ scriptContext.append(SET_HIDDEN_INPUT_FN_NAME_JSF2);
+ }
+ scriptContext.append("(").append(formNameStr).append(",")
+ .append(paramName).append(",").append(value).append(");");
+ scriptContext.append("}");
+
+ }
+
+ public static String getAutoScrollFunction(FacesContext facesContext)
+ {
+ ScriptContext script = new ScriptContext(MyfacesConfig
+ .getCurrentInstance(facesContext.getExternalContext())
+ .isPrettyHtml());
+
+ script.prettyLineIncreaseIndent();
+
+ script.append("function ");
+ script.append(AUTO_SCROLL_FUNCTION);
+ script.append("()");
+ script.append("{");
+ script.append("var x = 0; var y = 0;");
+ script.append("if (self.pageXOffset || self.pageYOffset)");
+ script.append("{");
+ script.append("x = self.pageXOffset;");
+ script.prettyLine();
+ script.append("y = self.pageYOffset;");
+ script.append("}");
+ script.append(" else if ((document.documentElement && document.documentElement.scrollLeft)||"+
+ "(document.documentElement && document.documentElement.scrollTop))");
+ script.append("{");
+ script.append("x = document.documentElement.scrollLeft;");
+ script.prettyLine();
+ script.append("y = document.documentElement.scrollTop;");
+ script.append("}");
+ script.append(" else if (document.body) ");
+ script.append("{");
+ script.append("x = document.body.scrollLeft;");
+ script.prettyLine();
+ script.append("y = document.body.scrollTop;");
+ script.append("}");
+ script.append("return x + \",\" + y;");
+ script.append("}");
+
+ ExternalContext externalContext = facesContext.getExternalContext();
+ String oldViewId = JavascriptUtils.getOldViewId(externalContext);
+ if (oldViewId != null
+ && oldViewId.equals(facesContext.getViewRoot().getViewId()))
+ {
+ //ok, we stayed on the same page, so let's scroll it to the former place
+ String scrolling = (String) externalContext
+ .getRequestParameterMap().get(AUTO_SCROLL_PARAM);
+ if (scrolling != null && scrolling.length() > 0)
+ {
+ int x = 0;
+ int y = 0;
+ int comma = scrolling.indexOf(',');
+ if (comma == -1)
+ {
+ log.warning("Illegal autoscroll request parameter: "
+ + scrolling);
+ }
+ else
+ {
+ try
+ {
+ //we convert to int against XSS vulnerability
+ x = Integer.parseInt(scrolling.substring(0, comma));
+ }
+ catch (NumberFormatException e)
+ {
+ log.warning("Error getting x offset for autoscroll feature. Bad param value: "
+ + scrolling);
+ x = 0; //ignore false numbers
+ }
+
+ try
+ {
+ //we convert to int against XSS vulnerability
+ y = Integer.parseInt(scrolling.substring(comma + 1));
+ }
+ catch (NumberFormatException e)
+ {
+ log.warning("Error getting y offset for autoscroll feature. Bad param value: "
+ + scrolling);
+ y = 0; //ignore false numbers
+ }
+ }
+ script.append("window.scrollTo(").append(x).append(",")
+ .append(y).append(");\n");
+ }
+ }
+
+ return script.toString();
+ }
+
+ /**
+ * Renders the hidden form input that is necessary for the autoscroll feature.
+ */
+ public static void renderAutoScrollHiddenInput(FacesContext facesContext,
+ ResponseWriter writer) throws IOException
+ {
+ HtmlRendererUtils.writePrettyLineSeparator(facesContext);
+ writer.startElement(HTML.INPUT_ELEM, null);
+ writer.writeAttribute(HTML.TYPE_ATTR, "hidden", null);
+ writer.writeAttribute(HTML.NAME_ATTR, AUTO_SCROLL_PARAM, null);
+ writer.endElement(HTML.INPUT_ELEM);
+ HtmlRendererUtils.writePrettyLineSeparator(facesContext);
+ }
+
+ /**
+ * Renders the autoscroll javascript function.
+ */
+ public static void renderAutoScrollFunction(FacesContext facesContext,
+ ResponseWriter writer) throws IOException
+ {
+ HtmlRendererUtils.writePrettyLineSeparator(facesContext);
+ writer.startElement(HTML.SCRIPT_ELEM, null);
+ writer.writeAttribute(HTML.SCRIPT_TYPE_ATTR,
+ HTML.SCRIPT_TYPE_TEXT_JAVASCRIPT, null);
+ writer.writeText(getAutoScrollFunction(facesContext), null);
+ writer.endElement(HTML.SCRIPT_ELEM);
+ HtmlRendererUtils.writePrettyLineSeparator(facesContext);
+ }
+
+ public static void appendClearHiddenCommandFormParamsFunctionCall(
+ StringBuilder buf, String formName)
+ {
+ appendClearHiddenCommandFormParamsFunctionCall(new ScriptContext(buf,
+ false), formName);
+ }
+
+ private static void appendClearHiddenCommandFormParamsFunctionCall(
+ ScriptContext context, String formName)
+ {
+ String functionName = HtmlRendererUtils
+ .getClearHiddenCommandFormParamsFunctionName(formName);
+ if (formName == null)
+ {
+ context.prettyLine();
+ context.append("var clearFn = ");
+ context.append(functionName);
+ context.append(";");
+ context.prettyLine();
+ context.append("if(typeof window[clearFn] =='function')");
+ context.append("{");
+ context.append("window[clearFn](formName);");
+ context.append("}");
+ }
+ else
+ {
+ context.prettyLine();
+ context.append("if(typeof window.");
+ context.append(functionName);
+ context.append("=='function')");
+ context.append("{");
+ context.append(functionName).append("('").append(formName)
+ .append("');");
+ context.append("}");
+ }
+ }
+
+ /**
+ * Prefixes the given String with "clear_" and removes special characters
+ *
+ * @param formName
+ * @return String
+ */
+ public static String getClearHiddenCommandFormParamsFunctionName(
+ String formName)
+ {
+ final char separatorChar = UINamingContainer
+ .getSeparatorChar(FacesContext.getCurrentInstance());
+ if (formName == null)
+ {
+ return "'" + HtmlRendererUtils.CLEAR_HIDDEN_FIELD_FN_NAME
+ + "_'+formName.replace(/-/g, '\\$" + separatorChar
+ + "').replace(/" + separatorChar + "/g,'_')";
+ }
+
+ return JavascriptUtils
+ .getValidJavascriptNameAsInRI(HtmlRendererUtils.CLEAR_HIDDEN_FIELD_FN_NAME + "_"
+ + formName.replace(separatorChar, '_'));
+ }
+
+ public static String getClearHiddenCommandFormParamsFunctionNameMyfacesLegacy(
+ String formName)
+ {
+ return "clear_"
+ + JavascriptUtils.getValidJavascriptName(formName, false);
+ }
+
+ /**
+ * Render the javascript function that is called on a click on a commandLink
+ * to clear the hidden inputs. This is necessary because on a browser back,
+ * each hidden input still has it's old value (browser cache!) and therefore
+ * a new submit would cause the according action once more!
+ *
+ * @param writer
+ * @param formName
+ * @param dummyFormParams
+ * @param formTarget
+ * @throws IOException
+ */
+ public static void renderClearHiddenCommandFormParamsFunction(
+ ResponseWriter writer, String formName, Set dummyFormParams,
+ String formTarget) throws IOException
+ {
+ //render the clear hidden inputs javascript function
+ String functionName = getClearHiddenCommandFormParamsFunctionName(formName);
+ writer.startElement(HTML.SCRIPT_ELEM, null);
+ writer.writeAttribute(HTML.TYPE_ATTR, "text/javascript", null);
+
+ // Using writeComment instead of write with <!-- tag
+ StringBuilder script = new StringBuilder();
+ script.append("function ");
+ script.append(functionName);
+ script.append("() {");
+ if (dummyFormParams != null)
+ {
+ script.append("\n var f = document.forms['");
+ script.append(formName);
+ script.append("'];");
+ int i = 0;
+ for (Iterator it = dummyFormParams.iterator(); it.hasNext();)
+ {
+ String elemVarName = "elem" + i;
+ script.append("\n var ").append(elemVarName).append(" = ");
+ script.append("f.elements['").append((String) it.next())
+ .append("'];");
+ script.append("\n if(typeof ").append(elemVarName)
+ .append(" !='undefined' && ");
+ script.append(elemVarName).append(".nodeName=='INPUT'){");
+ script.append("\n if (").append(elemVarName)
+ .append(".value != '') {");
+ script.append("\n " + elemVarName + ".value='';");
+ script.append("\n }");
+ script.append("\n }");
+ i++;
+ }
+ }
+ // clear form target
+ script.append("\n f.target=");
+ if (formTarget == null || formTarget.length() == 0)
+ {
+ //Normally one would think that setting target to null has the
+ //desired effect, but once again IE is different...
+ //Setting target to null causes IE to open a new window!
+ script.append("'';");
+ }
+ else
+ {
+ script.append("'");
+ script.append(formTarget);
+ script.append("';");
+ }
+ script.append("\n}");
+
+ //Just to be sure we call this clear method on each load.
+ //Otherwise in the case, that someone submits a form by pressing Enter
+ //within a text input, the hidden inputs won't be cleared!
+ script.append("\n");
+ script.append(functionName);
+ script.append("();");
+
+ writer.writeText(script.toString(), null);
+ writer.endElement(HTML.SCRIPT_ELEM);
+ }
+
+ /**
+ * This function correctly escapes the given JavaScript code
+ * for the use in the jsf.util.chain() JavaScript function.
+ * It also handles double-escaping correclty.
+ *
+ * @param javaScript
+ * @return
+ */
+ public static String escapeJavaScriptForChain(String javaScript)
+ {
+ // first replace \' with \\'
+ //String escaped = StringUtils.replace(javaScript, "\\'", "\\\\'");
+
+ // then replace ' with \'
+ // (this will replace every \' in the original to \\\')
+ //escaped = StringUtils.replace(escaped, '\'', "\\'");
+
+ //return escaped;
+
+ StringBuilder out = null;
+ for (int pos = 0; pos < javaScript.length(); pos++)
+ {
+ char c = javaScript.charAt(pos);
+
+ if (c == '\\' || c == '\'')
+ {
+ if (out == null)
+ {
+ out = new StringBuilder(javaScript.length() + 8);
+ if (pos > 0)
+ {
+ out.append(javaScript, 0, pos);
+ }
+ }
+ out.append('\\');
+ }
+ if (out != null)
+ {
+ out.append(c);
+ }
+ }
+
+ if (out == null)
+ {
+ return javaScript;
+ }
+ else
+ {
+ return out.toString();
+ }
+ }
+
+ public static void renderViewStateJavascript(FacesContext facesContext,
+ String hiddenId, String serializedState) throws IOException
+ {
+ ResponseWriter writer = facesContext.getResponseWriter();
+
+ writer.startElement(HTML.SCRIPT_ELEM, null);
+ writer.writeAttribute(HTML.TYPE_ATTR, "text/javascript", null);
+
+ final ExternalContext externalContext = facesContext
+ .getExternalContext();
+ final MyfacesConfig currentInstance = MyfacesConfig
+ .getCurrentInstance(externalContext);
+
+ ScriptContext context = new ScriptContext(
+ currentInstance.isPrettyHtml());
+ context.prettyLine();
+ context.increaseIndent();
+
+ context.append("function setViewState() {\n");
+ context.append("\tvar state = '");
+ context.append(serializedState);
+ context.append("';\n");
+ context.append("\tfor (var i = 0; i < document.forms.length; i++) {\n");
+ context.append("\t\tdocument.forms[i]['" + hiddenId
+ + "'].value = state;\n");
+ context.append("\t}\n");
+ context.append("}\n");
+ context.append("setViewState();\n");
+
+ context.decreaseIndent();
+
+ writer.writeText(context.toString(), null);
+
+ writer.endElement(HTML.SCRIPT_ELEM);
+ }
+}
Modified: myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlLinkRendererBase.java
URL: http://svn.apache.org/viewvc/myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlLinkRendererBase.java?rev=1535874&r1=1535873&r2=1535874&view=diff
==============================================================================
--- myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlLinkRendererBase.java (original)
+++ myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlLinkRendererBase.java Fri Oct 25 21:24:09 2013
@@ -84,7 +84,8 @@ public abstract class HtmlLinkRendererBa
{
String clientId = component.getClientId(facesContext);
FormInfo formInfo = findNestingForm(component, facesContext);
- if (formInfo != null)
+ boolean disabled = HtmlRendererUtils.isDisabled(component);
+ if (formInfo != null && !disabled)
{
String reqValue = (String) facesContext.getExternalContext().getRequestParameterMap().get(
HtmlRendererUtils.getHiddenCommandLinkFieldName(formInfo, facesContext));
@@ -97,7 +98,7 @@ public abstract class HtmlLinkRendererBa
}
}
if (component instanceof ClientBehaviorHolder &&
- !HtmlRendererUtils.isDisabled(component))
+ !disabled)
{
HtmlRendererUtils.decodeClientBehaviors(facesContext, component);
}
Modified: myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlMessageRendererBase.java
URL: http://svn.apache.org/viewvc/myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlMessageRendererBase.java?rev=1535874&r1=1535873&r2=1535874&view=diff
==============================================================================
--- myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlMessageRendererBase.java (original)
+++ myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlMessageRendererBase.java Fri Oct 25 21:24:09 2013
@@ -212,9 +212,23 @@ public abstract class HtmlMessageRendere
String title = getTitle(message);
boolean tooltip = isTooltip(message);
+ boolean showSummary = isShowSummary(message) && (summary != null);
+ boolean showDetail = isShowDetail(message) && (detail != null);
+
if (title == null && tooltip)
{
- title = summary;
+ if (showDetail)
+ {
+ title = detail;
+ }
+ else if (detail != null)
+ {
+ title = detail;
+ }
+ else
+ {
+ title = summary;
+ }
}
ResponseWriter writer = facesContext.getResponseWriter();
@@ -291,12 +305,14 @@ public abstract class HtmlMessageRendere
writer, message, HTML.SPAN_ELEM, HTML.STYLE_ATTR, style, span);
span |= HtmlRendererUtils.renderHTMLAttributeWithOptionalStartElement(
writer, message, HTML.SPAN_ELEM, HTML.STYLE_CLASS_ATTR, styleClass, span);
+ // Remember if renderStyleAndStyleClass is true, it means style and styleClass
+ // are rendered on the outer tag, and in that sense, role attribute should
+ // be rendered there too.
+ span |= HtmlRendererUtils.renderHTMLAttributeWithOptionalStartElement(
+ writer, message, HTML.ROLE_ATTR, HTML.ROLE_ATTR,
+ message.getAttributes().get(HTML.ROLE_ATTR), span);
}
-
- boolean showSummary = isShowSummary(message) && (summary != null);
- boolean showDetail = isShowDetail(message) && (detail != null);
-
if (showSummary && !(title == null && tooltip))
{
writer.writeText(summary, null);
Modified: myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlRendererUtils.java
URL: http://svn.apache.org/viewvc/myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlRendererUtils.java?rev=1535874&r1=1535873&r2=1535874&view=diff
==============================================================================
--- myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlRendererUtils.java (original)
+++ myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlRendererUtils.java Fri Oct 25 21:24:09 2013
@@ -34,11 +34,6 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.FacesException;
-import javax.faces.application.ConfigurableNavigationHandler;
-import javax.faces.application.NavigationCase;
-import javax.faces.application.NavigationHandler;
-import javax.faces.application.ProjectStage;
-import javax.faces.application.ViewHandler;
import javax.faces.component.EditableValueHolder;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
@@ -64,7 +59,6 @@ import javax.faces.convert.Converter;
import javax.faces.model.SelectItem;
import javax.faces.model.SelectItemGroup;
-import org.apache.myfaces.shared.application.NavigationUtils;
import org.apache.myfaces.shared.component.DisplayValueOnlyCapable;
import org.apache.myfaces.shared.component.EscapeCapable;
import org.apache.myfaces.shared.config.MyfacesConfig;
@@ -74,6 +68,7 @@ import org.apache.myfaces.shared.renderk
import org.apache.myfaces.shared.renderkit.html.util.FormInfo;
import org.apache.myfaces.shared.renderkit.html.util.HTMLEncoder;
import org.apache.myfaces.shared.renderkit.html.util.JavascriptUtils;
+import org.apache.myfaces.shared.renderkit.html.util.OutcomeTargetUtils;
/**
* @author Manfred Geiler (latest modification by $Author$)
@@ -1635,101 +1630,7 @@ public final class HtmlRendererUtils
public static String getOutcomeTargetHref(FacesContext facesContext,
UIOutcomeTarget component) throws IOException
{
- String outcome = component.getOutcome();
- outcome = (outcome == null) ? facesContext.getViewRoot().getViewId()
- : outcome;
- outcome = ((outcome == null) ? STR_EMPTY : outcome.trim());
- // Get the correct URL for the outcome.
- NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
- if (!(nh instanceof ConfigurableNavigationHandler))
- {
- throw new FacesException(
- "Navigation handler must be an instance of "
- + "ConfigurableNavigationHandler for using h:link or h:button");
- }
- ConfigurableNavigationHandler navigationHandler = (ConfigurableNavigationHandler) nh;
- // fromAction is null because there is no action method that was called to get the outcome
- NavigationCase navigationCase = navigationHandler.getNavigationCase(
- facesContext, null, outcome);
- // when navigation case is null, force the link or button to be disabled and log a warning
- if (navigationCase == null)
- {
- // log a warning
- log.warning("Could not determine NavigationCase for UIOutcomeTarget component "
- + RendererUtils.getPathToComponent(component));
-
- return null;
- }
- Map<String, List<String>> parameters = null;
- // handle URL parameters
- if (component.getChildCount() > 0)
- {
- List<UIParameter> validParams = getValidUIParameterChildren(
- facesContext, component.getChildren(), true, false);
- if (validParams.size() > 0)
- {
- parameters = new HashMap<String, List<String>>();
- }
- for (int i = 0, size = validParams.size(); i < size; i++)
- {
- UIParameter param = validParams.get(i);
- String name = param.getName();
- Object value = param.getValue();
- if (parameters.containsKey(name))
- {
- parameters.get(name).add(value.toString());
- }
- else
- {
- List<String> list = new ArrayList<String>(1);
- list.add(value.toString());
- parameters.put(name, list);
- }
- }
- }
- // handle NavigationCase parameters
- Map<String, List<String>> navigationCaseParams =
- NavigationUtils.getEvaluatedNavigationParameters(facesContext,
- navigationCase.getParameters());
- if (navigationCaseParams != null)
- {
- if (parameters == null)
- {
- parameters = new HashMap<String, List<String>>();
- }
- //parameters.putAll(navigationCaseParams);
- for (Map.Entry<String, List<String>> entry : navigationCaseParams
- .entrySet())
- {
- if (!parameters.containsKey(entry.getKey()))
- {
- parameters.put(entry.getKey(), entry.getValue());
- }
- }
- }
- if (parameters == null)
- {
- parameters = Collections.emptyMap();
- }
- // In theory the precedence order to deal with params is this:
- // component parameters, navigation-case parameters, view parameters
- // getBookmarkableURL deal with this details.
- ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
- String href = viewHandler.getBookmarkableURL(facesContext,
- navigationCase.getToViewId(facesContext),
- parameters, navigationCase.isIncludeViewParams() || component.isIncludeViewParams());
- // handle fragment (viewId#fragment)
- String fragment = (String) component.getAttributes().get("fragment");
- if (fragment != null)
- {
- fragment = fragment.trim();
-
- if (fragment.length() > 0)
- {
- href += "#" + fragment;
- }
- }
- return href;
+ return OutcomeTargetUtils.getOutcomeTargetHref(facesContext, component);
}
private static final String HTML_CONTENT_TYPE = "text/html";
@@ -2296,55 +2197,8 @@ public final class HtmlRendererUtils
FacesContext facesContext, List<UIComponent> children,
boolean skipNullValue, boolean skipUnrendered, boolean skipNullName)
{
- List<UIParameter> params = null;
- for (int i = 0, size = children.size(); i < size; i++)
- {
- UIComponent child = children.get(i);
- if (child instanceof UIParameter)
- {
- UIParameter param = (UIParameter) child;
- // check for the disable attribute (since 2.0)
- // and the render attribute (only if skipUnrendered is true)
- if (param.isDisable() || (skipUnrendered && !param.isRendered()))
- {
- // ignore this UIParameter and continue
- continue;
- }
- // check the name
- String name = param.getName();
- if (skipNullName && (name == null || STR_EMPTY.equals(name)))
- {
- // warn for a null-name
- log.log(Level.WARNING, "The UIParameter " + RendererUtils.getPathToComponent(param)
- + " has a name of null or empty string and thus will not be added to the URL.");
- // and skip it
- continue;
- }
- // check the value
- if (skipNullValue && param.getValue() == null)
- {
- if (facesContext.isProjectStage(ProjectStage.Development))
- {
- // inform the user about the null value when in Development stage
- log.log(Level.INFO, "The UIParameter " + RendererUtils.getPathToComponent(param)
- + " has a value of null and thus will not be added to the URL.");
- }
- // skip a null-value
- continue;
- }
- // add the param
- if (params == null)
- {
- params = new ArrayList<UIParameter>();
- }
- params.add(param);
- }
- }
- if (params == null)
- {
- params = Collections.emptyList();
- }
- return params;
+ return OutcomeTargetUtils.getValidUIParameterChildren(
+ facesContext, children, skipNullValue, skipUnrendered, skipNullName);
}
/**
Modified: myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlResponseWriterImpl.java
URL: http://svn.apache.org/viewvc/myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlResponseWriterImpl.java?rev=1535874&r1=1535873&r2=1535874&view=diff
==============================================================================
--- myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlResponseWriterImpl.java (original)
+++ myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlResponseWriterImpl.java Fri Oct 25 21:24:09 2013
@@ -21,6 +21,8 @@ package org.apache.myfaces.shared.render
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -103,6 +105,9 @@ public class HtmlResponseWriterImpl
private FacesContext _facesContext;
private boolean _cdataOpen;
+
+ private List<String> _startedChangedElements;
+ private List<Integer> _startedElementsCount;
private static final String CDATA_START = "<![CDATA[ \n";
private static final String CDATA_START_NO_LINE_RETURN = "<![CDATA[";
@@ -253,6 +258,8 @@ public class HtmlResponseWriterImpl
}
}
_isUTF8 = UTF8.equals(_characterEncoding);
+ _startedChangedElements = new ArrayList<String>();
+ _startedElementsCount = new ArrayList<Integer>();
}
public static boolean supportsContentType(String contentType)
@@ -336,6 +343,12 @@ public class HtmlResponseWriterImpl
}
String elementName = value.toString().trim();
+ if (!name.equals(elementName))
+ {
+ _startElementName = elementName;
+ _startedChangedElements.add(elementName);
+ _startedElementsCount.add(0);
+ }
_currentWriter.write((String) elementName);
}
else
@@ -347,18 +360,24 @@ public class HtmlResponseWriterImpl
{
_currentWriter.write(name);
}
+
+ if (!_startedElementsCount.isEmpty())
+ {
+ int i = _startedElementsCount.size()-1;
+ _startedElementsCount.set(i, _startedElementsCount.get(i)+1);
+ }
// Each time we start a element, it is necessary to check <script> or <style>,
// because we need to buffer all content to post process it later when it reach its end
// according to the initialization properties used.
- if(isScript(name))
+ if(isScript(_startElementName))
{
// handle a <script> start
_isInsideScript = Boolean.TRUE;
_isStyle = Boolean.FALSE;
_isTextArea = Boolean.FALSE;
}
- else if (isStyle(name))
+ else if (isStyle(_startElementName))
{
_isInsideScript = Boolean.FALSE;
_isStyle = Boolean.TRUE;
@@ -406,9 +425,25 @@ public class HtmlResponseWriterImpl
{
value = ((ValueExpression)value).getValue(getFacesContext().getELContext());
}
- encodeAndWriteURIAttribute(key, value, key);
+ // encodeAndWriteURIAttribute(key, value, key);
+ // JSF 2.2 In the renderkit javadoc of jsf 2.2 spec says this
+ // (Rendering Pass Through Attributes):
+ // "... The ResponseWriter must ensure that any pass through attributes are
+ // rendered on the outer-most markup element for the component. If there is
+ // a pass through attribute with the same name as a renderer specific
+ // attribute, the pass through attribute takes precedence. Pass through
+ // attributes are rendered as if they were passed to
+ // ResponseWriter.writeURIAttribute(). ..."
+ // Note here it says "as if they were passed", instead say "... attributes are
+ // encoded and rendered as if ...". Black box testing against RI shows that there
+ // is no URI encoding at all in this part, so in this case the best is do the
+ // same here. After all, it is resposibility of the one who set the passthrough
+ // attribute to do the proper encoding in cases when a URI is provided. However,
+ // that does not means the attribute should not be encoded as other attributes.
+ encodeAndWriteAttribute(key, value, key);
}
}
+
if (!_useStraightXml && isEmptyElement(_startElementName))
{
_currentWriter.write(" />");
@@ -419,7 +454,6 @@ public class HtmlResponseWriterImpl
else
{
_currentWriter.write('>');
-
/*
if(isScript(_startElementName))
{
@@ -493,12 +527,26 @@ public class HtmlResponseWriterImpl
throw new NullPointerException("elementName name must not be null");
}
+ String elementName = name;
+
+ if (!_startedElementsCount.isEmpty())
+ {
+ int i = _startedElementsCount.size()-1;
+ _startedElementsCount.set(i, _startedElementsCount.get(i)-1);
+ if (_startedElementsCount.get(i) == 0)
+ {
+ elementName = _startedChangedElements.get(i);
+ _startedChangedElements.remove(i);
+ _startedElementsCount.remove(i);
+ }
+ }
+
if (log.isLoggable(Level.WARNING))
{
if (_startElementName != null &&
- !name.equals(_startElementName))
+ !elementName.equals(_startElementName))
{
- log.warning("HTML nesting warning on closing " + name + ": element " + _startElementName +
+ log.warning("HTML nesting warning on closing " + elementName + ": element " + _startElementName +
(_startElementUIComponent==null?"":(" rendered by component : "+
RendererUtils.getPathToComponent(_startElementUIComponent)))+" not explicitly closed");
}
@@ -513,7 +561,7 @@ public class HtmlResponseWriterImpl
//tag was no empty tag - it has no accompanying end tag now.
if(_startElementName!=null)
- {
+ {
if (isScript() && (_isXhtmlContentType || _wrapScriptContentWithXmlCommentTag))
{
writeScriptContent();
@@ -526,12 +574,12 @@ public class HtmlResponseWriterImpl
}
//write closing tag
- writeEndTag(name);
+ writeEndTag(elementName);
}
}
else
{
- if (!_useStraightXml && isEmptyElement(name))
+ if (!_useStraightXml && isEmptyElement(elementName))
{
/*
Should this be here? It warns even when you have an x:htmlTag value="br", it should just close.
@@ -553,7 +601,7 @@ public class HtmlResponseWriterImpl
writeStyleContent();
_currentWriter = _outputWriter;
}
- writeEndTag(name);
+ writeEndTag(elementName);
}
}
@@ -803,6 +851,17 @@ public class HtmlResponseWriterImpl
_currentWriter.write('"');
}
}
+
+ private void encodeAndWriteAttribute(String name, Object value, String componentPropertyName) throws IOException
+ {
+ String strValue = (value==null)?"":value.toString();
+ _currentWriter.write(' ');
+ _currentWriter.write(name);
+ _currentWriter.write("=\"");
+ org.apache.myfaces.shared.renderkit.html.util.HTMLEncoder.encode(_currentWriter,
+ strValue, false, false, !_isUTF8);
+ _currentWriter.write('"');
+ }
public void writeURIAttribute(String name, Object value, String componentPropertyName) throws IOException
{
@@ -1086,7 +1145,7 @@ public class HtmlResponseWriterImpl
closeStartTagIfNecessary();
// empty string commonly used to force the start tag to be closed.
// in such case, do not call down the writer chain
- if (str.length() > 0)
+ if (str != null && str.length() > 0)
{
// Don't bother encoding anything if chosen character encoding is UTF-8
if (_isUTF8)
@@ -1150,4 +1209,14 @@ public class HtmlResponseWriterImpl
}
return _facesContext;
}
+
+ protected boolean getWrapScriptContentWithXmlCommentTag()
+ {
+ return _wrapScriptContentWithXmlCommentTag;
+ }
+
+ protected void forceFlush() throws IOException
+ {
+ _currentWriter.flush();
+ }
}
Modified: myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlTableRendererBase.java
URL: http://svn.apache.org/viewvc/myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlTableRendererBase.java?rev=1535874&r1=1535873&r2=1535874&view=diff
==============================================================================
--- myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlTableRendererBase.java (original)
+++ myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/HtmlTableRendererBase.java Fri Oct 25 21:24:09 2013
@@ -483,6 +483,7 @@ public class HtmlTableRendererBase exten
}
List children = null;
+ int columnStyleIndex = 0;
for (int j = 0, size = getChildCount(component); j < size; j++)
{
if (children == null)
@@ -496,16 +497,18 @@ public class HtmlTableRendererBase exten
if (columnRendering)
{
- beforeColumn(facesContext, uiData, j);
+ beforeColumn(facesContext, uiData, columnStyleIndex);
}
encodeColumnChild(facesContext, writer, uiData, child,
- styles, nc * uiData.getChildCount() + j);
+ styles, nc * uiData.getChildCount() + columnStyleIndex);
if (columnRendering)
{
- afterColumn(facesContext, uiData, j);
+ afterColumn(facesContext, uiData, columnStyleIndex);
}
+ columnStyleIndex = columnStyleIndex +
+ getColumnCountForComponent(facesContext, uiData, child);
}
}
@@ -582,6 +585,7 @@ public class HtmlTableRendererBase exten
renderRowStart(facesContext, writer, uiData, styles, currentRow);
List<UIComponent> children = null;
+ int columnStyleIndex = 0;
for (int j = 0, size = getChildCount(component); j < size; j++)
{
if (children == null)
@@ -595,16 +599,18 @@ public class HtmlTableRendererBase exten
if (columnRendering)
{
- beforeColumn(facesContext, uiData, j);
+ beforeColumn(facesContext, uiData, columnStyleIndex);
}
encodeColumnChild(facesContext, writer, uiData, child,
- styles, j);
+ styles, columnStyleIndex);
if (columnRendering)
{
- afterColumn(facesContext, uiData, j);
+ afterColumn(facesContext, uiData, columnStyleIndex);
}
+ columnStyleIndex = columnStyleIndex +
+ getColumnCountForComponent(facesContext, uiData, child);
}
}
@@ -821,6 +827,22 @@ public class HtmlTableRendererBase exten
{
}
/**
+ * Indicates the number of columns the component represents. By default each UIColumn instance
+ * is 1 column
+ * @param facesContext
+ * @param uiData
+ * @param child
+ * @return
+ */
+ protected int getColumnCountForComponent(FacesContext facesContext, UIData uiData, UIComponent child)
+ {
+ if (child instanceof UIColumn)
+ {
+ return 1;
+ }
+ return 0;
+ }
+ /**
*Perform any operations necessary immediately before each column child's header or footer is rendered
*
* @param facesContext the <code>FacesContext</code>.