Author: nbelaevski
Date: 2010-09-08 15:14:49 -0400 (Wed, 08 Sep 2010)
New Revision: 19137
Added:
trunk/core/api/src/test/java/org/richfaces/renderkit/
trunk/core/api/src/test/java/org/richfaces/renderkit/util/
trunk/core/api/src/test/java/org/richfaces/renderkit/util/IdSplitBuilderTest.java
Removed:
trunk/core/impl/src/main/java/org/richfaces/renderkit/util/AjaxRendererUtils.java
trunk/core/impl/src/main/java/org/richfaces/renderkit/util/IdSplitBuilder.java
trunk/core/impl/src/main/java/org/richfaces/renderkit/util/RendererUtils.java
trunk/core/impl/src/test/java/org/richfaces/renderkit/util/
Modified:
trunk/core/api/src/main/java/org/ajax4jsf/javascript/JSEncoder.java
trunk/core/api/src/test/java/org/ajax4jsf/javascript/ScriptUtilsTest.java
Log:
RF-7560 - synchronized unmerged files
Modified: trunk/core/api/src/main/java/org/ajax4jsf/javascript/JSEncoder.java
===================================================================
--- trunk/core/api/src/main/java/org/ajax4jsf/javascript/JSEncoder.java 2010-09-08
17:07:06 UTC (rev 19136)
+++ trunk/core/api/src/main/java/org/ajax4jsf/javascript/JSEncoder.java 2010-09-08
19:14:49 UTC (rev 19137)
@@ -31,13 +31,14 @@
// private char APOSTROPHE[] = { '\\', '\'' };
private static final char[] ENCODE_HEX = "0123456789ABCDEF".toCharArray();
- private static final char[] ENCODE_APOS = "\\'".toCharArray();
private static final char[] ENCODE_QUOT = "\\\"".toCharArray();
private static final char[] ENCODE_LF = "\\n".toCharArray();
+ private static final char[] ENCODE_BC = "\\b".toCharArray();
private static final char[] ENCODE_FF = "\\f".toCharArray();
private static final char[] ENCODE_CR = "\\r".toCharArray();
private static final char[] ENCODE_TAB = "\\t".toCharArray();
private static final char[] ENCODE_BS = "\\\\".toCharArray();
+ private static final char[] ENCODE_FS = "\\/".toCharArray();
// private static final char ENCODE_ESC[] = "\\e".toCharArray();
@@ -47,32 +48,34 @@
public JSEncoder() {}
/**
- * Return true or false wether this encoding can encode the specified
+ * Return true or false whether this encoding/format can encode the specified
* character or not.
* <p>
* This method will return true for the following character range: <br />
* <code>
- * <nobr>#x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]</nobr>
+ * <nobr>\b | \f | \t | \r | \n | " | \ | / | [#x20-#xD7FF] |
[#xE000-#xFFFD]</nobr>
* </code>
* </p>
*
* @see <a
href="http://www.w3.org/TR/REC-xml#charsets">W3C XML 1.0
</a>
+ * @see <a
href="http://json.org/">JSON.org</a>
*/
public boolean compile(char c) {
- if ((c == 0x09) || // [\t]
- (c == 0x0a) || // [\n]
- (c == 0x0d) || // [\r](c == 0x22) || // ["]
- (c == 0x22) || // ["]
- (c == 0x27) || // [']
- (c == 0x5c) || // [\]
- (c == 0x03) || // [esc]
- (c == ']') || // ] - to avoid conflicts
in CDATA
- (c == '<') || // - escape HTML markup
characters
- (c == '>') || // - HTML
- (c == '&') || // - HTML
- (c == '-') || // - HTML comments
- (c < 0x20) || // See
<
http://www.w3.org/TR/REC-xml#charsets>
- ((c > 0xd7ff) && (c < 0xe000)) ||
(c > 0xfffd) || (c > 0xff)) {
+ if ((c == '\b') ||
+ (c == '\f') |
+ (c == '\t') ||
+ (c == '\n') ||
+ (c == '\r') ||
+ (c == '"') ||
+ (c == '\\') ||
+ (c == '/') ||
+ (c == ']') || // ] - to avoid
conflicts in CDATA
+ (c == '<') || // - escape HTML
markup characters
+ (c == '>') || // - HTML
+ (c == '&') || // - HTML
+ (c == '-') || // - HTML comments
+ (c < 0x20) || // See
<
http://www.w3.org/TR/REC-xml#charsets>
+ ((c > 0xd7ff) && (c < 0xe000))
|| (c > 0xfffd) || (c > 0xff)) {
return false;
}
@@ -85,39 +88,36 @@
*/
public char[] encode(char c) {
switch (c) {
- case 0x03 :
- return ENCODE_FF; // (>) [>]
+ case '\b' :
+ return ENCODE_BC;
+
+ case '\f' :
+ return ENCODE_FF;
- case 0x09 :
- return ENCODE_TAB; // (>) [>]
+ case '\t' :
+ return ENCODE_TAB;
- case 0x0a :
- return ENCODE_LF; // (>) [>]
+ case '\n' :
+ return ENCODE_LF;
- case 0x0d :
- return ENCODE_CR; // (>) [>]
+ case '\r' :
+ return ENCODE_CR;
- case 0x22 :
- return ENCODE_QUOT; // (") ["]
+ case '"' :
+ return ENCODE_QUOT;
- case 0x27 :
- return ENCODE_APOS; // (') [']
+ case '\\' :
+ return ENCODE_BS;
- case 0x5c :
- return ENCODE_BS; // (<) [<]
-
+ case '/' :
+ return ENCODE_FS;
+
default : {
- if (c > 0xff) {
- char[] ret = {
- '\\', 'u', ENCODE_HEX[c >> 0xc & 0xf],
ENCODE_HEX[c >> 0x8 & 0xf], ENCODE_HEX[c >> 0x4 & 0xf],
- ENCODE_HEX[c & 0xf]
- };
+ char[] ret = {
+ '\\', 'u', ENCODE_HEX[c >> 0xc & 0xf],
ENCODE_HEX[c >> 0x8 & 0xf], ENCODE_HEX[c >> 0x4 & 0xf],
+ ENCODE_HEX[c & 0xf]
+ };
- return ret;
- }
-
- char[] ret = {'\\', 'x', ENCODE_HEX[c >> 0x4 &
0xf], ENCODE_HEX[c & 0xf]};
-
return ret;
}
}
Modified: trunk/core/api/src/test/java/org/ajax4jsf/javascript/ScriptUtilsTest.java
===================================================================
--- trunk/core/api/src/test/java/org/ajax4jsf/javascript/ScriptUtilsTest.java 2010-09-08
17:07:06 UTC (rev 19136)
+++ trunk/core/api/src/test/java/org/ajax4jsf/javascript/ScriptUtilsTest.java 2010-09-08
19:14:49 UTC (rev 19137)
@@ -123,9 +123,9 @@
* Test method for {@link
org.ajax4jsf.javascript.ScriptUtils#toScript(java.lang.Object)}.
*/
public void testStringToScript() {
- Object obj = "foo";
+ Object obj = "f \b\r\t\f\n\"'\\/ oo";
- assertEquals("\"foo\"", ScriptUtils.toScript(obj));
+ assertEquals("\"f \\b\\r\\t\\f\\n\\\"'\\\\\\/ oo\"",
ScriptUtils.toScript(obj));
}
/**
@@ -260,8 +260,8 @@
public void testAddEncoded() {
StringBuilder buff = new StringBuilder();
- ScriptUtils.addEncoded(buff, "foo\"\'");
- assertEquals("foo\\\"\\\'", buff.toString());
+ ScriptUtils.addEncoded(buff, "foo");
+ assertEquals("foo", buff.toString());
}
/**
Copied: trunk/core/api/src/test/java/org/richfaces/renderkit/util/IdSplitBuilderTest.java
(from rev 19136,
trunk/core/impl/src/test/java/org/richfaces/renderkit/util/IdSplitBuilderTest.java)
===================================================================
--- trunk/core/api/src/test/java/org/richfaces/renderkit/util/IdSplitBuilderTest.java
(rev 0)
+++
trunk/core/api/src/test/java/org/richfaces/renderkit/util/IdSplitBuilderTest.java 2010-09-08
19:14:49 UTC (rev 19137)
@@ -0,0 +1,81 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat, Inc. and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site:
http://www.fsf.org.
+ */
+package org.richfaces.renderkit.util;
+
+import static org.junit.Assert.assertArrayEquals;
+
+import org.junit.Test;
+import org.richfaces.renderkit.util.IdSplitBuilder;
+
+
+/**
+ * @author Nick Belaevski
+ *
+ */
+public class IdSplitBuilderTest {
+
+ private static String[] asArray(String... strings) {
+ return strings;
+ }
+
+ @Test
+ public void testEmptyString() throws Exception {
+ assertArrayEquals(asArray(), IdSplitBuilder.split(""));
+ assertArrayEquals(asArray(), IdSplitBuilder.split(" \r\t\n "));
+ }
+
+ @Test
+ public void testOneStrings() throws Exception {
+ assertArrayEquals(asArray("test"),
IdSplitBuilder.split("test"));
+ assertArrayEquals(asArray("some:id"),
IdSplitBuilder.split("some:id"));
+ assertArrayEquals(asArray("table:[1]"),
IdSplitBuilder.split("table:[1]"));
+ assertArrayEquals(asArray("table:[1, 2]"),
IdSplitBuilder.split("table:[1, 2]"));
+ assertArrayEquals(asArray("table:[1, 2]:nestedTable:[*]"),
IdSplitBuilder.split("table:[1, 2]:nestedTable:[*]"));
+ assertArrayEquals(asArray("table:[1, 2]:[*]:group"),
IdSplitBuilder.split("table:[1, 2]:[*]:group"));
+ assertArrayEquals(asArray("table:[1 2]:nestedTable:[*]"),
IdSplitBuilder.split("table:[1 2]:nestedTable:[*]"));
+ assertArrayEquals(asArray("table:[1 2]:[*]:group"),
IdSplitBuilder.split("table:[1 2]:[*]:group"));
+ }
+
+ @Test
+ public void testTwoStrings() throws Exception {
+ assertArrayEquals(asArray("test", "abc"),
IdSplitBuilder.split("test abc"));
+ assertArrayEquals(asArray("some:id", "form:table"),
IdSplitBuilder.split("some:id form:table"));
+ assertArrayEquals(asArray("test", "abc"),
IdSplitBuilder.split("test, abc"));
+ assertArrayEquals(asArray("some:id", "form:table"),
IdSplitBuilder.split("some:id, form:table"));
+
+ assertArrayEquals(asArray("test:[1 2 3]:abc", "form:[2]"),
IdSplitBuilder.split("test:[1 2 3]:abc form:[2]"));
+ assertArrayEquals(asArray("[1 2]:some", "[3\t4]:id"),
IdSplitBuilder.split(" [1 2]:some [3\t4]:id "));
+ }
+
+ @Test
+ public void testSeveralStrings() throws Exception {
+ assertArrayEquals(asArray("test", "abc", "def",
"ghi"), IdSplitBuilder.split("test abc def ghi"));
+ assertArrayEquals(asArray("test:[1 2]abc", "def",
"ghi"), IdSplitBuilder.split("test:[1 2]abc def ghi"));
+ assertArrayEquals(asArray("[1 2]abc", "[3, 4]def",
"ghi[5 6 7]"),
+ IdSplitBuilder.split("[1 2]abc [3, 4]def ghi[5 6 7]"));
+
+ assertArrayEquals(
+ asArray("test:[1 2]:abc", "table", "form:table:[ *
]:child", "extTable:[ 0, 3 ]:child:[1 8]:@header"),
+ IdSplitBuilder.split(" test:[1 2]:abc, table," +
+ " form:table:[ * ]:child, extTable:[ 0, 3 ]:child:[1
8]:@header" ));
+ }
+}
Deleted:
trunk/core/impl/src/main/java/org/richfaces/renderkit/util/AjaxRendererUtils.java
===================================================================
---
trunk/core/impl/src/main/java/org/richfaces/renderkit/util/AjaxRendererUtils.java 2010-09-08
17:07:06 UTC (rev 19136)
+++
trunk/core/impl/src/main/java/org/richfaces/renderkit/util/AjaxRendererUtils.java 2010-09-08
19:14:49 UTC (rev 19137)
@@ -1,1147 +0,0 @@
-/**
- * License Agreement.
- *
- * Rich Faces - Natural Ajax for Java Server Faces (JSF)
- *
- * Copyright (C) 2007 Exadel, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License version 2.1 as published by the Free Software Foundation.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-package org.richfaces.renderkit.util;
-
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.LinkedHashSet;
-import java.util.Map;
-import java.util.Set;
-
-import javax.faces.component.NamingContainer;
-import javax.faces.component.UIComponent;
-import javax.faces.component.UIForm;
-import javax.faces.context.FacesContext;
-import javax.faces.context.PartialResponseWriter;
-
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.component.AjaxClientBehavior;
-import org.ajax4jsf.component.AjaxComponent;
-import org.ajax4jsf.context.AjaxContext;
-import org.ajax4jsf.javascript.JSFunction;
-import org.ajax4jsf.javascript.JSFunctionDefinition;
-import org.ajax4jsf.javascript.JSReference;
-import org.ajax4jsf.renderkit.AJAXDataSerializer;
-import org.ajax4jsf.renderkit.AjaxEventOptions;
-import org.richfaces.application.ServiceTracker;
-import org.richfaces.log.Logger;
-import org.richfaces.log.RichfacesLogger;
-import org.richfaces.renderkit.HandlersChain;
-import org.richfaces.renderkit.util.RendererUtils.HTML;
-
-/**
- * @author shura
- * <p/>
- * Some utilites for render AJAX components.
- */
-public final class AjaxRendererUtils {
-
- public static final String AJAX_ABORT_ATTR = "ignoreDupResponses";
- public static final String AJAX_AREAS_RENDERED =
"org.ajax4jsf.areas.rendered";
- public static final String AJAX_DELAY_ATTR = "requestDelay";
-
- /**
- * Name Javasript function for submit AJAX request
- */
- public static final String AJAX_FUNCTION_NAME = "RichFaces.ajax";
-
- /**
- * @since 3.3.0
- */
- public static final String AJAX_PROCESS_ATTRIBUTE = "process";
- public static final String AJAX_QUEUE_ATTR = "eventsQueue";
- public static final String AJAX_REGIONS_ATTRIBUTE = "reRender";
- public static final String AJAX_SINGLE_ATTR = "ajaxSingle";
- public static final String AJAX_SINGLE_PARAMETER_NAME = "ajaxSingle";
- public static final String ALL = "@all";
- public static final String FORM = "@form";
- public static final String THIS = "@this";
- public static final String REGION = "@region";
- public static final String NONE = "@none";
-
- public static final Set<String> GLOBAL_META_COMPONENTS;
-
- static {
- GLOBAL_META_COMPONENTS = new HashSet<String>(2);
-
- GLOBAL_META_COMPONENTS.add(ALL);
- GLOBAL_META_COMPONENTS.add(NONE);
- }
-
- /**
- * Attribute to keep
- */
- public static final String LIMITRENDER_ATTR_NAME = "limitRender";
-
- /**
- * Attribute for keep JavaScript function name for call before updating
- * DOM tree.
- */
- public static final String ONBEFOREDOMUPDATE_ATTR_NAME =
"onbeforedomupdate";
- public static final String ONBEGIN_ATTR_NAME = "onbegin";
-
- /**
- * Attribute for keep JavaScript function name for call after complete
- * request.
- */
- public static final String ONCOMPLETE_ATTR_NAME = "oncomplete";
-
- public static final String DATA_ATTR_NAME = "data";
-
- /**
- * Attribute for keep JavaScript function name for call after complete
- * request.
- */
- public static final String ONCOMPLETE_CONTENT_ID =
"org.ajax4jsf.oncomplete";
- public static final String SIMILARITY_GROUPING_ID_ATTR =
"similarityGroupingId";
-
- /**
- * Attribute for keep clientId of status component
- */
- public static final String STATUS_ATTR_NAME = "status";
- public static final String VALUE_ATTR = "value";
-
- public static final String EXTENSION_ID = "org.richfaces.extension";
- public static final String AJAX_COMPONENT_ID_PARAMETER =
"org.richfaces.ajax.component";
- public static final String BEHAVIOR_EVENT_PARAMETER =
"javax.faces.behavior.event";
-
- public static final String QUEUE_ID_ATTRIBUTE = "queueId";
-
- private static final String BEFOREDOMUPDATE_ELEMENT_NAME =
"beforedomupdate";
- private static final String COMPLETE_ELEMENT_NAME = "complete";
- private static final String DATA_ELEMENT_NAME = "data";
- private static final String COMPONENT_DATA_ELEMENT_NAME = "componentData";
-
- private static final RendererUtils RENDERER_UTILS = RendererUtils.getInstance();
- private static final Class<?> OBJECT_ARRAY_CLASS = new Object[0].getClass();
- private static final Logger LOG = RichfacesLogger.RENDERKIT.getLogger();
-
- /**
- * Static class - protect constructor
- */
- private AjaxRendererUtils() {
- }
-
- private static enum BehaviorEventOptionsData {
- begin {
- @Override
- public String getAttributeValue(AjaxClientBehavior behavior) {
- return behavior.getOnbegin();
- }
- },
- error {
- @Override
- public String getAttributeValue(AjaxClientBehavior behavior) {
- return behavior.getOnerror();
- }
- },
- queueId {
- @Override
- public String getAttributeValue(AjaxClientBehavior behavior) {
- return behavior.getQueueId();
- }
- },
- event {
- @Override
- public String getAttributeValue(AjaxClientBehavior behavior) {
- return behavior.getOnevent();
- }
- };
-
- public abstract String getAttributeValue(AjaxClientBehavior behavior);
- }
-
- /**
- * Build JavaScript onclick event for given component
- *
- * @param uiComponent -
- * component for build event
- * @param facesContext
- * @return <code>StringBuffer</code> with Javascript code
- */
- public static StringBuffer buildOnClick(UIComponent uiComponent, FacesContext
facesContext) {
- return buildOnClick(uiComponent, facesContext, false);
- }
-
- /**
- * Build JavaScript onclick event for given component
- *
- * @param uiComponent -
- * component for build event
- * @param facesContext
- * @param omitDefaultActionUrl - default action URL is not encoded if parameter is
true
- * @return <code>StringBuffer</code> with Javascript code
- */
- public static StringBuffer buildOnClick(UIComponent uiComponent, FacesContext
facesContext,
- boolean omitDefaultActionUrl) {
- return buildOnEvent(uiComponent, facesContext, HTML.ONCLICK_ATTRIBUTE,
omitDefaultActionUrl);
- }
-
- /**
- * Build JavaScript event for component
- *
- * @param uiComponent -
- * component for build event
- * @param facesContext
- * @param eventName -
- * name of event
- * @return <code>StringBuffer</code> with Javascript code
- */
- public static StringBuffer buildOnEvent(UIComponent uiComponent, FacesContext
facesContext, String eventName) {
- return buildOnEvent(uiComponent, facesContext, eventName, false);
- }
-
- /**
- * Build JavaScript event for component
- *
- * @param uiComponent -
- * component for build event
- * @param facesContext
- * @param eventName -
- * name of event
- * @param omitDefaultActionUrl - default action URL is not encoded if parameter is
true
- * @return <code>StringBuffer</code> with Javascript code
- */
- public static StringBuffer buildOnEvent(UIComponent uiComponent, FacesContext
facesContext, String eventName,
- boolean omitDefaultActionUrl) {
- StringBuffer onEvent = new StringBuffer();
-
-// if (null != eventName) {
-// String commandOnEvent = (String) uiComponent.getAttributes().get(
-// eventName);
-// if (commandOnEvent != null) {
-// onEvent.append(commandOnEvent);
-// onEvent.append(';');
-// }
-// }
-// JSFunction ajaxFunction = buildAjaxFunction(uiComponent, facesContext);
-// // Create formal parameter for non-input elements ???
-// // Link Control pseudo-object
-// // Options map. Possible options for function call :
-// // control - name of form control for submit.
-// // name - name for link control \
-// // value - value of control. - possible replace by parameters ?
-// // single true/false - submit all form or only one control.
-// // affected - array of element's ID for update on responce.
-// // oncomplete - function for call after complete request.
-// // status - id of request status component.
-// // parameters - map of parameters name/value for append on request.
-// // ..........
-// ajaxFunction.addParameter(buildEventOptions(facesContext, uiComponent,
omitDefaultActionUrl));
-//
-// // appendAjaxSubmitParameters(facesContext, uiComponent, onEvent);
-// ajaxFunction.appendScript(onEvent);
-// if (uiComponent instanceof AjaxSupport) {
-// AjaxSupport support = (AjaxSupport) uiComponent;
-// if (support.isDisableDefault()) {
-// onEvent.append("; return false;");
-// }
-// }
-// LOG.debug(Messages.getMessage(Messages.BUILD_ONCLICK_INFO, uiComponent
-// .getId(), onEvent.toString()));
- return onEvent;
- }
-
- public static AjaxEventOptions buildEventOptions(FacesContext facesContext,
UIComponent component) {
- return buildEventOptions(facesContext, component, null);
- }
-
- public static AjaxEventOptions buildEventOptions(FacesContext facesContext,
UIComponent component,
- AjaxClientBehavior ajaxBehavior) {
- AjaxEventOptions ajaxEventOptions = new AjaxEventOptions();
- Map<String, Object> parametersMap =
RENDERER_UTILS.createParametersMap(facesContext, component);
- String ajaxStatusName = getAjaxStatus(component);
-
- if (ajaxBehavior != null) {
- ajaxStatusName = (ajaxBehavior.getStatus() != null) ?
ajaxBehavior.getStatus() : ajaxStatusName;
- appenAjaxBehaviorOptions(ajaxBehavior, ajaxEventOptions);
- } else {
- appendComponentOptions(facesContext, component, ajaxEventOptions);
- }
-
- if ((ajaxStatusName != null) && (ajaxStatusName.length() != 0)) {
- ajaxEventOptions.set(STATUS_ATTR_NAME, ajaxStatusName);
- }
-
- if (!parametersMap.isEmpty()) {
- ajaxEventOptions.getParameters().putAll(parametersMap);
- }
-
- return ajaxEventOptions;
- }
-
- private static boolean isNotEmpty(String value) {
- return (value != null) && (value.length() != 0);
- }
-
- private static void appenAjaxBehaviorOptions(AjaxClientBehavior behavior,
AjaxEventOptions ajaxEventOptions) {
- for (BehaviorEventOptionsData optionsData : BehaviorEventOptionsData.values()) {
- String eventHandlerValue = optionsData.getAttributeValue(behavior);
-
- if (isNotEmpty(eventHandlerValue)) {
- ajaxEventOptions.set(optionsData.toString(), eventHandlerValue);
- }
- }
- }
-
- private static void appendComponentOptions(FacesContext facesContext, UIComponent
component,
- AjaxEventOptions ajaxEventOptions) {
- String behaviorName = "begin";
- HandlersChain handlersChain = new HandlersChain(facesContext, component);
- String inlineHandler = getAjaxOnBegin(component);
-
- handlersChain.addInlineHandlerAsValue(inlineHandler);
- handlersChain.addBehaviors(behaviorName);
-
- String handlerScript = handlersChain.toScript();
-
- if (isNotEmpty(handlerScript)) {
- ajaxEventOptions.set(behaviorName, handlerScript);
- }
-
- String queueId = getQueueId(component);
- if (isNotEmpty(queueId)) {
- ajaxEventOptions.set(QUEUE_ID_ATTRIBUTE, queueId);
- }
-
- ajaxEventOptions.set("incId", "1");
- }
-
-// public static AjaxEventOptions buildEventOptions(FacesContext facesContext,
-// UIComponent uiComponent, Map<String, Object> params) {
-//
-// return buildEventOptions(facesContext, uiComponent, params, false);
-// }
-
- /**
- * @param facesContext
- * @param uiComponent
- * @return
- */
-// public static Map<String, Object> buildEventOptions(FacesContext facesContext,
-// UIComponent uiComponent, Map<String, Object> params, boolean
omitDefaultActionUrl) {
-// String clientId = uiComponent.getClientId(facesContext);
-// Map<String, Object> componentAttributes = uiComponent.getAttributes();
-// Map<String, Object> options = new HashMap<String, Object>();
-//
-// UIComponent nestingContainer = (UIComponent) findAjaxContainer(
-// facesContext, uiComponent);
-// String containerClientId = nestingContainer.getClientId(facesContext);
-// if (containerClientId != null &&
!AjaxViewRoot.ROOT_ID.equals(containerClientId)) {
-// options.put("containerId", containerClientId);
-// }
-//
-// Map<String, Object> parameters = new HashMap<String, Object>();
-// UIComponent targetComponent = (uiComponent instanceof
AjaxSupport)?uiComponent.getParent():uiComponent;
-// // UIForm form = getNestingForm(uiComponent);
-// // "input" - if assigned to html input element.
-// boolean input = targetComponent instanceof EditableValueHolder;
-// // Action component - button etc.
-//// boolean action = targetComponent instanceof ActionSource;
-//
-// boolean ajaxSingle = Boolean.TRUE.equals(componentAttributes
-// .get(AJAX_SINGLE_ATTR));
-// // For input components in single mode or without form submit input
-// // control )
-// if (ajaxSingle ) {
-// parameters.put(AJAX_SINGLE_PARAMETER_NAME,
targetComponent.getClientId(facesContext));
-// // options.put("single", JSReference.TRUE);
-// if (input) {
-// options.put("control", JSReference.THIS);
-// }
-// }
-// // Control value for submit
-// String controlName;
-// Object controlValue;
-// // TODO - make compatible with JSF RI/MyFaces ? use submittedValue ( if
-// // any ) for UIInput, converted value for ValueHolder.
-// controlName = clientId;
-// controlValue = clientId;
-// parameters.put(controlName, controlValue);
-// AjaxContext ajaxContext = AjaxContext.getCurrentInstance(facesContext);
-//
-// String ajaxActionURL = ajaxContext.getAjaxActionURL(facesContext);
-// if (omitDefaultActionUrl) {
-// UIComponent form = getNestingForm(uiComponent);
-// if (form != null && !RENDERER_UTILS.isBooleanAttribute(form,
"ajaxSubmit")) {
-// if (RENDERER_UTILS.getActionUrl(facesContext).equals(ajaxActionURL)) {
-// ajaxActionURL = null;
-// }
-// }
-// }
-//
-// if (ajaxActionURL != null) {
-// // Setup action URL. For portlet environment, it will be different from
-// // page.
-// options.put("actionUrl", ajaxActionURL);
-// }
-//
-// // Add application-wide Ajax parameters
-// parameters.putAll(ajaxContext.getCommonAjaxParameters());
-// // add child parameters
-// appendParameters(facesContext, uiComponent, parameters);
-//
-// if (params != null) {
-// parameters.putAll(params);
-// }
-//
-// if (!parameters.isEmpty()) {
-// options.put("parameters", parameters);
-// }
-// // parameter to render only current list of areas.
-//// if (isAjaxLimitToList(uiComponent)) {
-//// Set<? extends Object> ajaxAreas = getAjaxAreas(uiComponent);
-//// Set<String> areasIds = new HashSet<String>();
-//// if (null != ajaxAreas) {
-//// for (Iterator<? extends Object> iter = ajaxAreas.iterator();
iter.hasNext();) {
-//// String id = (String) iter.next();
-//// UIComponent comp = RendererUtils.getInstance().
-//// findComponentFor(uiComponent, id);
-//// if (null != comp) {
-//// areasIds.add(comp.getClientId(facesContext));
-//// } else {
-//// areasIds.add(id);
-//// }
-//// }
-//// }
-//// options.put("affected", areasIds);
-//// }
-// String oncomplete = getAjaxOncomplete(uiComponent);
-// if (null != oncomplete) {
-// options.put(ONCOMPLETE_ATTR_NAME, buildAjaxOncomplete(oncomplete));
-// }
-//
-// String beforeupdate = getAjaxOnBeforeDomUpdate(uiComponent);
-// if (null != beforeupdate) {
-// options.put(ONBEFOREDOMUPDATE_ATTR_NAME,
buildAjaxOnBeforeDomUpdate(beforeupdate));
-// }
-//
-//
-// String status = getAjaxStatus(uiComponent);
-// if (null != status) {
-// options.put("status", status);
-// }
-// String queue = (String) componentAttributes.get(AJAX_QUEUE_ATTR);
-// String implicitQueue = null;
-//
-// Integer requestDelay = (Integer) componentAttributes
-// .get(AJAX_DELAY_ATTR);
-// if (null != requestDelay && requestDelay.intValue() > 0) {
-// options.put(AJAX_DELAY_ATTR, requestDelay);
-// if (null == queue) {
-// implicitQueue = clientId;
-// }
-// }
-// Boolean ignoreDupResponses = (Boolean) componentAttributes
-// .get(AJAX_ABORT_ATTR);
-// if (null != ignoreDupResponses && ignoreDupResponses.booleanValue()) {
-// options.put(AJAX_ABORT_ATTR, JSReference.TRUE);
-// if (null == queue) {
-// implicitQueue = clientId;
-// }
-// }
-//
-// if (null != queue) {
-// options.put(AJAX_QUEUE_ATTR, queue);
-// } else if (implicitQueue != null) {
-// options.put("implicitEventsQueue", clientId);
-// }
-//
-// ExternalContext externalContext = facesContext.getExternalContext();
-// String namespace = externalContext.encodeNamespace("");
-// if (namespace != null && namespace.length() != 0) {
-// options.put("namespace", namespace);
-// }
-//
-// String similarityGroupingId = (String)
componentAttributes.get(SIMILARITY_GROUPING_ID_ATTR);
-// if (similarityGroupingId == null || similarityGroupingId.length() == 0) {
-// similarityGroupingId = clientId;
-// } else {
-// similarityGroupingId =
externalContext.encodeNamespace(similarityGroupingId);
-// }
-//
-// options.put(SIMILARITY_GROUPING_ID_ATTR, similarityGroupingId);
-//
-// // request timeout.
-// Integer timeout = (Integer) componentAttributes.get("timeout");
-// if (null != timeout && timeout.intValue() > 0) {
-// options.put("timeout", timeout);
-// }
-// // Encoding for requests
-// String encoding = (String) componentAttributes.get("encoding");
-// if (null != encoding) {
-// options.put("encoding", encoding);
-// }
-// return options;
-// }
-// /**
-// * Create call to Ajax Submit function with first two parameters
-// *
-// * @param uiComponent
-// * @param facesContext
-// * @param functionName
-// * @return
-// */
-// public static JSFunction buildAjaxFunction(UIComponent uiComponent,
-// FacesContext facesContext) {
-// JSFunction ajaxFunction = buildAjaxFunction(uiComponent, facesContext,
-// AJAX_FUNCTION_NAME);
-// // client-side script must have reference to event-enabled object.
-// ajaxFunction.addParameter(new JSReference("event"));
-// return ajaxFunction;
-// }
-
- /**
- * Create call to Ajax Submit function with first two parameters
- *
- * @param facesContext
- * @param uiComponent
- * @param functionName
- * @return
- */
- public static JSFunction buildAjaxFunction(FacesContext facesContext, UIComponent
uiComponent,
- String functionName) {
- JSFunction ajaxFunction = new JSFunction(functionName);
-
- ajaxFunction.addParameter(uiComponent.getClientId(facesContext));
- ajaxFunction.addParameter(JSReference.EVENT);
-
- return ajaxFunction;
- }
-
- /**
- * Append common parameters ( array of affected areas, status area id, on
- * complete function ) to JavaScript event string.
- *
- * @param uiComponent
- * @param onClick -
- * buffer with JavaScript code eg... AJAX.Submit(form,this
- */
-
- // public static void appendAjaxSubmitParameters(FacesContext facesContext,
- // UIComponent uiComponent, StringBuffer onClick)
- // {
- // Set ajaxAreas = getAjaxAreas(uiComponent);
- // onClick.append(',');
- // // parameter to render only current list of areas.
- // if (isAjaxLimitToList(uiComponent) && ajaxAreas != null &&
- // ajaxAreas.size() > 0)
- // {
- // onClick.append('[');
- // Iterator areas = ajaxAreas.iterator();
- // boolean first = true;
- // while (areas.hasNext())
- // {
- // String element = (String) areas.next();
- // UIComponent component = uiComponent.findComponent(element);
- // if (null != component)
- // {
- // if (!first)
- // {
- // onClick.append(',');
- // }
- // else
- // {
- // first = false;
- // }
- // onClick.append('\'');
- // onClick.append(component.getClientId(facesContext));
- // onClick.append('\'');
- // }
- // }
- // onClick.append("]");
- // }
- // else
- // {
- // onClick.append("null");
- // }
- // // insert id of request status element.
- // onClick.append(',');
- // String status = getAjaxStatus(uiComponent);
- // if (null != status)
- // {
- // onClick.append('\'').append(status).append('\'');
- // }
- // else
- // {
- // onClick.append("null");
- // }
- // // insert function name for call after completed request
- // onClick.append(',');
- // String oncomplete = getAjaxOncomplete(uiComponent);
- // if (null != oncomplete)
- // {
- // onClick.append(oncomplete);
- // }
- // else
- // {
- // onClick.append("null");
- // }
- //
- // }
-
- /**
- * Get list of clientId's for given component
- *
- * @param uiComponent
- * @return List of areas Id's , updated by this component.
- */
- public static Set<String> getAjaxAreas(UIComponent uiComponent) {
- Object areas;
-
- if (uiComponent instanceof AjaxComponent) {
- areas = ((AjaxComponent) uiComponent).getReRender();
- } else {
- areas =
uiComponent.getAttributes().get(AjaxRendererUtils.AJAX_REGIONS_ATTRIBUTE);
- }
-
- return asSet(areas);
- }
-
- /**
- * Returns set of areas to be processed as a result of this component action
invocation
- *
- * @param component
- * @return set of IDs that should be processed as a
- * @since 3.3.0
- */
- public static Set<String> getAjaxAreasToProcess(UIComponent component) {
- Object areas;
-
- if (component instanceof AjaxComponent) {
- areas = ((AjaxComponent) component).getProcess();
- } else {
- areas =
component.getAttributes().get(AjaxRendererUtils.AJAX_PROCESS_ATTRIBUTE);
- }
-
- return asSet(areas);
- }
-
- /**
- * Split parameter string into array of strings.
- * @param valuesSet
- * @return
- */
- public static String[] asArray(String valuesSet) {
- return IdSplitBuilder.split(valuesSet);
- }
-
- /**
- * Convert parameter ( Collection, List, array, String, comma-separated
- * String, whitespace-separate String) to set of strings.
- *
- * @param valueToSet -
- * object for conversion to Set.
- * @return - set of strings.
- */
- @SuppressWarnings("unchecked")
- public static Set<String> asSet(Object valueToSet) {
- if (null != valueToSet) {
-
- // Simplest case - set.
- if (valueToSet instanceof Set) {
- return new LinkedHashSet<String>((Set<String>) valueToSet);
- } else if (valueToSet instanceof Collection) { // Other collections.
- return new LinkedHashSet<String>((Collection<String>)
valueToSet);
- } else if (OBJECT_ARRAY_CLASS.isAssignableFrom(valueToSet.getClass())) { //
Array
- return new LinkedHashSet<String>(Arrays.asList((String[])
valueToSet));
- } else if (valueToSet instanceof String) { // Tokenize string.
- String areasString = ((String) valueToSet).trim();
-
- if (areasString.contains(",") || areasString.contains("
")) {
- String[] values = asArray(areasString);
- Set<String> result = new
LinkedHashSet<String>(values.length);
- for (String value : values) {
- result.add(value);
- }
-
- return result;
- } else {
- Set<String> areasSet = new LinkedHashSet<String>(5);
-
- areasSet.add(areasString);
-
- return areasSet;
- }
- }
- }
-
- return null;
- }
-
- /**
- * Get status area Id for given component.
- *
- * @param component
- * @return clientId of status area, or <code>null</code>
- */
- public static String getAjaxStatus(UIComponent component) {
- String statusId;
-
- if (component instanceof AjaxComponent) {
- statusId = ((AjaxComponent) component).getStatus();
- } else {
- statusId = (String) component.getAttributes().get(STATUS_ATTR_NAME);
- }
-
- return statusId;
-
-// if (null != statusId) {
-// UIComponent status = RendererUtils.getInstance().
-// findComponentFor(component, statusId);
-//
-// if (null != status) {
-// statusId = status
-// .getClientId(FacesContext.getCurrentInstance());
-// } else {
-// LOG.warn(Messages.getMessage(
-// Messages.AJAX_STATUS_COMPONENT_NOT_FOWND_WARNING,
-// component.getId()));
-// }
-// }
-// return statusId;
- }
-
- public static String getQueueId(UIComponent component) {
- return (String) component.getAttributes().get(QUEUE_ID_ATTRIBUTE);
- }
-
- public static JSFunctionDefinition buildAjaxOncomplete(String body) {
- JSFunctionDefinition function = new JSFunctionDefinition("request",
"event", "data");
-
- function.addToBody(body);
-
- return function;
- }
-
- public static JSFunctionDefinition buildAjaxOnBeforeDomUpdate(String body) {
- JSFunctionDefinition function = new JSFunctionDefinition("request",
"event", "data");
-
- function.addToBody(body);
-
- return function;
- }
-
- /**
- * Get function name for call on completed ajax request.
- *
- * @param component for wich calculate function name
- * @return name of JavaScript function or <code>null</code>
- */
- //TODO nick - refactor - remove this method?
- public static String getAjaxOncomplete(UIComponent component) {
- if (component instanceof AjaxComponent) {
- return ((AjaxComponent) component).getOncomplete();
- }
-
- return (String) component.getAttributes().get(ONCOMPLETE_ATTR_NAME);
- }
-
- /**
- * Get function name for call before update DOM.
- *
- * @param component for wich calculate function name
- * @return name of JavaScript function or <code>null</code>
- */
- //TODO nick - refactor - remove this method?
- public static String getAjaxOnBeforeDomUpdate(UIComponent component) {
- if (component instanceof AjaxComponent) {
- return ((AjaxComponent) component).getOnbeforedomupdate();
- }
-
- return (String) component.getAttributes().get(ONBEFOREDOMUPDATE_ATTR_NAME);
- }
-
- //TODO nick - refactor - remove this method?
- public static String getAjaxOnBegin(UIComponent component) {
- if (component instanceof AjaxComponent) {
- return ((AjaxComponent) component).getOnbegin();
- }
-
- return (String) component.getAttributes().get(ONBEGIN_ATTR_NAME);
- }
-
- /**
- * @param component
- * @return
- * @since 4.0
- */
- public static Object getAjaxData(UIComponent component) {
- if (component instanceof AjaxComponent) {
- return ((AjaxComponent) component).getData();
- }
-
- return component.getAttributes().get(DATA_ATTR_NAME);
- }
-
- /**
- * Calculate, must be component render only given areas, or all sended from
- * server.
- *
- * @param component
- * @return <code>true</code> if client must render ONLY given areas.
- */
- public static boolean isAjaxLimitRender(UIComponent component) {
- boolean result = false;
-
- if (component instanceof AjaxComponent) {
- result = ((AjaxComponent) component).isLimitRender();
- } else {
- try {
- result = ((Boolean)
component.getAttributes().get(LIMITRENDER_ATTR_NAME)).booleanValue();
- } catch (NullPointerException e) {
-
- // NullPointer - ignore ...
- } catch (ClassCastException e1) {
-
- // not Boolean - false ...
- }
- }
-
- return result;
- }
-
- /**
- * Replacement for buggy in MyFaces <code>RendererUtils</code>
- *
- * @param component
- * @return
- */
- public static String getAbsoluteId(UIComponent component) {
- if (component == null) {
- throw new
NullPointerException(Messages.getMessage(Messages.COMPONENT_NULL_ERROR_2));
- }
-
- StringBuffer idBuf = new StringBuffer();
-
- idBuf.append(component.getId());
-
- UIComponent parent = component;
-
- while ((parent = parent.getParent()) != null) {
- if (parent instanceof NamingContainer) {
- idBuf.insert(0, NamingContainer.SEPARATOR_CHAR);
- idBuf.insert(0, parent.getId());
- }
- }
-
- idBuf.insert(0, NamingContainer.SEPARATOR_CHAR);
- LOG.debug(Messages.getMessage(Messages.CALCULATE_COMPONENT_ID_INFO,
component.getId(), idBuf.toString()));
-
- return idBuf.toString();
- }
-
- /**
- * Find nested form for given component
- *
- * @param component
- * @return nested <code>UIForm</code> component, or
<code>null</code>
- */
- public static UIComponent getNestingForm(UIComponent component) {
- UIComponent parent = component;
-
- // Search enclosed UIForm or ADF UIXForm component
- while ((parent != null) && !(parent instanceof UIForm)
- &&
!("org.apache.myfaces.trinidad.Form".equals(parent.getFamily()))
- && !("oracle.adf.Form".equals(parent.getFamily()))) {
- parent = parent.getParent();
- }
-
- return parent;
- }
-
- protected static String getAjaxActionUrl(FacesContext facesContext) {
- return
AjaxContext.getCurrentInstance(facesContext).getAjaxActionURL(facesContext);
- }
-
-// /**
-// * Encode rendered areas as special HTML tag ( span in current release )
-// *
-// * @param context
-// * @param component
-// * @throws IOException
-// */
-// public static void encodeAreas(FacesContext context, UIComponent component) throws
IOException {
-// AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
-// ExternalContext externalContext = context.getExternalContext();
-// Map<String, Object> requestMap = externalContext.getRequestMap();
-// Set<String> rendered = ajaxContext.getAjaxRenderedAreas();
-//
-// // write special area for list of rendered elements. Client-side
-// // Java
-// // Script
-// // read this structure for update areas of DOM tree.
-// ResponseWriter out = context.getResponseWriter();
-//
-// // Create <span> element to keep list rendered aread ( in title
-// // attribute )
-// // More right will create special namespace for such
-// // information,
-// // but I want to keep simple html ( xhtml ) document - on case
-// // I have troubles with microsoft XMLHTTP validations.
-// out.startElement(AjaxContainerRenderer.AJAX_RESULT_GROUP_TAG, component);
-// out.writeAttribute(HTML.NAME_ATTRIBUTE,
AjaxContainerRenderer.AJAX_UPDATE_HEADER, null);
-//
-// StringBuffer senderString = new StringBuffer();
-//
-// for (Iterator<String> it = rendered.iterator(); it.hasNext();) {
-// String id = it.next();
-//
-// senderString.append(id);
-//
-// if (it.hasNext()) {
-// senderString.append(',');
-// }
-// }
-//
-// out.writeAttribute(AjaxContainerRenderer.AJAX_RESULT_GROUP_ATTR, senderString,
null);
-// out.endElement(AjaxContainerRenderer.AJAX_RESULT_GROUP_TAG);
-//
-// // For sequences and client-saved states.
-// out.startElement(AjaxContainerRenderer.AJAX_VIEW_STATE_TAG, component);
-// out.writeAttribute(HTML.ID_ATTRIBUTE, AjaxContainerRenderer.AJAX_VIEW_STATE_ID,
null);
-// writeState(context);
-// out.endElement(AjaxContainerRenderer.AJAX_VIEW_STATE_TAG);
-//
-// // Write rendered flag to html <meta>
-// out.startElement(AjaxContainerRenderer.AJAX_RESULT_GROUP_TAG, component);
-// out.writeAttribute(HTML.ID_ATTRIBUTE, AjaxContainerRenderer.AJAX_FLAG_HEADER,
null);
-// out.writeAttribute(HTML.NAME_ATTRIBUTE, AjaxContainerRenderer.AJAX_FLAG_HEADER,
null);
-// out.writeAttribute(AjaxContainerRenderer.AJAX_RESULT_GROUP_ATTR,
"true", null);
-// out.endElement(AjaxContainerRenderer.AJAX_RESULT_GROUP_TAG);
-//
-// // set response header with list of rendered ID's
-// Object response = externalContext.getResponse();
-//
-// // Use reflection for send responce headers - we can get
-// // different responces classes
-// // for different environment ( portal, cocoon etc )
-// if (response instanceof HttpServletResponse) {
-// HttpServletResponse httpResponse = (HttpServletResponse) response;
-//
-// httpResponse.setHeader(AjaxContainerRenderer.AJAX_FLAG_HEADER,
"true");
-// } else {
-// try {
-// Method setHeadergMethod =
response.getClass().getMethod("setHeader",
-// new Class[]{String.class, String.class});
-//
-// setHeadergMethod.invoke(response,
AjaxContainerRenderer.AJAX_FLAG_HEADER, "true");
-// } catch (Exception e) {
-//
LOG.error(Messages.getMessage(Messages.DETECTING_ENCODING_DISABLED_ERROR));
-//
LOG.error(Messages.getMessage(Messages.OBTAIN_RESPONSE_SET_HEADER_ERROR, e));
-// }
-// }
-//
-// Map<String, Object> responseDataMap =
ajaxContext.getResponseComponentDataMap();
-//
-// // Get data serializer instance
-// AJAXDataSerializer serializer = ServiceTracker.getService(context,
AJAXDataSerializer.class);
-//
-// // Put data to JavaScript handlers, inside <span> elements.
-// for (Map.Entry<String, Object> entry : responseDataMap.entrySet()) {
-// out.startElement(HTML.SPAN_ELEM, component);
-// out.writeAttribute(HTML.ID_ATTRIBUTE, entry.getKey(), null);
-//
-// String dataString = serializer.asString(entry.getValue());
-//
-// out.write(dataString);
-// out.endElement(HTML.SPAN_ELEM);
-// }
-//
-// // Include active 'oncomplete' function content :
-// Object oncomplete = ajaxContext.getOncomplete();
-//
-// if (null != oncomplete) {
-// out.startElement(HTML.SPAN_ELEM, component);
-// out.writeAttribute(HTML.ID_ATTRIBUTE, ONCOMPLETE_CONTENT_ID, null);
-// out.writeText(oncomplete, null);
-// out.endElement(HTML.SPAN_ELEM);
-// }
-//
-// // For self-rendered case, we use own methods for replace stateKey by
-// // real value in XML filter.
-// // if(ajaxContext.isSelfRender()){
-// // saveViewState(context, out);
-// // }
-// requestMap.put(AJAX_AREAS_RENDERED, "true");
-// }
-
- /**
- * Write state saving markers to context, include MyFaces view sequence.
- *
- * @param context
- * @throws IOException
- */
- public static void writeState(FacesContext context) throws IOException {
- context.getApplication().getViewHandler().writeState(context);
- }
-
-// /**
-// * Encode declaration for AJAX response. Render
<html><body>
-// *
-// * @param context
-// * @param component
-// * @throws IOException
-// */
-// public static void encodeAjaxBegin(FacesContext context, UIComponent component)
throws IOException {
-//
-// // AjaxContainer ajax = (AjaxContainer) component;
-// ResponseWriter out = context.getResponseWriter();
-//
-// // DebugUtils.traceView("ViewRoot in AJAX Page encode begin");
-// out.startElement("html", component);
-//
-// Locale locale = context.getViewRoot().getLocale();
-//
-// out.writeAttribute(HTML.LANG_ATTRIBUTE, locale.toString(), "lang");
-// out.startElement("body", component);
-// }
-//
-// /**
-// * End encoding of AJAX response. Render tag with included areas and close
-// * </body></html>
-// *
-// * @param context
-// * @param component
-// * @throws IOException
-// */
-// public static void encodeAjaxEnd(FacesContext context, UIComponent component)
throws IOException {
-//
-// // AjaxContainer ajax = (AjaxContainer) component;
-// ResponseWriter out = context.getResponseWriter();
-//
-// // DebugUtils.traceView("ViewRoot in AJAX Page encode begin");
-// encodeAreas(context, component);
-// out.endElement("body");
-// out.endElement("html");
-// }
-
- /**
- * @param facesContext
- * @return
- */
- public static boolean isAjaxRequest(FacesContext facesContext) {
- return AjaxContext.getCurrentInstance(facesContext).isAjaxRequest();
- }
-
- /**
- * TODO: add deprecation
- *
- * @param facesContext
- * @param component
- * @param id
- */
- public static void addRegionByName(FacesContext facesContext, UIComponent component,
String id) {
- AjaxContext.getCurrentInstance(facesContext).addComponentToAjaxRender(component,
id);
- }
-
- /**
- * @param facesContext
- * @param component
- */
- public static void addRegionsFromComponent(UIComponent component, FacesContext
facesContext) {
- AjaxContext.getCurrentInstance(facesContext).addRegionsFromComponent(component);
- }
-
- private static void startExtensionElementIfNecessary(
- PartialResponseWriter partialResponseWriter,
- Map<String, String> attributes,
- boolean[] writingState) throws IOException {
-
- if (!writingState[0]) {
- writingState[0] = true;
-
- partialResponseWriter.startExtension(attributes);
- }
- }
-
- private static void endExtensionElementIfNecessary(
- PartialResponseWriter partialResponseWriter,
- boolean[] writingState) throws IOException {
-
- if (writingState[0]) {
- writingState[0] = false;
-
- partialResponseWriter.endExtension();
- }
- }
-
- public static void renderAjaxExtensions(FacesContext facesContext, UIComponent
component) throws IOException {
- AjaxContext ajaxContext = AjaxContext.getCurrentInstance(facesContext);
-
- Map<String, String> attributes =
Collections.singletonMap(HTML.ID_ATTRIBUTE,
- facesContext.getExternalContext().encodeNamespace(EXTENSION_ID));
- PartialResponseWriter writer =
facesContext.getPartialViewContext().getPartialResponseWriter();
- boolean[] writingState = new boolean[]{false};
-
- Object onbeforedomupdate = ajaxContext.getOnbeforedomupdate();
- if (onbeforedomupdate != null) {
- String string = onbeforedomupdate.toString();
- if (string.length() != 0) {
- startExtensionElementIfNecessary(writer, attributes, writingState);
- writer.startElement(BEFOREDOMUPDATE_ELEMENT_NAME, component);
- writer.writeText(onbeforedomupdate, null);
- writer.endElement(BEFOREDOMUPDATE_ELEMENT_NAME);
- }
- }
-
- Object oncomplete = ajaxContext.getOncomplete();
- if (oncomplete != null) {
- String string = oncomplete.toString();
- if (string.length() != 0) {
- startExtensionElementIfNecessary(writer, attributes, writingState);
- writer.startElement(COMPLETE_ELEMENT_NAME, component);
- writer.writeText(oncomplete, null);
- writer.endElement(COMPLETE_ELEMENT_NAME);
- }
- }
-
- Object responseData = ajaxContext.getResponseData();
- if (responseData != null) {
- startExtensionElementIfNecessary(writer, attributes, writingState);
- writer.startElement(DATA_ELEMENT_NAME, component);
-
- AJAXDataSerializer serializer = ServiceTracker.getService(facesContext,
AJAXDataSerializer.class);
- writer.writeText(serializer.asString(responseData), null);
-
- writer.endElement(DATA_ELEMENT_NAME);
- }
-
- Map<String, Object> responseComponentDataMap =
ajaxContext.getResponseComponentDataMap();
- if (responseComponentDataMap != null &&
!responseComponentDataMap.isEmpty()) {
- startExtensionElementIfNecessary(writer, attributes, writingState);
- writer.startElement(COMPONENT_DATA_ELEMENT_NAME, component);
-
- AJAXDataSerializer serializer = ServiceTracker.getService(facesContext,
AJAXDataSerializer.class);
- writer.writeText(serializer.asString(responseComponentDataMap), null);
-
- writer.endElement(COMPONENT_DATA_ELEMENT_NAME);
- }
-
- endExtensionElementIfNecessary(writer, writingState);
-
- }
-
-}
Deleted: trunk/core/impl/src/main/java/org/richfaces/renderkit/util/IdSplitBuilder.java
===================================================================
---
trunk/core/impl/src/main/java/org/richfaces/renderkit/util/IdSplitBuilder.java 2010-09-08
17:07:06 UTC (rev 19136)
+++
trunk/core/impl/src/main/java/org/richfaces/renderkit/util/IdSplitBuilder.java 2010-09-08
19:14:49 UTC (rev 19137)
@@ -1,150 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2010, Red Hat, Inc. and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site:
http://www.fsf.org.
- */
-package org.richfaces.renderkit.util;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * @author Nick Belaevski
- */
-final class IdSplitBuilder {
-
- private static final int INITIAL_SPLIT_LIST_SIZE = 3;
-
- private enum State {
- IN_ID (true) {
-
- @Override
- public State getNextState(char c) {
- if (c == '[') {
- return State.IN_ID_INSIDE_BRACKETS;
- } else if (isSeparator(c)) {
- return State.OUTSIDE_ID;
- } else {
- return this;
- }
- }
- },
- IN_ID_INSIDE_BRACKETS (true) {
-
- @Override
- public State getNextState(char c) {
- if (c == ']') {
- return State.IN_ID;
- } else {
- return this;
- }
- }
- },
- OUTSIDE_ID (false) {
-
- @Override
- public State getNextState(char c) {
- if (!isSeparator(c)) {
- if (c == '[') {
- return State.IN_ID_INSIDE_BRACKETS;
- } else {
- return State.IN_ID;
- }
- }
-
- return this;
- }
- };
-
- private final boolean idSegment;
-
- private State(boolean idSegment) {
- this.idSegment = idSegment;
- }
-
- private static boolean isSeparator(char c) {
- return c == ',' || Character.isWhitespace(c);
- }
-
- public abstract State getNextState(char c);
-
- public boolean isIdSegment() {
- return idSegment;
- }
-
- public void processChar(IdSplitBuilder builder, char c, int charIdx) {
- State nextState = getNextState(c);
-
- if (nextState.isIdSegment() ^ isIdSegment()) {
- if (nextState.isIdSegment()) {
- builder.setStartIndex(charIdx);
- } else {
- builder.flushBuilder(charIdx);
- builder.setStartIndex(-1);
- }
- }
-
- builder.state = nextState;
- }
- }
-
- private int startIdx = -1;
-
- private String sourceString;
-
- private List<String> result = new
ArrayList<String>(INITIAL_SPLIT_LIST_SIZE);
-
- private State state = State.OUTSIDE_ID;
-
- private IdSplitBuilder(String sourceString) {
- super();
- this.sourceString = sourceString;
- }
-
- private void setStartIndex(int idx) {
- startIdx = idx;
- }
-
- private void flushBuilder(int endIdx) {
- if (startIdx >= 0 && endIdx > startIdx) {
- String id = sourceString.substring(startIdx, endIdx);
- result.add(id);
- }
- }
-
- private void build() {
- int length = sourceString.length();
- for (int i = 0; i < length; i++) {
- char c = sourceString.charAt(i);
- state.processChar(this, c, i);
- }
- flushBuilder(length);
- }
-
- private String[] getSplit() {
- return result.toArray(new String[result.size()]);
- }
-
- public static String[] split(String s) {
- IdSplitBuilder splitBuilder = new IdSplitBuilder(s);
- splitBuilder.build();
- return splitBuilder.getSplit();
- }
-
-}
\ No newline at end of file
Deleted: trunk/core/impl/src/main/java/org/richfaces/renderkit/util/RendererUtils.java
===================================================================
---
trunk/core/impl/src/main/java/org/richfaces/renderkit/util/RendererUtils.java 2010-09-08
17:07:06 UTC (rev 19136)
+++
trunk/core/impl/src/main/java/org/richfaces/renderkit/util/RendererUtils.java 2010-09-08
19:14:49 UTC (rev 19137)
@@ -1,1314 +0,0 @@
-/**
- * License Agreement.
- *
- * Rich Faces - Natural Ajax for Java Server Faces (JSF)
- *
- * Copyright (C) 2007 Exadel, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License version 2.1 as published by the Free Software Foundation.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-
-
-package org.richfaces.renderkit.util;
-
-import java.io.IOException;
-import java.lang.reflect.Array;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.Map;
-import java.util.Set;
-
-import javax.faces.FacesException;
-import javax.faces.application.ViewHandler;
-import javax.faces.component.EditableValueHolder;
-import javax.faces.component.NamingContainer;
-import javax.faces.component.UIComponent;
-import javax.faces.component.UIForm;
-import javax.faces.component.UIParameter;
-import javax.faces.component.UIViewRoot;
-import javax.faces.component.ValueHolder;
-import javax.faces.component.behavior.ClientBehaviorContext.Parameter;
-import javax.faces.component.behavior.ClientBehaviorHolder;
-import javax.faces.context.FacesContext;
-import javax.faces.context.ResponseWriter;
-import javax.faces.convert.Converter;
-
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.component.JavaScriptParameter;
-import org.ajax4jsf.javascript.JSEncoder;
-import org.ajax4jsf.javascript.JSFunctionDefinition;
-import org.ajax4jsf.javascript.JSReference;
-import org.ajax4jsf.util.HtmlDimensions;
-import org.richfaces.context.ComponentIdResolver;
-import org.richfaces.renderkit.HandlersChain;
-
-/**
- * Util class for common render operations - render passthru html attributes,
- * iterate over child components etc.
- *
- * @author asmirnov(a)exadel.com (latest modification by $Author: alexsmirnov $)
- * @version $Revision: 1.1.2.6 $ $Date: 2007/02/08 19:07:16 $
- *
- */
-public class RendererUtils {
-
- public static final String DUMMY_FORM_ID = ":_form";
-
- // we'd better use this instance multithreadly quickly
- private static final RendererUtils INSTANCE = new RendererUtils();
-
- /**
- * Substitutions for components properies names and HTML attributes names.
- */
- private static final Map<String, String> SUBSTITUTIONS = new HashMap<String,
String>();
-
- private static final Set<String> REQUIRED_ATTRIBUTES = new
HashSet<String>();
-
- static {
- SUBSTITUTIONS.put(HTML.CLASS_ATTRIBUTE, "styleClass");
-
- REQUIRED_ATTRIBUTES.add(HTML.ALT_ATTRIBUTE);
-
- Arrays.sort(HTML.PASS_THRU);
- Arrays.sort(HTML.PASS_THRU_EVENTS);
- Arrays.sort(HTML.PASS_THRU_BOOLEAN);
- Arrays.sort(HTML.PASS_THRU_URI);
- }
-
- // can be created by subclasses;
- // administratively restricted to be created by package members ;)
- protected RendererUtils() {
- super();
- }
-
- /**
- * Wrapper class around object value used to transform values into particular JS
objects
- *
- * @author Nick Belaevski
- * @since 3.3.2
- */
- public static enum ScriptHashVariableWrapper {
-
- /**
- * No-op default wrapper
- */
- DEFAULT {
- @Override
- Object wrap(Object o) {
- return o;
- }
- },
-
- /**
- * Event handler functions wrapper. Wraps <pre>functionCode</pre>
object into:
- * <pre>function(event) {
- * functionCode
- * }</pre>
- */
- EVENT_HANDLER {
- @Override
- Object wrap(Object o) {
- return new JSFunctionDefinition("event").addToBody(o);
- }
- };
-
- /**
- * Method that does the wrapping
- *
- * @param o object to wrap
- * @return wrapped object
- */
- abstract Object wrap(Object o);
- }
-
- /**
- * Use this method to get singleton instance of RendererUtils
- * @return singleton instance
- */
- public static RendererUtils getInstance() {
- return INSTANCE;
- }
-
- /**
- * Encode id attribute with clientId component property
- *
- * @param context
- * @param component
- * @throws IOException
- */
- public void encodeId(FacesContext context, UIComponent component) throws IOException
{
- encodeId(context, component, HTML.ID_ATTRIBUTE);
- }
-
- /**
- * Encode clientId to custom attribute ( for example, to control name )
- *
- * @param context
- * @param component
- * @param attribute
- * @throws IOException
- */
- public void encodeId(FacesContext context, UIComponent component, String attribute)
throws IOException {
- String clientId = null;
-
- try {
- clientId = component.getClientId(context);
- } catch (Exception e) {
-
- // just ignore if clientId wasn't inited yet
- }
-
- if (null != clientId) {
- context.getResponseWriter().writeAttribute(attribute, clientId,
- (String) getComponentAttributeName(attribute));
- }
- }
-
- /**
- * Encode id attribute with clientId component property. Encoded only if id
- * not auto generated.
- *
- * @param context
- * @param component
- * @throws IOException
- */
- public void encodeCustomId(FacesContext context, UIComponent component) throws
IOException {
- if (hasExplicitId(component)) {
- context.getResponseWriter().writeAttribute(HTML.ID_ATTRIBUTE,
component.getClientId(context),
- HTML.ID_ATTRIBUTE);
- }
- }
-
- public Map<String, Object> createParametersMap(FacesContext context,
UIComponent component) {
- Map<String, Object> parameters = new LinkedHashMap<String,
Object>();
-
- if (component.getChildCount() > 0) {
- for (UIComponent child : component.getChildren()) {
- if (child instanceof UIParameter) {
- UIParameter parameter = (UIParameter) child;
- String name = parameter.getName();
- Object value = parameter.getValue();
-
- if (null == name) {
- throw new
IllegalArgumentException(Messages.getMessage(Messages.UNNAMED_PARAMETER_ERROR,
- component.getClientId(context)));
- }
-
- boolean escape = true;
-
- if (child instanceof JavaScriptParameter) {
- JavaScriptParameter actionParam = (JavaScriptParameter) child;
-
- escape = !actionParam.isNoEscape();
- }
-
- if (escape) {
- if (value == null) {
- value = "";
- }
- } else {
- value = new JSReference(value.toString());
-
- // if(it.hasNext()){onEvent.append(',');};
- // renderAjaxLinkParameter( name,
- // value, onClick, jsForm, nestingForm);
- }
-
- parameters.put(name, value);
- }
- }
- }
-
- return parameters;
- }
-
- private void encodeBehaviors(FacesContext context, ClientBehaviorHolder
behaviorHolder,
- String defaultHtmlEventName, String[]
attributesExclusions)
- throws IOException {
-
-// if (attributesExclusions != null && attributesExclusions.length != 0) {
-// assert false : "Not supported yet";
-// }
- // TODO: disabled component check
- String defaultEventName = behaviorHolder.getDefaultEventName();
- Collection<String> eventNames = behaviorHolder.getEventNames();
-
- if (eventNames != null) {
- UIComponent component = (UIComponent) behaviorHolder;
- ResponseWriter writer = context.getResponseWriter();
- Collection<Parameter> parametersList =
HandlersChain.createParametersList(createParametersMap(context,
- component));
-
- for (String behaviorEventName : eventNames) {
- if (behaviorEventName.equals(defaultEventName)) {
- continue;
- }
-
- String htmlEventName = "on" + behaviorEventName;
-
- if ((attributesExclusions == null) ||
(Arrays.binarySearch(attributesExclusions, htmlEventName) < 0)) {
- HandlersChain handlersChain = new HandlersChain(context, component,
parametersList);
-
- handlersChain.addInlineHandlerFromAttribute(htmlEventName);
- handlersChain.addBehaviors(behaviorEventName);
-
- String handlerScript = handlersChain.toScript();
-
- if (!isEmpty(handlerScript)) {
- writer.writeAttribute(htmlEventName, handlerScript,
htmlEventName);
- }
- }
- }
- }
- }
-
- /**
- * Encode common pass-thru html attributes.
- *
- * @param context
- * @param component
- * @throws IOException
- */
- public void encodePassThru(FacesContext context, UIComponent component, String
defaultHtmlEvent)
- throws IOException {
-
- encodeAttributesFromArray(context, component, HTML.PASS_THRU);
-
- if (component instanceof ClientBehaviorHolder) {
- ClientBehaviorHolder clientBehaviorHolder = (ClientBehaviorHolder)
component;
-
- encodeBehaviors(context, clientBehaviorHolder, defaultHtmlEvent, null);
- } else {
- encodeAttributesFromArray(context, component, HTML.PASS_THRU_EVENTS);
- }
- }
-
- /**
- * Encode pass-through attributes except specified ones
- *
- * @param context
- * @param component
- * @param exclusions
- * @throws IOException
- */
- public void encodePassThruWithExclusions(FacesContext context, UIComponent component,
String exclusions,
- String defaultHtmlEvent) throws IOException {
-
- if (null != exclusions) {
- String[] exclusionsArray = exclusions.split(",");
-
- encodePassThruWithExclusionsArray(context, component, exclusionsArray,
defaultHtmlEvent);
- }
- }
-
- public void encodePassThruWithExclusionsArray(FacesContext context, UIComponent
component, String[] exclusions,
- String defaultHtmlEvent) throws IOException {
-
- ResponseWriter writer = context.getResponseWriter();
- Map<String, Object> attributes = component.getAttributes();
-
- Arrays.sort(exclusions);
-
- for (int i = 0; i < HTML.PASS_THRU.length; i++) {
- String attribute = HTML.PASS_THRU[i];
-
- if (Arrays.binarySearch(exclusions, attribute) < 0) {
- encodePassThruAttribute(context, attributes, writer, attribute);
- }
- }
-
- if (component instanceof ClientBehaviorHolder) {
- ClientBehaviorHolder clientBehaviorHolder = (ClientBehaviorHolder)
component;
-
- encodeBehaviors(context, clientBehaviorHolder, defaultHtmlEvent,
exclusions);
- } else {
- for (int i = 0; i < HTML.PASS_THRU_EVENTS.length; i++) {
- String attribute = HTML.PASS_THRU_EVENTS[i];
-
- if (Arrays.binarySearch(exclusions, attribute) < 0) {
- encodePassThruAttribute(context, attributes, writer, attribute);
- }
- }
- }
- }
-
- /**
- * Encode one pass-thru attribute, with plain/boolean/url value, got from
- * properly component attribute.
- *
- * @param context
- * @param writer
- * @param attribute
- * @throws IOException
- */
- public void encodePassThruAttribute(FacesContext context, Map<String, Object>
attributes, ResponseWriter writer,
- String attribute) throws IOException {
-
- Object value = attributeValue(attribute,
attributes.get(getComponentAttributeName(attribute)));
-
- if ((null != value) && shouldRenderAttribute(attribute, value)) {
- if (Arrays.binarySearch(HTML.PASS_THRU_URI, attribute) >= 0) {
- String url =
context.getApplication().getViewHandler().getResourceURL(context, value.toString());
-
- url = context.getExternalContext().encodeResourceURL(url);
- writer.writeURIAttribute(attribute, url, attribute);
- } else {
- writer.writeAttribute(attribute, value, attribute);
- }
- }
- }
-
- public void encodeAttributesFromArray(FacesContext context, UIComponent component,
String[] attrs)
- throws IOException {
-
- ResponseWriter writer = context.getResponseWriter();
- Map<String, Object> attributes = component.getAttributes();
-
- for (int i = 0; i < attrs.length; i++) {
- String attribute = attrs[i];
-
- encodePassThruAttribute(context, attributes, writer, attribute);
- }
- }
-
- /**
- * Encode attributes given by comma-separated string list.
- *
- * @param context
- * current JSF context
- * @param component
- * for with render attributes values
- * @param attrs
- * comma separated list of attributes
- * @throws IOException
- */
- public void encodeAttributes(FacesContext context, UIComponent component, String
attrs) throws IOException {
- if (null != attrs) {
- String[] attrsArray = attrs.split(",");
-
- encodeAttributesFromArray(context, component, attrsArray);
- }
- }
-
- /**
- * @param context
- * @param component
- * @param property
- * @param attributeName
- *
- * @throws IOException
- */
- public void encodeAttribute(FacesContext context, UIComponent component, Object
property, String attributeName)
- throws IOException {
-
- ResponseWriter writer = context.getResponseWriter();
- Object value = component.getAttributes().get(property);
-
- if (shouldRenderAttribute(attributeName, value)) {
- writer.writeAttribute(attributeName, value, property.toString());
- }
- }
-
- public void encodeAttribute(FacesContext context, UIComponent component, String
attribute) throws IOException {
- encodeAttribute(context, component, getComponentAttributeName(attribute),
attribute);
- }
-
- /**
- * Write html-attribute
- *
- * @param writer
- * @param attribute
- * @param value
- * @throws IOException
- */
- public void writeAttribute(ResponseWriter writer, String attribute, Object value)
throws IOException {
- if (shouldRenderAttribute(attribute, value)) {
- writer.writeAttribute(attribute, value.toString(), attribute);
- }
- }
-
- /**
- * @return true if and only if the argument <code>attributeVal</code> is
- * an instance of a wrapper for a primitive type and its value is
- * equal to the default value for that type as given in the spec.
- */
- public boolean shouldRenderAttribute(Object attributeVal) {
- if (null == attributeVal) {
- return false;
- } else if ((attributeVal instanceof Boolean)
- && ((Boolean) attributeVal).booleanValue() ==
Boolean.FALSE.booleanValue()) {
- return false;
- } else if (attributeVal.toString().length() == 0) {
- return false;
- } else {
- return isValidProperty(attributeVal);
- }
- }
-
- public boolean shouldRenderAttribute(String attributeName, Object attributeVal) {
- if (REQUIRED_ATTRIBUTES.contains(attributeName)) {
- if (attributeVal == null) {
- return false;
- }
- } else {
- return shouldRenderAttribute(attributeVal);
- }
-
- return true;
- }
-
- /**
- * Test for valid value of property. by default, for non-setted properties
- * with Java primitive types of JSF component return appropriate MIN_VALUE .
- *
- * @param property -
- * value of property returned from
- * {@link UIComponent#getAttributes()}
- * @return true for setted property, false otherthise.
- */
- public boolean isValidProperty(Object property) {
- if (null == property) {
- return false;
- } else if ((property instanceof Integer) && ((Integer)
property).intValue() == Integer.MIN_VALUE) {
- return false;
- } else if ((property instanceof Double) && ((Double)
property).doubleValue() == Double.MIN_VALUE) {
- return false;
- } else if ((property instanceof Character) && ((Character)
property).charValue() == Character.MIN_VALUE) {
- return false;
- } else if ((property instanceof Float) && ((Float) property).floatValue()
== Float.MIN_VALUE) {
- return false;
- } else if ((property instanceof Short) && ((Short) property).shortValue()
== Short.MIN_VALUE) {
- return false;
- } else if ((property instanceof Byte) && ((Byte) property).byteValue() ==
Byte.MIN_VALUE) {
- return false;
- } else if ((property instanceof Long) && ((Long) property).longValue() ==
Long.MIN_VALUE) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Checks if the argument passed in is empty or not.
- * Object is empty if it is: <br />
- * - <code>null</code><br />
- * - zero-length string<br />
- * - empty collection<br />
- * - empty map<br />
- * - zero-length array<br />
- *
- * @param o object to check for emptiness
- * @since 3.3.2
- * @return <code>true</code> if the argument is empty,
<code>false</code> otherwise
- */
- public boolean isEmpty(Object o) {
- if (null == o) {
- return true;
- }
-
- if (o instanceof String) {
- return 0 == ((String) o).length();
- }
-
- if (o instanceof Collection<?>) {
- return ((Collection<?>) o).isEmpty();
- }
-
- if (o instanceof Map<?, ?>) {
- return ((Map<?, ?>) o).isEmpty();
- }
-
- if (o.getClass().isArray()) {
- return Array.getLength(o) == 0;
- }
-
- return false;
- }
-
- /**
- * Puts value into map under specified key if the value is not empty and not
default.
- * Performs optional value wrapping.
- *
- * @param hash
- * @param name
- * @param value
- * @param defaultValue
- * @param wrapper
- *
- * @since 3.3.2
- */
- public void addToScriptHash(Map<String, Object> hash, String name, Object
value, String defaultValue,
- ScriptHashVariableWrapper wrapper) {
- ScriptHashVariableWrapper wrapperOrDefault = (wrapper != null) ? wrapper :
ScriptHashVariableWrapper.DEFAULT;
-
- if (isValidProperty(value) && !isEmpty(value)) {
- if (!isEmpty(defaultValue)) {
- if (!defaultValue.equals(value.toString())) {
- hash.put(name, wrapperOrDefault.wrap(value));
- }
- } else {
- if (!(value instanceof Boolean) || ((Boolean) value).booleanValue()) {
- hash.put(name, wrapperOrDefault.wrap(value));
- }
- }
- }
- }
-
- /**
- * Puts value into map under specified key if the value is not empty and not
default.
- * Performs optional value wrapping.
- *
- * @param hash
- * @param name
- * @param value
- * @param defaultValue
- *
- * @since 3.3.2
- */
- public void addToScriptHash(Map<String, Object> hash, String name, Object
value, String defaultValue) {
- addToScriptHash(hash, name, value, defaultValue, null);
- }
-
- /**
- * Puts value into map under specified key if the value is not empty and not
default.
- * Performs optional value wrapping.
- *
- * @param hash
- * @param name
- * @param value
- *
- * @since 3.3.2
- */
- public void addToScriptHash(Map<String, Object> hash, String name, Object
value) {
- addToScriptHash(hash, name, value, null, null);
- }
-
- /**
- * Convert HTML attribute name to component property name.
- *
- * @param key
- * @return
- */
- protected Object getComponentAttributeName(Object key) {
- Object converted = SUBSTITUTIONS.get(key);
-
- if (null == converted) {
- return key;
- } else {
- return converted;
- }
- }
-
- /**
- * Convert attribute value to proper object. For known html boolean
- * attributes return name for true value, otherthise - null. For non-boolean
- * attributes return same value.
- *
- * @param name
- * attribute name.
- * @param value
- * @return
- */
- protected Object attributeValue(String name, Object value) {
- if (null == value || Arrays.binarySearch(HTML.PASS_THRU_BOOLEAN, name) < 0) {
- return value;
- }
-
- boolean checked;
-
- if (value instanceof Boolean) {
- checked = ((Boolean) value).booleanValue();
- } else {
- checked = Boolean.parseBoolean(value.toString());
- }
-
- return checked ? name : null;
- }
-
- /**
- * Get boolean value of logical attribute
- *
- * @param component
- * @param name
- * attribute name
- * @return true if attribute is equals Boolean.TRUE or String "true" ,
false
- * otherwise.
- */
- public boolean isBooleanAttribute(UIComponent component, String name) {
- Object attrValue = component.getAttributes().get(name);
- boolean result = false;
-
- if (null != attrValue) {
- if (attrValue instanceof String) {
- result = "true".equalsIgnoreCase((String) attrValue);
- } else {
- result = Boolean.TRUE.equals(attrValue);
- }
- }
-
- return result;
- }
-
- /**
- * Return converted value for {@link javax.faces.component.ValueHolder} as
- * String, perform nessesary convertions.
- *
- * @param context
- * @param component
- * @return
- */
- public String getValueAsString(FacesContext context, UIComponent component) {
-
- // First - get submitted value for input components
- if (component instanceof EditableValueHolder) {
- EditableValueHolder input = (EditableValueHolder) component;
- String submittedValue = (String) input.getSubmittedValue();
-
- if (null != submittedValue) {
- return submittedValue;
- }
- }
-
- // If no submitted value presented - convert same for UIInput/UIOutput
- if (component instanceof ValueHolder) {
- return formatValue(context, component, ((ValueHolder)
component).getValue());
- } else {
- throw new IllegalArgumentException(
- Messages.getMessage(Messages.CONVERTING_NON_VALUE_HOLDER_COMPONENT_ERROR,
component.getId()));
- }
- }
-
- /**
- * Convert any object value to string. If component instance of
- * {@link ValueHolder } got {@link Converter} for formatting. If not,
- * attempt to use converter based on value type.
- *
- * @param context
- * @param component
- * @return
- */
- public String formatValue(FacesContext context, UIComponent component, Object value)
{
- if (value instanceof String) {
- return (String) value;
- }
-
- Converter converter = null;
-
- if (component instanceof ValueHolder) {
- ValueHolder holder = (ValueHolder) component;
-
- converter = holder.getConverter();
- }
-
- if ((null == converter) && (null != value)) {
- try {
- converter = context.getApplication().createConverter(value.getClass());
- } catch (FacesException e) {
-
- // TODO - log converter exception.
- }
- }
-
- if (null == converter) {
- if (null != value) {
- return value.toString();
- }
- } else {
- return converter.getAsString(context, component, value);
- }
-
- return "";
- }
-
- public String encodePx(String value) {
- return HtmlDimensions.formatPx(HtmlDimensions.decode(value));
- }
-
- /**
- * formats given value to
- *
- * @param value
- *
- * @return
- */
- public String encodePctOrPx(String value) {
- if (value.indexOf('%') > 0) {
- return value;
- } else {
- return encodePx(value);
- }
- }
-
- /**
- * Find nested form for given component
- *
- * @param component
- * @return nested <code>UIForm</code> component, or
<code>null</code>
- */
- public UIForm getNestingForm(FacesContext context, UIComponent component) {
- UIComponent parent = component.getParent();
-
- while ((parent != null) && !(parent instanceof UIForm)) {
- parent = parent.getParent();
- }
-
- UIForm nestingForm = null;
-
- if (parent != null) {
-
- // link is nested inside a form
- nestingForm = (UIForm) parent;
- }
-
- return nestingForm;
- }
-
- /**
- * @param context
- * @param component
- * @return
- * @throws IOException
- */
- public void encodeBeginFormIfNessesary(FacesContext context, UIComponent component)
throws IOException {
- UIForm form = getNestingForm(context, component);
-
- if (null == form) {
- ResponseWriter writer = context.getResponseWriter();
- String clientId = component.getClientId(context) + DUMMY_FORM_ID;
-
- encodeBeginForm(context, component, writer, clientId);
-
- // writer.writeAttribute(HTML.STYLE_ATTRIBUTE, "margin:0;
- // padding:0;", null);
- }
- }
-
- /**
- * @param context
- * @param component
- * @param writer
- * @param clientId
- * @throws IOException
- */
- public void encodeBeginForm(FacesContext context, UIComponent component,
ResponseWriter writer, String clientId)
- throws IOException {
-
- String actionURL = getActionUrl(context);
- String encodeActionURL =
context.getExternalContext().encodeActionURL(actionURL);
-
- writer.startElement(HTML.FORM_ELEMENT, component);
- writer.writeAttribute(HTML.ID_ATTRIBUTE, clientId, null);
- writer.writeAttribute(HTML.NAME_ATTRIBUTE, clientId, null);
- writer.writeAttribute(HTML.METHOD_ATTRIBUTE, "post", null);
- writer.writeAttribute(HTML.STYLE_ATTRIBUTE, "margin:0; padding:0; display:
inline;", null);
- writer.writeURIAttribute(HTML.ACTION_ATTRIBUTE, encodeActionURL,
"action");
- }
-
- /**
- * @param context
- * @param component
- * @throws IOException
- */
- public void encodeEndFormIfNessesary(FacesContext context, UIComponent component)
throws IOException {
- UIForm form = getNestingForm(context, component);
-
- if (null == form) {
- ResponseWriter writer = context.getResponseWriter();
-
- // TODO - hidden form parameters ?
- encodeEndForm(context, writer);
- }
- }
-
- /**
- * @param context
- * @param writer
- * @throws IOException
- */
- public void encodeEndForm(FacesContext context, ResponseWriter writer) throws
IOException {
- AjaxRendererUtils.writeState(context);
- writer.endElement(HTML.FORM_ELEMENT);
- }
-
- /**
- * @param facesContext
- * @return String A String representing the action URL
- */
- public String getActionUrl(FacesContext facesContext) {
- ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
- String viewId = facesContext.getViewRoot().getViewId();
-
- return viewHandler.getActionURL(facesContext, viewId);
- }
-
- /**
- * Simplified version of {@link encodeId}
- *
- * @param context
- * @param component
- * @return client id of current component
- */
- public String clientId(FacesContext context, UIComponent component) {
- String clientId = "";
-
- try {
- clientId = component.getClientId(context);
- } catch (Exception e) {
-
- // just ignore
- }
-
- return clientId;
- }
-
- /**
- * Wtrie JavaScript with start/end elements and type.
- *
- * @param context
- * @param component
- * @param script
- */
- public void writeScript(FacesContext context, UIComponent component, Object script)
throws IOException {
- ResponseWriter writer = context.getResponseWriter();
-
- writer.startElement(HTML.SCRIPT_ELEM, component);
- writer.writeAttribute(HTML.TYPE_ATTR, "text/javascript",
"type");
- writer.writeText(script, null);
- writer.endElement(HTML.SCRIPT_ELEM);
- }
-
- /**
- * @param ids
- * @param keyword
- * @return
- * @since 4.0
- */
- private static boolean checkKeyword(Collection<String> ids, String keyword) {
- if (ids.contains(keyword)) {
- if (ids.size() != 1) {
- //TODO log
- }
-
- return true;
- }
-
- return false;
- }
-
- public String getPredefinedMetaComponentId(FacesContext facesContext, UIComponent
component, String id) {
-
- if (AjaxRendererUtils.ALL.equals(id)) {
- return AjaxRendererUtils.ALL;
- } else if (AjaxRendererUtils.NONE.equals(id)) {
- return AjaxRendererUtils.NONE;
- } else if (AjaxRendererUtils.THIS.equals(id)) {
- return component.getClientId(facesContext);
- } else if (AjaxRendererUtils.FORM.equals(id)) {
- UIForm nestingForm = getNestingForm(facesContext, component);
- if (nestingForm != null) {
- return nestingForm.getClientId(facesContext);
- } else {
- //TODO nick - log warning for missing form
- }
- }
-
- return null;
- }
-
- /**
- * @param context
- * @param component
- * @param shortIds
- * @since 4.0
- * @return
- */
- public Collection<String> findComponentsFor(FacesContext context, UIComponent
component,
- Collection<String> shortIds) {
-
- // TODO - implement
- // TODO add support for @*
- Set<String> result = new LinkedHashSet<String>(shortIds.size());
-
- if (checkKeyword(shortIds, AjaxRendererUtils.ALL)) {
- result.add(AjaxRendererUtils.ALL);
- } else if (checkKeyword(shortIds, AjaxRendererUtils.NONE)) {
- //do nothing, use empty set
- } else {
- ComponentIdResolver locator = new ComponentIdResolver(context);
-
- for (String id : shortIds) {
- String predefinedMetaComponentId = getPredefinedMetaComponentId(context,
component, id);
- if (predefinedMetaComponentId != null) {
- if
(AjaxRendererUtils.GLOBAL_META_COMPONENTS.contains(predefinedMetaComponentId)) {
- result.clear();
- result.add(predefinedMetaComponentId);
- break;
- } else {
- result.add(predefinedMetaComponentId);
- continue;
- }
- }
-
- locator.addId(id);
- }
-
- locator.resolve(component);
-
- result.addAll(locator.getResolvedIds());
- }
-
- return result;
- }
-
- public UIComponent findComponentFor(FacesContext context, UIComponent component,
String id) {
- return findComponentFor(component, id);
- }
-
- /**
- * @param component
- * @param id
- * @return
- */
- public UIComponent findComponentFor(UIComponent component, String id) {
- if (id == null) {
- throw new NullPointerException("id is null!");
- }
-
- if (id.length() == 0) {
- return null;
- }
-
- UIComponent target = null;
- UIComponent parent = component;
- UIComponent root = component;
-
- while ((null == target) && (null != parent)) {
- target = parent.findComponent(id);
- root = parent;
- parent = parent.getParent();
- }
-
- if (null == target) {
- target = findUIComponentBelow(root, id);
- }
-
- return target;
- }
-
- /**
- * If target component contains generated id and for doesn't, correct for id
- * @param forAttr
- * @param component
- *
- */
- public String correctForIdReference(String forAttr, UIComponent component) {
- int contains = forAttr.indexOf(UIViewRoot.UNIQUE_ID_PREFIX);
-
- if (contains <= 0) {
- String id = component.getId();
- int pos = id.indexOf(UIViewRoot.UNIQUE_ID_PREFIX);
-
- if (pos > 0) {
- return forAttr.concat(id.substring(pos));
- }
- }
-
- return forAttr;
- }
-
- private UIComponent findUIComponentBelow(UIComponent root, String id) {
- UIComponent target = null;
-
- for (Iterator<UIComponent> iter = root.getFacetsAndChildren();
iter.hasNext();) {
- UIComponent child = (UIComponent) iter.next();
-
- if (child instanceof NamingContainer) {
- try {
- target = child.findComponent(id);
- } catch (IllegalArgumentException iae) {
- continue;
- }
- }
-
- if (target == null) {
- if ((child.getChildCount() > 0) || (child.getFacetCount() > 0)) {
- target = findUIComponentBelow(child, id);
- }
- }
-
- if (target != null) {
- break;
- }
- }
-
- return target;
- }
-
- public static void writeEventHandlerFunction(FacesContext context, UIComponent
component, String eventName)
- throws IOException {
-
- ResponseWriter writer = context.getResponseWriter();
- Object script = component.getAttributes().get(eventName);
-
- if ((script != null) && !script.equals("")) {
- JSFunctionDefinition onEventDefinition = new JSFunctionDefinition();
-
- onEventDefinition.addParameter("event");
- onEventDefinition.addToBody(script);
- writer.writeText(eventName + ": " + onEventDefinition.toScript(),
null);
- } else {
- writer.writeText(eventName + ": ''", null);
- }
- }
-
- public JSFunctionDefinition getAsEventHandler(FacesContext context, UIComponent
component, String attributeName,
- String append) {
- String event = (String) component.getAttributes().get(attributeName);
-
- if (event != null) {
- event = event.trim();
-
- if (event.length() != 0) {
- JSFunctionDefinition function = new JSFunctionDefinition();
-
- function.addParameter("event");
-
- if ((null != append) && (append.length() > 0)) {
- function.addToBody(event + append);
- } else {
- function.addToBody(event);
- }
-
- return function;
- }
- }
-
- return null;
- }
-
- public String escapeJavaScript(Object o) {
- if (o != null) {
- StringBuilder result = new StringBuilder();
- JSEncoder encoder = new JSEncoder();
- char[] chars = o.toString().toCharArray();
- int start = 0;
- int end = chars.length;
-
- for (int x = start; x < end; x++) {
- char c = chars[x];
-
- if (encoder.compile(c)) {
- continue;
- }
-
- if (start != x) {
- result.append(chars, start, x - start);
- }
-
- result.append(encoder.encode(c));
- start = x + 1;
-
- continue;
- }
-
- if (start != end) {
- result.append(chars, start, end - start);
- }
-
- return result.toString();
- } else {
- return null;
- }
- }
-
- public void encodeChildren(FacesContext context, UIComponent component) throws
IOException {
- if (component.getChildCount() > 0) {
- for (UIComponent child : component.getChildren()) {
- child.encodeAll(context);
- }
- }
- }
-
- public boolean hasExplicitId(UIComponent component) {
- return component.getId() != null &&
!component.getId().startsWith(UIViewRoot.UNIQUE_ID_PREFIX);
- }
-
- /**
- * Common HTML elements and attributes names.
- *
- * @author asmirnov(a)exadel.com (latest modification by $Author: alexsmirnov $)
- * @version $Revision: 1.1.2.6 $ $Date: 2007/02/08 19:07:16 $
- *
- */
- public interface HTML {
- // elements
- public static final String A_ELEMENT = "a";
- public static final String BODY_ELEMENT = "body";
- public static final String IMG_ELEMENT = "img";
- public static final String INPUT_ELEM = "input";
- public static final String INPUT_TYPE_HIDDEN = "hidden";
- public static final String BUTTON = "button";
- public static final String CAPTION_ELEMENT = "caption";
- public static final String CHARSET_ATTR = "charset";
- public static final String COORDS_ATTR = "coords";
- public static final String COLGROUP_ELEMENT = "colgroup";
- public static final String COL_ELEMENT = "col";
- public static final String DISABLED_ATTR = "disabled";
- public static final String DIV_ELEM = "div";
- public static final String DD_ELEMENT = "dd";
- public static final String DL_ELEMENT = "dl";
- public static final String DT_ELEMENT = "dt";
- public static final String FORM_ELEMENT = "form";
- public static final String HEAD_ELEMENT = "head";
- public static final String HEIGHT_ATTRIBUTE = "height";
- public static final String HREFLANG_ATTR = "hreflang";
- public static final String HREF_ATTR = "href";
- public static final String HTML_ELEMENT = "html";
- public static final String LINK_ELEMENT = "link";
- public static final String SCRIPT_ELEM = "script";
- public static final String SPAN_ELEM = "span";
- public static final String TFOOT_ELEMENT = "tfoot";
- public static final String THEAD_ELEMENT = "thead";
- public static final String TABLE_ELEMENT = "table";
- public static final String TBODY_ELEMENT = "tbody";
- public static final String TD_ELEM = "td";
- public static final String TR_ELEMENT = "tr";
- public static final String TH_ELEM = "th";
- public static final String TITLE_ELEM = "title";
- public static final String UL_ELEMENT = "ul";
- public static final String OL_ELEMENT = "ol";
- public static final String LI_ELEMENT = "li";
-
- // attributes
- public static final String FRAME_ATTRIBUTE = "frame";
- public static final String BORDER_ATTRIBUTE = "border";
- public static final String BGCOLOR_ATTRIBUTE = "bgcolor";
- public static final String ACCEPT_ATTRIBUTE = "accept";
- public static final String ACCEPT_CHARSET_ATTRIBUTE =
"accept-charset";
- public static final String ACCESSKEY_ATTRIBUTE = "accesskey";
- public static final String ACTION_ATTRIBUTE = "action";
- public static final String ALIGN_ATTRIBUTE = "align";
- public static final String ALT_ATTRIBUTE = "alt";
- public static final String AUTOCOMPLETE_ATTRIBUTE = "autocomplete";
- public static final String CLASS_ATTRIBUTE = "class";
- public static final String COLS_ATTRIBUTE = "cols";
- public static final String COLSPAN_ATTRIBUTE = "colspan";
- public static final String CELLPADDING_ATTRIBUTE = "cellpadding";
- public static final String CELLSPACING_ATTRIBUTE = "cellspacing";
- public static final String DIR_ATTRIBUTE = "dir";
- public static final String ENCTYPE_ATTRIBUTE = "enctype";
-
- public static final String ID_ATTRIBUTE = "id";
- public static final String LANG_ATTRIBUTE = "lang";
- public static final String LONGDESC_ATTRIBUTE = "longdesc";
- public static final String MAXLENGTH_ATTRIBUTE = "maxlength";
- public static final String MEDIA_ATTRIBUTE = "media";
- public static final String METHOD_ATTRIBUTE = "method";
- public static final String NAME_ATTRIBUTE = "name";
- public static final String NOWRAP_ATTRIBUTE = "nowrap";
- public static final String ROWS_ATTRIBUTE = "rows";
- public static final String RULES_ATTRIBUTE = "rules";
- public static final String ROWSPAN_ATTRIBUTE = "rowspan";
- public static final String READONLY_ATTRIBUTE = "readonly";
- public static final String SIZE_ATTRIBUTE = "size";
- public static final String SRC_ATTRIBUTE = "src";
- public static final String STYLE_ATTRIBUTE = "style";
- public static final String SUMMARY_ATTRIBUTE = "summary";
- public static final String SCOPE_ATTRIBUTE = "scope";
- public static final String TABINDEX_ATTRIBUTE = "tabindex";
- public static final String TITLE_ATTRIBUTE = "title";
- public static final String TARGET_ATTRIBUTE = "target";
- public static final String TYPE_ATTR = "type";
-
- public static final String USEMAP_ATTRIBUTE = "usemap";
-
- public static final String VALIGN_ATTRIBUTE = "valign";
- public static final String VALUE_ATTRIBUTE = "value";
- public static final String WIDTH_ATTRIBUTE = "width";
-
-
- public static final String ONBLUR_ATTRIBUTE = "onblur";
- public static final String ONCHANGE_ATTRIBUTE = "onchange";
- public static final String ONCLICK_ATTRIBUTE = "onclick";
- public static final String ONDBLCLICK_ATTRIBUTE = "ondblclick";
- public static final String ONFOCUS_ATTRIBUTE = "onfocus";
- public static final String ONKEYDOWN_ATTRIBUTE = "onkeydown";
- public static final String ONKEYPRESS_ATTRIBUTE = "onkeypress";
- public static final String ONKEYUP_ATTRIBUTE = "onkeyup";
- public static final String ONLOAD_ATTRIBUTE = "onload";
- public static final String ONMOUSEDOWN_ATTRIBUTE = "onmousedown";
- public static final String ONMOUSEMOVE_ATTRIBUTE = "onmousemove";
- public static final String ONMOUSEOUT_ATTRIBUTE = "onmouseout";
- public static final String ONMOUSEOVER_ATTRIBUTE = "onmouseover";
- public static final String ONMOUSEUP_ATTRIBUTE = "onmouseup";
- public static final String ONRESET_ATTRIBUTE = "onreset";
- public static final String ONSELECT_ATTRIBUTE = "onselect";
- public static final String ONSUBMIT_ATTRIBUTE = "onsubmit";
- public static final String ONUNLOAD_ATTRIBUTE = "onunload";
-
- public static final String REL_ATTR = "rel";
- public static final String REV_ATTR = "rev";
- public static final String SHAPE_ATTR = "shape";
- public static final String STYLE_CLASS_ATTR = "styleClass";
-
-
-
- // public static final String ONRESET_ATTRIBUTE = "onreset";
- // attributes sets.
- public static final String[] PASS_THRU = {
-
- // DIR_ATTRIBUTE,
- // LANG_ATTRIBUTE,
- // STYLE_ATTRIBUTE,
- // TITLE_ATTRIBUTE
- "accesskey", "alt", "cols", "height",
"lang", "longdesc", "maxlength", "rows",
"size", "tabindex", "title",
- "width", "dir", "rules", "frame",
"border", "cellspacing", "cellpadding", "summary",
"bgcolor", "usemap",
- "enctype", "accept-charset", "accept",
"target", "charset", "coords", "hreflang",
"rel", "rev", "shape",
- "disabled", "readonly", "ismap",
"align"
- };
-
- /**
- * HTML attributes allowed boolean-values only
- */
- public static final String[] PASS_THRU_BOOLEAN = {
- "disabled", "declare", "readonly",
"compact", "ismap", "selected", "checked",
"nowrap", "noresize",
- "nohref", "noshade", "multiple"
- };
- public static final String[] PASS_THRU_EVENTS = {
- "onblur", "onchange", "onclick",
"ondblclick", "onfocus", "onkeydown",
"onkeypress", "onkeyup", "onload",
- "onmousedown", "onmousemove", "onmouseout",
"onmouseover", "onmouseup", "onreset", "onselect",
"onsubmit",
- "onunload"
- };
- public static final String[] PASS_THRU_STYLES = {"style",
"class", };
-
- /**
- * all HTML attributes with URI value.
- */
- public static final String[] PASS_THRU_URI = {
- "usemap", "background", "codebase",
"cite", "data", "classid", "href",
"longdesc", "profile", "src"
- };
-
-
- public static final String TEXT_JAVASCRIPT_TYPE = "text/javascript";
- public static final String REL_STYLESHEET = "stylesheet";
- public static final String CSS_TYPE = "text/css";
- public static final String JAVASCRIPT_TYPE = "text/javascript";
- }
-}