Author: Alex.Kolonitsky
Date: 2009-11-01 12:10:42 -0500 (Sun, 01 Nov 2009)
New Revision: 15800
Removed:
root/framework/trunk/impl/src/main/java/org/richfaces/json/Test.java
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/component/EnclosingFormRequiredException.java
root/framework/trunk/impl/src/main/java/org/richfaces/component/FileUploadConstants.java
root/framework/trunk/impl/src/main/java/org/richfaces/component/RowKeyContextEventWrapper.java
root/framework/trunk/impl/src/main/java/org/richfaces/component/SavedState.java
root/framework/trunk/impl/src/main/java/org/richfaces/component/UIDataAdaptor.java
root/framework/trunk/impl/src/main/java/org/richfaces/component/UIRangedNumberInput.java
root/framework/trunk/impl/src/main/java/org/richfaces/component/UISequence.java
root/framework/trunk/impl/src/main/java/org/richfaces/component/UISwitchablePanel.java
root/framework/trunk/impl/src/main/java/org/richfaces/component/nsutils/NSUtils.java
root/framework/trunk/impl/src/main/java/org/richfaces/component/nsutils/package-info.java
root/framework/trunk/impl/src/main/java/org/richfaces/component/package-info.java
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/AbstractMessageUtil.java
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/ComponentMessageUtil.java
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/ComponentUtil.java
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/FormUtil.java
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/HtmlUtil.java
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/MessageUtil.java
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/ViewUtil.java
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/package-info.java
root/framework/trunk/impl/src/main/java/org/richfaces/context/AttributesContext.java
root/framework/trunk/impl/src/main/java/org/richfaces/context/ComponentCallback.java
root/framework/trunk/impl/src/main/java/org/richfaces/context/ContextProvider.java
root/framework/trunk/impl/src/main/java/org/richfaces/context/ExecuteComponentCallback.java
root/framework/trunk/impl/src/main/java/org/richfaces/context/PartialViewContextAjaxOutputTracker.java
root/framework/trunk/impl/src/main/java/org/richfaces/context/PartialViewContextFactoryImpl.java
root/framework/trunk/impl/src/main/java/org/richfaces/context/PartialViewContextImpl.java
root/framework/trunk/impl/src/main/java/org/richfaces/context/RenderComponentCallback.java
root/framework/trunk/impl/src/main/java/org/richfaces/context/SingletonsContext.java
root/framework/trunk/impl/src/main/java/org/richfaces/event/SwitchablePanelSwitchEvent.java
root/framework/trunk/impl/src/main/java/org/richfaces/event/package-info.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/CDL.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/Cookie.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/CookieList.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/HTTP.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/HTTPTokener.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSContentHandler.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONAccessor.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONArray.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONCollection.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONException.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONMap.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONObject.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONString.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONStringer.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONTokener.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONWriter.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/XML.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/XMLTokener.java
root/framework/trunk/impl/src/main/java/org/richfaces/json/package-info.java
Log:
Code style policy
https://jira.jboss.org/jira/browse/RFPL-195
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/component/EnclosingFormRequiredException.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/EnclosingFormRequiredException.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/EnclosingFormRequiredException.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,36 +19,37 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component;
import javax.faces.FacesException;
-
/**
* @author Filip Antonov - mailto:fantonov@exadel.com
* created 08.02.2007
- *
+ *
*/
public class EnclosingFormRequiredException extends FacesException {
- /**
- *
- */
- private static final long serialVersionUID = 1877777524838776600L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1877777524838776600L;
- public EnclosingFormRequiredException() {
- super();
- }
+ public EnclosingFormRequiredException() {
+ super();
+ }
- public EnclosingFormRequiredException(String message, Throwable cause) {
- super(message, cause);
- }
+ public EnclosingFormRequiredException(String message) {
+ super(message);
+ }
- public EnclosingFormRequiredException(String message) {
- super(message);
- }
+ public EnclosingFormRequiredException(Throwable cause) {
+ super(cause);
+ }
- public EnclosingFormRequiredException(Throwable cause) {
- super(cause);
- }
+ public EnclosingFormRequiredException(String message, Throwable cause) {
+ super(message, cause);
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/component/FileUploadConstants.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/FileUploadConstants.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/FileUploadConstants.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component;
import org.ajax4jsf.request.MultipartRequest;
@@ -27,40 +29,35 @@
* @author Nick Belaevski
* @since 3.3.0
*/
-
public final class FileUploadConstants {
+ public static final String FILE_UPLOAD_ACTION =
"_richfaces_file_upload_action";
+ public static final String FILE_UPLOAD_ACTION_PROGRESS = "progress";
+ public static final String FILE_UPLOAD_ACTION_STOP =
"richfaces_file_upload_action_stop";
- /**
- * Request parameter that indicates if multipart request forced by rich file
- * upload component
- */
- public static final String UPLOAD_FILES_ID = "_richfaces_upload_uid";
+ /** Request parameter name indicated that file was uploaded by RF component */
+ public static final String FILE_UPLOAD_INDICATOR =
"_richfaces_upload_file_indicator";
- /** Session bean name to store max files count allowed to upload */
- public static final String UPLOADED_COUNTER =
"_richfaces_uploaded_file_counter";
-
- /** Request parameter name indicated that file was uploaded by RF component */
- public static final String FILE_UPLOAD_INDICATOR =
"_richfaces_upload_file_indicator";
+ /** Session bean name where progress bar's percent map will be stored */
+ public static final String PERCENT_BEAN_NAME =
"_richfaces_upload_percents";
- /** Session bean name where request size will be stored */
- public static final String REQUEST_SIZE_BEAN_NAME =
"_richfaces_request_size";
+ /** Session bean name where stop keys will be stored */
+ public static final String REQUEST_KEYS_BEAN_NAME =
"_richfaces_request_keys";
- /** Session bean name where progress bar's percent map will be stored */
- public static final String PERCENT_BEAN_NAME = "_richfaces_upload_percents";
+ /** Session bean name where request size will be stored */
+ public static final String REQUEST_SIZE_BEAN_NAME =
"_richfaces_request_size";
- /** Session bean name where stop keys will be stored */
- public static final String REQUEST_KEYS_BEAN_NAME =
"_richfaces_request_keys";
+ /** Session bean name to store max files count allowed to upload */
+ public static final String UPLOADED_COUNTER =
"_richfaces_uploaded_file_counter";
- public static final String FILE_UPLOAD_ACTION =
"_richfaces_file_upload_action";
+ /**
+ * Request parameter that indicates if multipart request forced by rich file
+ * upload component
+ */
+ public static final String UPLOAD_FILES_ID = "_richfaces_upload_uid";
+ public static final String FILE_UPLOAD_REQUEST_ATTRIBUTE_NAME =
MultipartRequest.class.getName();
- public static final String FILE_UPLOAD_ACTION_STOP =
"richfaces_file_upload_action_stop";
-
- public static final String FILE_UPLOAD_ACTION_PROGRESS = "progress";
+ private FileUploadConstants() {
- public static final String FILE_UPLOAD_REQUEST_ATTRIBUTE_NAME =
MultipartRequest.class.getName();
-
- private FileUploadConstants() {
- //private constructor
- }
-
+ // private constructor
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/component/RowKeyContextEventWrapper.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/RowKeyContextEventWrapper.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/RowKeyContextEventWrapper.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -18,8 +18,10 @@
* 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.component;
import javax.faces.component.UIComponent;
@@ -29,26 +31,23 @@
/**
* @author Nick Belaevski
- *
+ *
*/
class RowKeyContextEventWrapper extends FacesEvent {
- /**
- *
- */
- private static final long serialVersionUID = -869970815228914529L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = -869970815228914529L;
+ private FacesEvent event;
+ private Object rowKey;
- private FacesEvent event;
-
- private Object rowKey;
-
public RowKeyContextEventWrapper(UIComponent component, FacesEvent event, Object
rowKey) {
- super(component);
-
- this.event = event;
- this.rowKey = rowKey;
+ super(component);
+ this.event = event;
+ this.rowKey = rowKey;
}
-
+
public FacesEvent getFacesEvent() {
return this.event;
}
@@ -68,12 +67,11 @@
public void processListener(FacesListener listener) {
throw new IllegalStateException();
}
-
- /**
- * @return the rowKey
- */
- public Object getRowKey() {
- return rowKey;
- }
-
+
+ /**
+ * @return the rowKey
+ */
+ public Object getRowKey() {
+ return rowKey;
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/component/SavedState.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/SavedState.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/SavedState.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -18,129 +18,122 @@
* 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.component;
+import org.ajax4jsf.component.IterationStateHolder;
+
import java.io.Serializable;
import javax.faces.component.EditableValueHolder;
import javax.faces.component.UIForm;
-import org.ajax4jsf.component.IterationStateHolder;
+//from RI
-// from RI
/**
* This class keep values of {@link EditableValueHolder} row-sensitive
* fields.
- *
+ *
* @author shura
- *
+ *
*/
final class SavedState implements Serializable {
+ public static final SavedState EMPTY = new SavedState();
+ private static final long serialVersionUID = 2920252657338389849L;
+ private boolean valid = true;
+ private Object iterationState;
+ private boolean localValueSet;
+ private boolean submitted;
+ private Object submittedValue;
+ private Object value;
- private Object submittedValue;
+ public SavedState() {
+ super();
+ }
- private Object iterationState;
+ public SavedState(EditableValueHolder evh) {
+ super();
+ this.value = evh.getLocalValue();
+ this.valid = evh.isValid();
+ this.submittedValue = evh.getSubmittedValue();
+ this.localValueSet = evh.isLocalValueSet();
+ }
- private Object value;
+ public SavedState(IterationStateHolder ish) {
+ super();
+ this.iterationState = ish.getIterationState();
+ }
- private boolean localValueSet;
+ public SavedState(UIForm form) {
+ super();
+ this.submitted = form.isSubmitted();
+ }
- private boolean submitted;
+ Object getSubmittedValue() {
+ return this.submittedValue;
+ }
- private static final long serialVersionUID = 2920252657338389849L;
+ void setSubmittedValue(Object submittedValue) {
+ this.submittedValue = submittedValue;
+ }
- public static final SavedState EMPTY = new SavedState();
-
- public SavedState() {
- super();
- }
-
- public SavedState(EditableValueHolder evh) {
- super();
+ boolean isValid() {
+ return this.valid;
+ }
- this.value = evh.getLocalValue();
- this.valid = evh.isValid();
- this.submittedValue = evh.getSubmittedValue();
- this.localValueSet = evh.isLocalValueSet();
- }
+ void setValid(boolean valid) {
+ this.valid = valid;
+ }
- public SavedState(IterationStateHolder ish) {
- super();
+ Object getValue() {
+ return this.value;
+ }
- this.iterationState = ish.getIterationState();
- }
-
- public SavedState(UIForm form) {
- super();
+ public void setValue(Object value) {
+ this.value = value;
+ }
- this.submitted = form.isSubmitted();
- }
-
- Object getSubmittedValue() {
- return (this.submittedValue);
- }
+ boolean isLocalValueSet() {
+ return this.localValueSet;
+ }
- void setSubmittedValue(Object submittedValue) {
- this.submittedValue = submittedValue;
- }
+ public void setLocalValueSet(boolean localValueSet) {
+ this.localValueSet = localValueSet;
+ }
- private boolean valid = true;
+ public Object getIterationState() {
+ return iterationState;
+ }
- boolean isValid() {
- return (this.valid);
- }
+ public void setIterationState(Object iterationState) {
+ this.iterationState = iterationState;
+ }
- void setValid(boolean valid) {
- this.valid = valid;
- }
+ @Override
+ public String toString() {
+ if (iterationState != null) {
+ return "iterationState: " + iterationState;
+ } else {
+ return "submittedValue: " + submittedValue + " value: " +
value + " localValueSet: " + localValueSet
+ + " submitted: " + submitted;
+ }
+ }
- Object getValue() {
- return (this.value);
- }
+ public void apply(EditableValueHolder evh) {
+ evh.setValue(this.value);
+ evh.setValid(this.valid);
+ evh.setSubmittedValue(this.submittedValue);
+ evh.setLocalValueSet(this.localValueSet);
+ }
- public void setValue(Object value) {
- this.value = value;
- }
+ public void apply(IterationStateHolder ish) {
+ ish.setIterationState(this.iterationState);
+ }
- boolean isLocalValueSet() {
- return (this.localValueSet);
- }
-
- public void setLocalValueSet(boolean localValueSet) {
- this.localValueSet = localValueSet;
- }
-
- public Object getIterationState() {
- return iterationState;
- }
-
- public void setIterationState(Object iterationState) {
- this.iterationState = iterationState;
- }
-
- public String toString() {
- if (iterationState != null) {
- return "iterationState: " + iterationState;
- } else {
- return "submittedValue: " + submittedValue + " value: " + value
- + " localValueSet: " + localValueSet + " submitted: " +
submitted;
- }
- }
-
- public void apply(EditableValueHolder evh) {
- evh.setValue(this.value);
- evh.setValid(this.valid);
- evh.setSubmittedValue(this.submittedValue);
- evh.setLocalValueSet(this.localValueSet);
- }
-
- public void apply(IterationStateHolder ish) {
- ish.setIterationState(this.iterationState);
- }
-
- public void apply(UIForm form) {
- form.setSubmitted(this.submitted);
- }
+ public void apply(UIForm form) {
+ form.setSubmitted(this.submitted);
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/component/UIDataAdaptor.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/UIDataAdaptor.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/UIDataAdaptor.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -18,13 +18,30 @@
* 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.component;
+import org.ajax4jsf.component.AjaxDataEncoder;
+import org.ajax4jsf.component.IterationStateHolder;
+import org.ajax4jsf.model.DataComponentState;
+import org.ajax4jsf.model.DataVisitResult;
+import org.ajax4jsf.model.DataVisitor;
+import org.ajax4jsf.model.ExtendedDataModel;
+import org.ajax4jsf.model.Range;
+import org.ajax4jsf.model.SerializableDataModel;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
import java.io.IOException;
import java.io.Serializable;
+
import java.text.MessageFormat;
+
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
@@ -33,6 +50,7 @@
import java.util.Set;
import javax.el.ValueExpression;
+
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.component.ContextCallback;
@@ -42,7 +60,6 @@
import javax.faces.component.StateHolder;
import javax.faces.component.UIComponent;
import javax.faces.component.UIComponentBase;
-import javax.faces.component.UIData;
import javax.faces.component.UIForm;
import javax.faces.component.UINamingContainer;
import javax.faces.component.UIViewRoot;
@@ -59,245 +76,269 @@
import javax.faces.event.FacesEvent;
import javax.faces.render.Renderer;
-import org.ajax4jsf.component.AjaxDataEncoder;
-import org.ajax4jsf.component.IterationStateHolder;
-import org.ajax4jsf.model.DataComponentState;
-import org.ajax4jsf.model.DataVisitResult;
-import org.ajax4jsf.model.DataVisitor;
-import org.ajax4jsf.model.ExtendedDataModel;
-import org.ajax4jsf.model.Range;
-import org.ajax4jsf.model.SerializableDataModel;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
/**
* Base class for iterable components, like dataTable, Tomahawk dataList,
* Facelets repeat, tree etc., with support for partial rendering on AJAX
* responces for one or more selected iterations.
- *
+ *
* @author shura
- *
+ *
*/
+
//TODO check AjaxDataEncoder
-public abstract class UIDataAdaptor extends UIComponentBase implements AjaxDataEncoder,
NamingContainer,
- UniqueIdVendor, IterationStateHolder {
+public abstract class UIDataAdaptor extends UIComponentBase
+ implements AjaxDataEncoder, NamingContainer, UniqueIdVendor, IterationStateHolder
{
+ /**
+ * <p>The standard component family for this component.</p>
+ */
+ public static final String COMPONENT_FAMILY = "org.richfaces.Data";
- /**
- * <p>The standard component type for this component.</p>
- */
- public static final String COMPONENT_TYPE = "org.richfaces.Data";
+ /**
+ * <p>The standard component type for this component.</p>
+ */
+ public static final String COMPONENT_TYPE = "org.richfaces.Data";
- /**
- * <p>The standard component family for this component.</p>
- */
- public static final String COMPONENT_FAMILY = "org.richfaces.Data";
+ private static final Logger LOG = RichfacesLogger.COMPONENTS.getLogger();
- private static final Logger log = RichfacesLogger.COMPONENTS.getLogger();
- private enum PropertyKeys {
- ajaxKeys, lastId, var, rowKeyVar, stateVar, childState, rowKeyConverter
- }
-
- private Object rowKey = null;
-
- private Object ajaxRowKey = null;
+ /**
+ * Visitor for process decode on children components.
+ */
+ protected ComponentVisitor decodeVisitor = new ComponentVisitor() {
+ @Override
+ public void processComponent(FacesContext context, UIComponent c, Object
argument) {
+ c.processDecodes(context);
+ }
+ };
- private DataComponentState componentState = null;
-
- private ExtendedDataModel<?> extendedDataModel = null;
+ /**
+ * Visitor for process validation phase
+ */
+ protected ComponentVisitor validateVisitor = new ComponentVisitor() {
+ @Override
+ public void processComponent(FacesContext context, UIComponent c, Object
argument) {
+ c.processValidators(context);
+ }
+ };
- private Object originalVarValue;
+ /**
+ * Visitor for process update model phase.
+ */
+ protected ComponentVisitor updateVisitor = new ComponentVisitor() {
+ @Override
+ public void processComponent(FacesContext context, UIComponent c, Object
argument) {
+ c.processUpdates(context);
+ }
+ };
- private String clientId;
-
- /**
- *
- */
- public UIDataAdaptor() {
- super();
- }
+ private Object ajaxRowKey = null;
+ private DataComponentState componentState = null;
+ private ExtendedDataModel<?> extendedDataModel = null;
+ private Object rowKey = null;
- /* (non-Javadoc)
- * @see javax.faces.component.UIComponent#getFamily()
- */
- @Override
- public String getFamily() {
- return COMPONENT_FAMILY;
- }
+ private String clientId;
+ private Object originalVarValue;
- /* (non-Javadoc)
- * @see org.ajax4jsf.component.AjaxDataEncoder#getAjaxKeys()
- */
- @SuppressWarnings("unchecked")
- public Set<Object> getAjaxKeys() {
- Set<Object> defaultAjaxKeys = null;
- if (ajaxRowKey != null) {
- //cannot use Collections.singleton() because ajaxKeys set should be modifiable
- defaultAjaxKeys = new HashSet<Object>(1);
- defaultAjaxKeys.add(ajaxRowKey);
- }
-
- return (Set<Object>) getStateHelper().eval(PropertyKeys.ajaxKeys,
- defaultAjaxKeys);
- }
+ private enum PropertyKeys {
+ ajaxKeys, lastId, var, rowKeyVar, stateVar, childState, rowKeyConverter
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.component.AjaxDataEncoder#setAjaxKeys(java.util.Set)
- */
- public void setAjaxKeys(Set<Object> ajaxKeys) {
- getStateHelper().put(PropertyKeys.ajaxKeys, ajaxKeys);
- }
+ public UIDataAdaptor() {
+ super();
+ }
- /* (non-Javadoc)
- * @see
org.ajax4jsf.component.AjaxChildrenEncoder#encodeAjaxChild(javax.faces.context.FacesContext,
java.lang.String, java.util.Set, java.util.Set)
- */
- public void encodeAjaxChild(FacesContext context, String path,
- Set<String> ids, Set<String> renderedAreas) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.component.UIComponent#getFamily()
+ */
+ @Override
+ public String getFamily() {
+ return COMPONENT_FAMILY;
+ }
- /* (non-Javadoc)
- * @see
javax.faces.component.UniqueIdVendor#createUniqueId(javax.faces.context.FacesContext,
java.lang.String)
- */
- public String createUniqueId(FacesContext context, String seed) {
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.component.AjaxDataEncoder#getAjaxKeys()
+ */
+ @SuppressWarnings("unchecked")
+ public Set<Object> getAjaxKeys() {
+ Set<Object> defaultAjaxKeys = null;
+
+ if (ajaxRowKey != null) {
+
+ // cannot use Collections.singleton() because ajaxKeys set should be
modifiable
+ defaultAjaxKeys = new HashSet<Object>(1);
+ defaultAjaxKeys.add(ajaxRowKey);
+ }
+
+ return (Set<Object>) getStateHelper().eval(PropertyKeys.ajaxKeys,
defaultAjaxKeys);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.component.AjaxDataEncoder#setAjaxKeys(java.util.Set)
+ */
+ public void setAjaxKeys(Set<Object> ajaxKeys) {
+ getStateHelper().put(PropertyKeys.ajaxKeys, ajaxKeys);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see
org.ajax4jsf.component.AjaxChildrenEncoder#encodeAjaxChild(javax.faces.context.FacesContext,
+ * java.lang.String, java.util.Set, java.util.Set)
+ */
+ public void encodeAjaxChild(FacesContext context, String path, Set<String> ids,
Set<String> renderedAreas)
+ throws IOException {
+
+ // TODO Auto-generated method stub
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see
javax.faces.component.UniqueIdVendor#createUniqueId(javax.faces.context.FacesContext,
java.lang.String)
+ */
+ public String createUniqueId(FacesContext context, String seed) {
Integer i = (Integer) getStateHelper().get(PropertyKeys.lastId);
- int lastId = ((i != null) ? i : 0);
- getStateHelper().put(PropertyKeys.lastId, ++lastId);
- return UIViewRoot.UNIQUE_ID_PREFIX + (seed == null ? lastId : seed);
- }
-
- /**
- * @return the rowKey
- */
- public Object getRowKey() {
- return rowKey;
- }
-
- /**
- * Setup current row by key. Perform same functionality as
- * {@link UIData#setRowIndex(int)}, but for key object - it may be not only
- * row number in sequence data, but, for example - path to current node in
- * tree.
- *
- * @param faces -
- * current FacesContext
- * @param key
- * new key value.
- */
- public void setRowKey(FacesContext facesContext, Object rowKey) {
- this.saveChildState(facesContext);
+ int lastId = (i != null) ? i : 0;
- this.rowKey = rowKey;
- this.clientId = null;
+ getStateHelper().put(PropertyKeys.lastId, ++lastId);
- getExtendedDataModel().setRowKey(rowKey);
+ return UIViewRoot.UNIQUE_ID_PREFIX + ((seed == null) ? lastId : seed);
+ }
- boolean rowSelected = (rowKey != null) && isRowAvailable();
- setupVariable(facesContext, rowSelected);
+ /**
+ * @return the rowKey
+ */
+ public Object getRowKey() {
+ return rowKey;
+ }
- this.restoreChildState(facesContext);
- }
-
- /**
- * Save values of {@link EditableValueHolder} fields before change current
- * row.
- *
- * @param faces
- */
- protected void saveChildState(FacesContext facesContext) {
- Iterator<UIComponent> itr = dataChildren();
- while (itr.hasNext()) {
- this.saveChildState(facesContext, (UIComponent) itr.next());
- }
- }
+ /**
+ * Setup current row by key. Perform same functionality as
+ * {@link javax.faces.component.UIData#setRowIndex(int)}, but for key object - it may
be not only
+ * row number in sequence data, but, for example - path to current node in
+ * tree.
+ *
+ * @param faces -
+ * current FacesContext
+ * @param key
+ * new key value.
+ */
+ public void setRowKey(FacesContext facesContext, Object rowKey) {
+ this.saveChildState(facesContext);
+ this.rowKey = rowKey;
+ this.clientId = null;
+ getExtendedDataModel().setRowKey(rowKey);
- /**
- * @param facesContext
- * @param next
- * @param childState
- */
- protected void saveChildState(FacesContext facesContext, UIComponent component) {
-
- //TODO - is it right?
- if (component.isTransient()) {
- return ;
- }
-
- SavedState state = null;
-
- if (component instanceof IterationStateHolder) {
- IterationStateHolder ish = (IterationStateHolder) component;
- state = new SavedState(ish);
- } else if (component instanceof EditableValueHolder) {
- EditableValueHolder evh = (EditableValueHolder) component;
- state = new SavedState(evh);
- } else if (component instanceof UIForm) {
- UIForm form = (UIForm) component;
- state = new SavedState(form);
- }
-
- if (state != null) {
- //TODO - use local map - children save their state themselves using visitors
- getStateHelper().put(PropertyKeys.childState,
- component.getClientId(facesContext), state);
- }
+ boolean rowSelected = (rowKey != null) && isRowAvailable();
- if (component.getChildCount() > 0) {
- for (UIComponent child: component.getChildren()) {
- saveChildState(facesContext, child);
- }
- }
-
- if (component.getFacetCount() > 0) {
- for (UIComponent facet: component.getFacets().values()) {
- saveChildState(facesContext, facet);
- }
- }
- }
+ setupVariable(facesContext, rowSelected);
+ this.restoreChildState(facesContext);
+ }
- protected Iterator<UIComponent> dataChildren() {
- if (getChildCount() > 0) {
- return getChildren().iterator();
- } else {
- return Collections.<UIComponent>emptyList().iterator();
- }
- }
-
- protected Iterator<UIComponent> fixedChildren() {
- if (getFacetCount() > 0) {
- return getFacets().values().iterator();
- } else {
- return Collections.<UIComponent>emptyList().iterator();
- }
- }
+ /**
+ * Save values of {@link EditableValueHolder} fields before change current
+ * row.
+ *
+ * @param faces
+ */
+ protected void saveChildState(FacesContext facesContext) {
+ Iterator<UIComponent> itr = dataChildren();
- /**
- * @param facesContext
- */
- protected void restoreChildState(FacesContext facesContext) {
- Iterator<UIComponent> itr = dataChildren();
- while (itr.hasNext()) {
- this.restoreChildState(facesContext, (UIComponent) itr.next());
- }
- }
+ while (itr.hasNext()) {
+ this.saveChildState(facesContext, (UIComponent) itr.next());
+ }
+ }
- /**
- * Restore values of {@link EditableValueHolder} fields after change current
- * row.
- * @param facesContext
- * @param next
- * @param childState
- */
- protected void restoreChildState(FacesContext facesContext, UIComponent component) {
-
+ /**
+ * @param facesContext
+ * @param next
+ * @param childState
+ */
+ protected void saveChildState(FacesContext facesContext, UIComponent component) {
+
+ // TODO - is it right?
+ if (component.isTransient()) {
+ return;
+ }
+
+ SavedState state = null;
+
+ if (component instanceof IterationStateHolder) {
+ IterationStateHolder ish = (IterationStateHolder) component;
+
+ state = new SavedState(ish);
+ } else if (component instanceof EditableValueHolder) {
+ EditableValueHolder evh = (EditableValueHolder) component;
+
+ state = new SavedState(evh);
+ } else if (component instanceof UIForm) {
+ UIForm form = (UIForm) component;
+
+ state = new SavedState(form);
+ }
+
+ if (state != null) {
+
+ // TODO - use local map - children save their state themselves using
visitors
+ getStateHelper().put(PropertyKeys.childState,
component.getClientId(facesContext), state);
+ }
+
+ if (component.getChildCount() > 0) {
+ for (UIComponent child : component.getChildren()) {
+ saveChildState(facesContext, child);
+ }
+ }
+
+ if (component.getFacetCount() > 0) {
+ for (UIComponent facet : component.getFacets().values()) {
+ saveChildState(facesContext, facet);
+ }
+ }
+ }
+
+ protected Iterator<UIComponent> dataChildren() {
+ if (getChildCount() > 0) {
+ return getChildren().iterator();
+ } else {
+ return Collections.<UIComponent>emptyList().iterator();
+ }
+ }
+
+ protected Iterator<UIComponent> fixedChildren() {
+ if (getFacetCount() > 0) {
+ return getFacets().values().iterator();
+ } else {
+ return Collections.<UIComponent>emptyList().iterator();
+ }
+ }
+
+ /**
+ * @param facesContext
+ */
+ protected void restoreChildState(FacesContext facesContext) {
+ Iterator<UIComponent> itr = dataChildren();
+
+ while (itr.hasNext()) {
+ this.restoreChildState(facesContext, (UIComponent) itr.next());
+ }
+ }
+
+ /**
+ * Restore values of {@link EditableValueHolder} fields after change current
+ * row.
+ * @param facesContext
+ * @param next
+ * @param childState
+ */
+ protected void restoreChildState(FacesContext facesContext, UIComponent component) {
String id = component.getId();
+
component.setId(id); // Forces client id to be reset
SavedState savedState = null;
- @SuppressWarnings("unchecked")
- Map<String, SavedState> savedStatesMap =
+ @SuppressWarnings("unchecked") Map<String, SavedState>
savedStatesMap =
(Map<String, SavedState>)
getStateHelper().get(PropertyKeys.childState);
if (savedStatesMap != null) {
@@ -305,749 +346,737 @@
}
if (savedState == null) {
- savedState = SavedState.EMPTY;
- }
-
-
+ savedState = SavedState.EMPTY;
+ }
+
if (component instanceof IterationStateHolder) {
- IterationStateHolder ish = (IterationStateHolder) component;
- savedState.apply(ish);
- } else if (component instanceof EditableValueHolder) {
- EditableValueHolder evh = (EditableValueHolder) component;
- savedState.apply(evh);
- } else if (component instanceof UIForm) {
- UIForm form = (UIForm) component;
- savedState.apply(form);
- }
-
- if (component.getChildCount() > 0) {
- for (UIComponent child: component.getChildren()) {
- restoreChildState(facesContext, child);
- }
- }
-
- if (component.getFacetCount() > 0) {
- for (UIComponent facet: component.getFacets().values()) {
- restoreChildState(facesContext, facet);
- }
- }
- }
+ IterationStateHolder ish = (IterationStateHolder) component;
- public void setRowKey(Object rowKey) {
- setRowKey(getFacesContext(), rowKey);
- }
+ savedState.apply(ish);
+ } else if (component instanceof EditableValueHolder) {
+ EditableValueHolder evh = (EditableValueHolder) component;
- protected boolean isAjaxKeyEvent(FacesEvent event) {
- return (event instanceof ActionEvent) || (event instanceof BehaviorEvent);
- }
-
- protected void addAjaxKeyEvent(FacesEvent event) {
- Object eventRowKey = getRowKey();
- if (null != eventRowKey) {
- this.ajaxRowKey = eventRowKey;
- }
- }
+ savedState.apply(evh);
+ } else if (component instanceof UIForm) {
+ UIForm form = (UIForm) component;
- /* (non-Javadoc)
- * @see javax.faces.component.UIComponentBase#queueEvent(javax.faces.event.FacesEvent)
- */
- @Override
- public void queueEvent(FacesEvent event) {
- if (isAjaxKeyEvent(event)) {
- addAjaxKeyEvent(event);
- }
+ savedState.apply(form);
+ }
- super.queueEvent(new RowKeyContextEventWrapper(this, event, getRowKey()));
- }
-
- /* (non-Javadoc)
- * @see javax.faces.component.UIComponentBase#broadcast(javax.faces.event.FacesEvent)
- */
- @Override
- public void broadcast(FacesEvent event) throws AbortProcessingException {
+ if (component.getChildCount() > 0) {
+ for (UIComponent child : component.getChildren()) {
+ restoreChildState(facesContext, child);
+ }
+ }
+
+ if (component.getFacetCount() > 0) {
+ for (UIComponent facet : component.getFacets().values()) {
+ restoreChildState(facesContext, facet);
+ }
+ }
+ }
+
+ public void setRowKey(Object rowKey) {
+ setRowKey(getFacesContext(), rowKey);
+ }
+
+ protected boolean isAjaxKeyEvent(FacesEvent event) {
+ return (event instanceof ActionEvent) || (event instanceof BehaviorEvent);
+ }
+
+ protected void addAjaxKeyEvent(FacesEvent event) {
+ Object eventRowKey = getRowKey();
+
+ if (null != eventRowKey) {
+ this.ajaxRowKey = eventRowKey;
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see
javax.faces.component.UIComponentBase#queueEvent(javax.faces.event.FacesEvent)
+ */
+ @Override
+ public void queueEvent(FacesEvent event) {
+ if (isAjaxKeyEvent(event)) {
+ addAjaxKeyEvent(event);
+ }
+
+ super.queueEvent(new RowKeyContextEventWrapper(this, event, getRowKey()));
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see
javax.faces.component.UIComponentBase#broadcast(javax.faces.event.FacesEvent)
+ */
+ @Override
+ public void broadcast(FacesEvent event) throws AbortProcessingException {
if (!(event instanceof RowKeyContextEventWrapper)) {
- if (!broadcastLocal(event)) {
+ if (!broadcastLocal(event)) {
super.broadcast(event);
- }
+ }
+
return;
}
+
FacesContext context = getFacesContext();
+
// Set up the correct context and fire our wrapped event
RowKeyContextEventWrapper revent = (RowKeyContextEventWrapper) event;
+ Object oldRowKey = getRowKey();
- Object oldRowKey = getRowKey();
setRowKey(revent.getRowKey());
+
FacesEvent rowEvent = revent.getFacesEvent();
UIComponent source = rowEvent.getComponent();
UIComponent compositeParent = null;
+
try {
if (!UIComponent.isCompositeComponent(source)) {
compositeParent = UIComponent.getCompositeComponentParent(source);
}
+
if (compositeParent != null) {
compositeParent.pushComponentToEL(context, null);
}
+
source.pushComponentToEL(context, null);
source.broadcast(rowEvent);
} finally {
source.popComponentFromEL(context);
+
if (compositeParent != null) {
compositeParent.popComponentFromEL(context);
}
}
-
+
setRowKey(oldRowKey);
- }
+ }
- /**
- * Process events targetted for concrete implementation. Hook method called
- * from {@link #broadcast(FacesEvent)}
- *
- * @param event -
- * processed event.
- * @return true if event processed, false if component must continue
- * processing.
- */
- //TODO - is it still actual?
- protected boolean broadcastLocal(FacesEvent event) {
- return false;
- }
+ /**
+ * Process events targetted for concrete implementation. Hook method called
+ * from {@link #broadcast(FacesEvent)}
+ *
+ * @param event -
+ * processed event.
+ * @return true if event processed, false if component must continue
+ * processing.
+ */
- /**
- * @return the extendedDataModel
- */
- protected ExtendedDataModel<?> getExtendedDataModel() {
- if (extendedDataModel == null) {
- extendedDataModel = createExtendedDataModel();
- }
- return extendedDataModel;
- }
-
- /**
- * @return
- */
- protected abstract ExtendedDataModel<?> createExtendedDataModel();
+ // TODO - is it still actual?
+ protected boolean broadcastLocal(FacesEvent event) {
+ return false;
+ }
- /**
- * @param extendedDataModel the extendedDataModel to set
- */
- protected void setExtendedDataModel(ExtendedDataModel<?> extendedDataModel) {
- this.extendedDataModel = extendedDataModel;
- }
+ /**
+ * @return the extendedDataModel
+ */
+ protected ExtendedDataModel<?> getExtendedDataModel() {
+ if (extendedDataModel == null) {
+ extendedDataModel = createExtendedDataModel();
+ }
- public String getVar() {
- return (String) getStateHelper().get(PropertyKeys.var);
- }
-
- public void setVar(String var) {
- getStateHelper().put(PropertyKeys.var, var);
- }
-
- public String getRowKeyVar() {
- return (String) getStateHelper().get(PropertyKeys.rowKeyVar);
- }
-
- public void setRowKeyVar(String rowKeyVar) {
- getStateHelper().put(PropertyKeys.rowKeyVar, rowKeyVar);
- }
-
- public String getStateVar() {
- return (String) getStateHelper().get(PropertyKeys.stateVar);
- }
-
- public void setStateVar(String stateVar) {
- getStateHelper().put(PropertyKeys.stateVar, stateVar);
- }
+ return extendedDataModel;
+ }
- //TODO - review and probably remove
- public int getRowCount() {
- return getExtendedDataModel().getRowCount();
- }
+ /**
+ * @return
+ */
+ protected abstract ExtendedDataModel<?> createExtendedDataModel();
- public Object getRowData() {
- return getExtendedDataModel().getRowData();
- }
+ /**
+ * @param extendedDataModel the extendedDataModel to set
+ */
+ protected void setExtendedDataModel(ExtendedDataModel<?> extendedDataModel) {
+ this.extendedDataModel = extendedDataModel;
+ }
- public boolean isRowAvailable() {
- return getExtendedDataModel().isRowAvailable();
- }
+ public String getVar() {
+ return (String) getStateHelper().get(PropertyKeys.var);
+ }
- /**
- * Setup EL variable for different iteration. Value of row data and
- * component state will be put into request scope attributes with names
- * given by "var" and "varState" bean properties.
- *
- * Changed: does not check for row availability now
- *
- * @param faces
- * current faces context
- * @param localModel
- * @param rowSelected
- */
- protected void setupVariable(FacesContext faces, boolean rowSelected) {
- Map<String, Object> attrs = faces.getExternalContext().getRequestMap();
- if (rowSelected) {
- // Current row data.
- setupVariable(getVar(), attrs, getRowData());
- // Component state variable.
- setupVariable(getStateVar(), attrs, getComponentState());
- // Row key Data variable.
- setupVariable(getRowKeyVar(), attrs, getRowKey());
+ public void setVar(String var) {
+ getStateHelper().put(PropertyKeys.var, var);
+ }
- } else {
- removeVariable(getVar(), attrs);
- removeVariable(getStateVar(), attrs);
- removeVariable(getRowKeyVar(), attrs);
- }
- }
+ public String getRowKeyVar() {
+ return (String) getStateHelper().get(PropertyKeys.rowKeyVar);
+ }
- /**
- * @return
- */
- public DataComponentState getComponentState() {
- if (componentState != null) {
- return componentState;
- }
-
- ValueExpression componentStateExpression =
getValueExpression("componentState");
- if (componentStateExpression != null) {
- componentState = (DataComponentState)
componentStateExpression.getValue(getFacesContext().getELContext());
- }
-
- if (componentState == null) {
- componentState = createComponentState();
+ public void setRowKeyVar(String rowKeyVar) {
+ getStateHelper().put(PropertyKeys.rowKeyVar, rowKeyVar);
+ }
- if (componentStateExpression != null &&
- !componentStateExpression.isReadOnly(getFacesContext().getELContext())) {
-
- componentStateExpression.setValue(getFacesContext().getELContext(), componentState);
- }
- }
-
- return componentState;
- }
+ public String getStateVar() {
+ return (String) getStateHelper().get(PropertyKeys.stateVar);
+ }
- protected abstract DataComponentState createComponentState();
-
- /**
- * @param var
- * @param attrs
- * @param rowData
- */
- private void setupVariable(String var, Map<String, Object> attrs, Object rowData)
{
- if (var != null) {
- attrs.put(var, rowData);
- }
- }
+ public void setStateVar(String stateVar) {
+ getStateHelper().put(PropertyKeys.stateVar, stateVar);
+ }
- /**
- * @param var
- * @param attrs
- * @param rowData
- */
- private void removeVariable(String var, Map<String, Object> attrs) {
- if (var != null) {
- attrs.remove(var);
- }
- }
+ // TODO - review and probably remove
+ public int getRowCount() {
+ return getExtendedDataModel().getRowCount();
+ }
- public Converter getRowKeyConverter() {
- return (Converter) getStateHelper().eval(PropertyKeys.rowKeyConverter);
- }
-
- public void setRowKeyConverter(Converter converter) {
- //TODO - handle partial state saving
- getStateHelper().put(PropertyKeys.rowKeyConverter, converter);
- }
+ public Object getRowData() {
+ return getExtendedDataModel().getRowData();
+ }
- @Override
- public String getClientId(FacesContext facesContext) {
+ public boolean isRowAvailable() {
+ return getExtendedDataModel().isRowAvailable();
+ }
+
+ /**
+ * Setup EL variable for different iteration. Value of row data and
+ * component state will be put into request scope attributes with names
+ * given by "var" and "varState" bean properties.
+ *
+ * Changed: does not check for row availability now
+ *
+ * @param faces
+ * current faces context
+ * @param localModel
+ * @param rowSelected
+ */
+ protected void setupVariable(FacesContext faces, boolean rowSelected) {
+ Map<String, Object> attrs = faces.getExternalContext().getRequestMap();
+
+ if (rowSelected) {
+
+ // Current row data.
+ setupVariable(getVar(), attrs, getRowData());
+
+ // Component state variable.
+ setupVariable(getStateVar(), attrs, getComponentState());
+
+ // Row key Data variable.
+ setupVariable(getRowKeyVar(), attrs, getRowKey());
+ } else {
+ removeVariable(getVar(), attrs);
+ removeVariable(getStateVar(), attrs);
+ removeVariable(getRowKeyVar(), attrs);
+ }
+ }
+
+ /**
+ * @return
+ */
+ public DataComponentState getComponentState() {
+ if (componentState != null) {
+ return componentState;
+ }
+
+ ValueExpression componentStateExpression =
getValueExpression("componentState");
+
+ if (componentStateExpression != null) {
+ componentState = (DataComponentState)
componentStateExpression.getValue(getFacesContext().getELContext());
+ }
+
+ if (componentState == null) {
+ componentState = createComponentState();
+
+ if ((componentStateExpression != null)
+ &&
!componentStateExpression.isReadOnly(getFacesContext().getELContext())) {
+ componentStateExpression.setValue(getFacesContext().getELContext(),
componentState);
+ }
+ }
+
+ return componentState;
+ }
+
+ protected abstract DataComponentState createComponentState();
+
+ /**
+ * @param var
+ * @param attrs
+ * @param rowData
+ */
+ private void setupVariable(String var, Map<String, Object> attrs, Object
rowData) {
+ if (var != null) {
+ attrs.put(var, rowData);
+ }
+ }
+
+ /**
+ * @param var
+ * @param attrs
+ * @param rowData
+ */
+ private void removeVariable(String var, Map<String, Object> attrs) {
+ if (var != null) {
+ attrs.remove(var);
+ }
+ }
+
+ public Converter getRowKeyConverter() {
+ return (Converter) getStateHelper().eval(PropertyKeys.rowKeyConverter);
+ }
+
+ public void setRowKeyConverter(Converter converter) {
+
+ // TODO - handle partial state saving
+ getStateHelper().put(PropertyKeys.rowKeyConverter, converter);
+ }
+
+ @Override
+ public String getClientId(FacesContext facesContext) {
if (facesContext == null) {
throw new NullPointerException("context");
}
- if (null == clientId) {
- StringBuilder id = new StringBuilder(super.getClientId(facesContext));
- Object rowKey = getRowKey();
- if (rowKey != null) {
- // Use converter to get String representation ot the row key.
- Converter rowKeyConverter = getRowKeyConverter();
- if(null == rowKeyConverter){
- // Create default converter for a row key.
- rowKeyConverter = facesContext.getApplication().createConverter(rowKey.getClass());
- // Store converter for a invokeOnComponents call.
- if(null != rowKeyConverter){
- setRowKeyConverter(rowKeyConverter);
- }
- }
- String rowKeyString;
- if (null != rowKeyConverter) {
- // Temporary set clientId, to avoid infinite calls from converter.
- clientId = id.toString();
- rowKeyString = rowKeyConverter.getAsString(facesContext, this, rowKey);
- } else {
- rowKeyString = rowKey.toString();
- }
-
- id.append(UINamingContainer.getSeparatorChar(facesContext)).append(rowKeyString);
- }
-
- Renderer renderer = getRenderer(facesContext);
- if (null != renderer) {
- clientId = renderer.convertClientId(facesContext, id.toString());
- } else {
- clientId = id.toString();
- }
- }
-
- return clientId;
- }
-
- /**
- * Base class for visit data model at phases decode, validation and update
- * model
- *
- * @author shura
- *
- */
- protected abstract class ComponentVisitor implements DataVisitor {
+ if (null == clientId) {
+ StringBuilder id = new StringBuilder(super.getClientId(facesContext));
+ Object rowKey = getRowKey();
- public DataVisitResult process(FacesContext context, Object rowKey, Object argument) {
- setRowKey(context, rowKey);
- if (isRowAvailable()) {
- Iterator<UIComponent> childIterator = dataChildren();
- while (childIterator.hasNext()) {
- UIComponent component = childIterator.next();
- processComponent(context, component, argument);
- }
- }
-
- return DataVisitResult.CONTINUE;
- }
+ if (rowKey != null) {
- public abstract void processComponent(FacesContext context,
- UIComponent c, Object argument);
+ // Use converter to get String representation ot the row key.
+ Converter rowKeyConverter = getRowKeyConverter();
- }
+ if (null == rowKeyConverter) {
- /**
- * Visitor for process decode on children components.
- */
- protected ComponentVisitor decodeVisitor = new ComponentVisitor() {
+ // Create default converter for a row key.
+ rowKeyConverter =
facesContext.getApplication().createConverter(rowKey.getClass());
- public void processComponent(FacesContext context, UIComponent c,
- Object argument) {
- c.processDecodes(context);
- }
+ // Store converter for a invokeOnComponents call.
+ if (null != rowKeyConverter) {
+ setRowKeyConverter(rowKeyConverter);
+ }
+ }
- };
+ String rowKeyString;
- /**
- * Visitor for process validation phase
- */
- protected ComponentVisitor validateVisitor = new ComponentVisitor() {
+ if (null != rowKeyConverter) {
- public void processComponent(FacesContext context, UIComponent c,
- Object argument) {
- c.processValidators(context);
- }
+ // Temporary set clientId, to avoid infinite calls from converter.
+ clientId = id.toString();
+ rowKeyString = rowKeyConverter.getAsString(facesContext, this,
rowKey);
+ } else {
+ rowKeyString = rowKey.toString();
+ }
- };
+
id.append(UINamingContainer.getSeparatorChar(facesContext)).append(rowKeyString);
+ }
- /**
- * Visitor for process update model phase.
- */
- protected ComponentVisitor updateVisitor = new ComponentVisitor() {
+ Renderer renderer = getRenderer(facesContext);
- public void processComponent(FacesContext context, UIComponent c,
- Object argument) {
- c.processUpdates(context);
- }
+ if (null != renderer) {
+ clientId = renderer.convertClientId(facesContext, id.toString());
+ } else {
+ clientId = id.toString();
+ }
+ }
- };
+ return clientId;
+ }
- /**
- * Save current state of data variable.
- *
- * @param faces
- * current faces context
- */
- //TODO move into walk() method body
- public void captureOrigValue(FacesContext faces) {
- String var = getVar();
- if (var != null) {
- Map<String, Object> attrs = faces.getExternalContext().getRequestMap();
- this.originalVarValue = attrs.get(var);
- }
-
- //TODO add support for another variables
- }
+ /**
+ * Save current state of data variable.
+ *
+ * @param faces
+ * current faces context
+ */
- /**
- * Restore value of data variable after processing phase.
- *
- * @param faces
- * current faces context
- */
- public void restoreOrigValue(FacesContext faces) {
- String var = getVar();
- if (var != null) {
- Map<String, Object> attrs = faces.getExternalContext().getRequestMap();
- if (this.originalVarValue != null) {
- attrs.put(var, this.originalVarValue);
- } else {
- attrs.remove(var);
- }
- }
- }
+ // TODO move into walk() method body
+ public void captureOrigValue(FacesContext faces) {
+ String var = getVar();
- /* (non-Javadoc)
- * @see javax.faces.component.UIComponent#setValueExpression(java.lang.String,
javax.el.ValueExpression)
- */
- @Override
- public void setValueExpression(String name, ValueExpression binding) {
- if ("var".equals(name) || "rowKeyVar".equals(name) ||
"stateVar".equals(name)) {
- throw new IllegalArgumentException(MessageFormat.format("{0} cannot be
EL-expression",
- name));
- }
-
- super.setValueExpression(name, binding);
- }
-
- /**
- * Check for validation errors on children components. If true, saved values
- * must be keep on render phase
- *
- * @param context
- * @return
- */
- protected boolean keepSaved(FacesContext context) {
- // For an any validation errors, children components state should be preserved
- FacesMessage.Severity sev = context.getMaximumSeverity();
- return (sev != null && (FacesMessage.SEVERITY_ERROR.compareTo(sev) >= 0));
- }
-
-
- /**
- * Perform iteration on all children components and all data rows with given
- * visitor.
- *
- * @param faces
- * @param visitor
- */
- protected void iterate(FacesContext faces, ComponentVisitor visitor) {
- // stop if not rendered
- if (!this.isRendered()) {
- return;
- }
+ if (var != null) {
+ Map<String, Object> attrs =
faces.getExternalContext().getRequestMap();
- // reset rowIndex
- this.captureOrigValue(faces);
- this.setRowKey(faces, null);
-
- try {
- Iterator<UIComponent> fixedChildren = fixedChildren();
- while (fixedChildren.hasNext()) {
- UIComponent component = fixedChildren.next();
- visitor.processComponent(faces, component, null);
- }
+ this.originalVarValue = attrs.get(var);
+ }
- walk(faces, visitor, null);
- } catch (Exception e) {
- throw new FacesException(e);
- } finally {
- this.setRowKey(faces, null);
- this.restoreOrigValue(faces);
- }
- }
+ // TODO add support for another variables
+ }
-
- /**
- * Walk ( visit ) this component on all data-aware children for each row.
- *
- * @param faces
- * @param visitor
- */
- public void walk(FacesContext faces, DataVisitor visitor, Object argument) {
- Range range = null;
-
- DataComponentState componentState = getComponentState();
- if (componentState != null) {
- range = componentState.getRange();
- }
-
- getExtendedDataModel().walk(faces, visitor, range, argument);
- }
+ /**
+ * Restore value of data variable after processing phase.
+ *
+ * @param faces
+ * current faces context
+ */
+ public void restoreOrigValue(FacesContext faces) {
+ String var = getVar();
- public void processDecodes(FacesContext faces) {
- if (!this.isRendered()) {
- return;
- }
-
- this.iterate(faces, decodeVisitor);
- this.decode(faces);
- }
+ if (var != null) {
+ Map<String, Object> attrs =
faces.getExternalContext().getRequestMap();
- public void processValidators(FacesContext faces) {
- if (!this.isRendered()) {
- return ;
- }
+ if (this.originalVarValue != null) {
+ attrs.put(var, this.originalVarValue);
+ } else {
+ attrs.remove(var);
+ }
+ }
+ }
- this.iterate(faces, validateVisitor);
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.component.UIComponent#setValueExpression(java.lang.String,
javax.el.ValueExpression)
+ */
+ @Override
+ public void setValueExpression(String name, ValueExpression binding) {
+ if ("var".equals(name) || "rowKeyVar".equals(name) ||
"stateVar".equals(name)) {
+ throw new IllegalArgumentException(MessageFormat.format("{0} cannot be
EL-expression", name));
+ }
- public void processUpdates(FacesContext faces) {
- if (!this.isRendered()) {
- return;
- }
-
- this.iterate(faces, updateVisitor);
- ExtendedDataModel<?> dataModel = getExtendedDataModel();
- // If no validation errors, update values for serializable model,
- // restored from view.
- if (dataModel instanceof SerializableDataModel && (!keepSaved(faces))) {
- SerializableDataModel serializableModel = (SerializableDataModel) dataModel;
- serializableModel.update();
- }
- }
+ super.setValueExpression(name, binding);
+ }
- @Override
- public void setId(String id) {
- super.setId(id);
- this.clientId = null;
- }
+ /**
+ * Check for validation errors on children components. If true, saved values
+ * must be keep on render phase
+ *
+ * @param context
+ * @return
+ */
+ protected boolean keepSaved(FacesContext context) {
- /* (non-Javadoc)
- * @see org.ajax4jsf.component.IterationStateHolder#getIterationState()
- */
- public Object getIterationState() {
- assert (rowKey == null);
-
- StateHelper stateHelper = getStateHelper();
-
- return new Object[] {
- stateHelper.get(PropertyKeys.childState),
- this.componentState,
- this.ajaxRowKey,
- this.extendedDataModel,
- };
- }
-
- /* (non-Javadoc)
- * @see org.ajax4jsf.component.IterationStateHolder#setIterationState(java.lang.Object)
- */
- public void setIterationState(Object stateObject) {
- assert (rowKey == null);
- //TODO - ?
- //restoreChildState(getFacesContext());
+ // For an any validation errors, children components state should be preserved
+ FacesMessage.Severity sev = context.getMaximumSeverity();
- StateHelper stateHelper = getStateHelper();
- if (stateObject != null) {
- Object[] state = (Object[]) stateObject;
-
- stateHelper.put(PropertyKeys.childState, state[0]);
- this.componentState = (DataComponentState) state[1];
- this.ajaxRowKey = state[2];
- this.extendedDataModel = (ExtendedDataModel<?>) state[3];
- } else {
- stateHelper.remove(PropertyKeys.childState);
- this.componentState = null;
- this.ajaxRowKey = null;
- this.extendedDataModel = null;
- }
- }
+ return (sev != null) && (FacesMessage.SEVERITY_ERROR.compareTo(sev) >=
0);
+ }
- protected void resetDataModel(FacesContext context) {
- this.extendedDataModel = null;
- }
-
- protected void resetChildState(FacesContext context) {
- getStateHelper().remove(PropertyKeys.childState);
- }
-
- protected void preEncodeBegin(FacesContext context) {
- resetDataModel(context);
-
- if (!keepSaved(context)) {
- resetChildState(context);
- }
- }
+ /**
+ * Perform iteration on all children components and all data rows with given
+ * visitor.
+ *
+ * @param faces
+ * @param visitor
+ */
+ protected void iterate(FacesContext faces, ComponentVisitor visitor) {
- @Override
- public void encodeBegin(FacesContext context) throws IOException {
- preEncodeBegin(context);
-
- super.encodeBegin(context);
- }
+ // stop if not rendered
+ if (!this.isRendered()) {
+ return;
+ }
- /* (non-Javadoc)
- * @see
javax.faces.component.UIComponentBase#saveState(javax.faces.context.FacesContext)
- */
- @Override
- public Object saveState(FacesContext context) {
- //TODO handle model serialization - "execute" model
- Boolean componentStateIsStateHolder = null;
- Object savedComponentState = null;
-
- //TODO - partial state saving handling
- if (componentState instanceof StateHolder) {
- componentStateIsStateHolder = Boolean.TRUE;
- StateHolder stateHolder = (StateHolder) componentState;
- if (!stateHolder.isTransient()) {
- savedComponentState = stateHolder.saveState(context);
- }
- } else {
- componentStateIsStateHolder = Boolean.FALSE;
- if (componentState instanceof Serializable) {
- savedComponentState = componentState;
- }
- }
-
- return new Object[] {
- super.saveState(context),
- savedComponentState,
- componentStateIsStateHolder
- };
- }
-
- /* (non-Javadoc)
- * @see
javax.faces.component.UIComponentBase#restoreState(javax.faces.context.FacesContext,
java.lang.Object)
- */
- @Override
- public void restoreState(FacesContext context, Object stateObject) {
- Object[] state = (Object[]) stateObject;
- // TODO Auto-generated method stub
- super.restoreState(context, state[0]);
+ // reset rowIndex
+ this.captureOrigValue(faces);
+ this.setRowKey(faces, null);
- Object savedComponentState = state[1];
- if (savedComponentState != null) {
- boolean componentStateIsStateHolder = ((Boolean) state[2]).booleanValue();
- if (componentStateIsStateHolder) {
- componentState = createComponentState();
- ((StateHolder) componentState).restoreState(context, savedComponentState);
- } else {
- componentState = (DataComponentState) restoreAttachedState(context,
savedComponentState);
- }
-
- //TODO update state model binding
- }
- }
-
- private boolean matchesBaseId(String clientId, String baseId, char separatorChar) {
- if (clientId.equals(baseId)) {
- return true;
- }
-
- //if clientId.startsWith(baseId + separatorChar)
- if (clientId.startsWith(baseId) && clientId.length() > baseId.length()
&&
- clientId.charAt(baseId.length()) == separatorChar) {
-
- return true;
- }
-
- return false;
- }
-
-
- @Override
- public boolean invokeOnComponent(FacesContext context, String clientId,
- ContextCallback callback) throws FacesException {
- if (null == context || null == clientId || null == callback) {
- throw new NullPointerException();
- }
-
- String baseId = super.getClientId(context);
- if (!matchesBaseId(clientId, baseId, UINamingContainer.getSeparatorChar(context))) {
- return false;
- }
-
- boolean found = false;
- Object oldRowKey = getRowKey();
+ try {
+ Iterator<UIComponent> fixedChildren = fixedChildren();
- //TODO - this does not seem right
- captureOrigValue(context);
-
- try {
- //TODO - ?
- //if (null != oldRowKey) {
- setRowKey(context, null);
- //}
-
- if (clientId.equals(baseId)) {
- callback.invokeContextCallback(context, this);
- found = true;
- } else {
- Iterator<UIComponent> fixedChildrenItr = fixedChildren();
- while (fixedChildrenItr.hasNext() && !found) {
- UIComponent fixedChild = fixedChildrenItr.next();
- found = fixedChild.invokeOnComponent(context, clientId, callback);
- }
- }
-
- if (!found) {
- Object newRowKey = null;
- // Call for a child component - try to detect row key
- // baseId.length() + 1 expression skips SEPARATOR_CHAR
- String rowKeyString = extractKeySegment(context,
- clientId.substring(baseId.length() + 1));
- if (rowKeyString != null) {
- Converter keyConverter = getRowKeyConverter();
- if (null != keyConverter) {
- try {
- newRowKey = keyConverter.getAsObject(context, this,
- rowKeyString);
- } catch (ConverterException e) {
- // TODO: log error
- }
- }
- }
-
- setRowKey(context, newRowKey);
-
- if (isRowAvailable()) {
- Iterator<UIComponent> dataChildrenItr = dataChildren();
- while (dataChildrenItr.hasNext() && !found) {
- UIComponent dataChild = dataChildrenItr.next();
- found = dataChild.invokeOnComponent(context, clientId, callback);
- }
- }
- }
- } catch (Exception e) {
- throw new FacesException(e);
- } finally {
- //if (null != oldRowKey) {
- try {
- setRowKey(context, oldRowKey);
- restoreOrigValue(context);
- } catch (Exception e) {
- log.error(e.getMessage(), e);
- }
- //}
- }
-
- return found;
- }
-
+ while (fixedChildren.hasNext()) {
+ UIComponent component = fixedChildren.next();
+
+ visitor.processComponent(faces, component, null);
+ }
+
+ walk(faces, visitor, null);
+ } catch (Exception e) {
+ throw new FacesException(e);
+ } finally {
+ this.setRowKey(faces, null);
+ this.restoreOrigValue(faces);
+ }
+ }
+
+ /**
+ * Walk ( visit ) this component on all data-aware children for each row.
+ *
+ * @param faces
+ * @param visitor
+ */
+ public void walk(FacesContext faces, DataVisitor visitor, Object argument) {
+ Range range = null;
+ DataComponentState componentState = getComponentState();
+
+ if (componentState != null) {
+ range = componentState.getRange();
+ }
+
+ getExtendedDataModel().walk(faces, visitor, range, argument);
+ }
+
+ public void processDecodes(FacesContext faces) {
+ if (!this.isRendered()) {
+ return;
+ }
+
+ this.iterate(faces, decodeVisitor);
+ this.decode(faces);
+ }
+
+ public void processValidators(FacesContext faces) {
+ if (!this.isRendered()) {
+ return;
+ }
+
+ this.iterate(faces, validateVisitor);
+ }
+
+ public void processUpdates(FacesContext faces) {
+ if (!this.isRendered()) {
+ return;
+ }
+
+ this.iterate(faces, updateVisitor);
+
+ ExtendedDataModel<?> dataModel = getExtendedDataModel();
+
+ // If no validation errors, update values for serializable model,
+ // restored from view.
+ if ((dataModel instanceof SerializableDataModel) && (!keepSaved(faces)))
{
+ SerializableDataModel serializableModel = (SerializableDataModel) dataModel;
+
+ serializableModel.update();
+ }
+ }
+
+ @Override
+ public void setId(String id) {
+ super.setId(id);
+ this.clientId = null;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.component.IterationStateHolder#getIterationState()
+ */
+ public Object getIterationState() {
+ assert rowKey == null;
+
+ StateHelper stateHelper = getStateHelper();
+
+ return new Object[] {stateHelper.get(PropertyKeys.childState),
this.componentState, this.ajaxRowKey,
+ this.extendedDataModel, };
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see
org.ajax4jsf.component.IterationStateHolder#setIterationState(java.lang.Object)
+ */
+ public void setIterationState(Object stateObject) {
+ assert rowKey == null;
+
+ // TODO - ?
+ // restoreChildState(getFacesContext());
+ StateHelper stateHelper = getStateHelper();
+
+ if (stateObject != null) {
+ Object[] state = (Object[]) stateObject;
+
+ stateHelper.put(PropertyKeys.childState, state[0]);
+ this.componentState = (DataComponentState) state[1];
+ this.ajaxRowKey = state[2];
+ this.extendedDataModel = (ExtendedDataModel<?>) state[3];
+ } else {
+ stateHelper.remove(PropertyKeys.childState);
+ this.componentState = null;
+ this.ajaxRowKey = null;
+ this.extendedDataModel = null;
+ }
+ }
+
+ protected void resetDataModel(FacesContext context) {
+ this.extendedDataModel = null;
+ }
+
+ protected void resetChildState(FacesContext context) {
+ getStateHelper().remove(PropertyKeys.childState);
+ }
+
+ protected void preEncodeBegin(FacesContext context) {
+ resetDataModel(context);
+
+ if (!keepSaved(context)) {
+ resetChildState(context);
+ }
+ }
+
+ @Override
+ public void encodeBegin(FacesContext context) throws IOException {
+ preEncodeBegin(context);
+ super.encodeBegin(context);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see
javax.faces.component.UIComponentBase#saveState(javax.faces.context.FacesContext)
+ */
+ @Override
+ public Object saveState(FacesContext context) {
+
+ // TODO handle model serialization - "execute" model
+ Boolean componentStateIsStateHolder = null;
+ Object savedComponentState = null;
+
+ // TODO - partial state saving handling
+ if (componentState instanceof StateHolder) {
+ componentStateIsStateHolder = Boolean.TRUE;
+
+ StateHolder stateHolder = (StateHolder) componentState;
+
+ if (!stateHolder.isTransient()) {
+ savedComponentState = stateHolder.saveState(context);
+ }
+ } else {
+ componentStateIsStateHolder = Boolean.FALSE;
+
+ if (componentState instanceof Serializable) {
+ savedComponentState = componentState;
+ }
+ }
+
+ return new Object[] {super.saveState(context), savedComponentState,
componentStateIsStateHolder};
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see
javax.faces.component.UIComponentBase#restoreState(javax.faces.context.FacesContext,
java.lang.Object)
+ */
+ @Override
+ public void restoreState(FacesContext context, Object stateObject) {
+ Object[] state = (Object[]) stateObject;
+
+ // TODO Auto-generated method stub
+ super.restoreState(context, state[0]);
+
+ Object savedComponentState = state[1];
+
+ if (savedComponentState != null) {
+ boolean componentStateIsStateHolder = ((Boolean) state[2]).booleanValue();
+
+ if (componentStateIsStateHolder) {
+ componentState = createComponentState();
+ ((StateHolder) componentState).restoreState(context,
savedComponentState);
+ } else {
+ componentState = (DataComponentState) restoreAttachedState(context,
savedComponentState);
+ }
+
+ // TODO update state model binding
+ }
+ }
+
+ private boolean matchesBaseId(String clientId, String baseId, char separatorChar) {
+ if (clientId.equals(baseId)) {
+ return true;
+ }
+
+ // if clientId.startsWith(baseId + separatorChar)
+ if (clientId.startsWith(baseId) && (clientId.length() >
baseId.length())
+ && (clientId.charAt(baseId.length()) == separatorChar)) {
+ return true;
+ }
+
+ return false;
+ }
+
+ @Override
+ public boolean invokeOnComponent(FacesContext context, String clientId,
ContextCallback callback)
+ throws FacesException {
+
+ if ((null == context) || (null == clientId) || (null == callback)) {
+ throw new NullPointerException();
+ }
+
+ String baseId = super.getClientId(context);
+
+ if (!matchesBaseId(clientId, baseId,
UINamingContainer.getSeparatorChar(context))) {
+ return false;
+ }
+
+ boolean found = false;
+ Object oldRowKey = getRowKey();
+
+ // TODO - this does not seem right
+ captureOrigValue(context);
+
+ try {
+
+ // TODO - ?
+ // if (null != oldRowKey) {
+ setRowKey(context, null);
+
+ // }
+ if (clientId.equals(baseId)) {
+ callback.invokeContextCallback(context, this);
+ found = true;
+ } else {
+ Iterator<UIComponent> fixedChildrenItr = fixedChildren();
+
+ while (fixedChildrenItr.hasNext() && !found) {
+ UIComponent fixedChild = fixedChildrenItr.next();
+
+ found = fixedChild.invokeOnComponent(context, clientId, callback);
+ }
+ }
+
+ if (!found) {
+ Object newRowKey = null;
+
+ // Call for a child component - try to detect row key
+ // baseId.length() + 1 expression skips SEPARATOR_CHAR
+ String rowKeyString = extractKeySegment(context,
clientId.substring(baseId.length() + 1));
+
+ if (rowKeyString != null) {
+ Converter keyConverter = getRowKeyConverter();
+
+ if (null != keyConverter) {
+ try {
+ newRowKey = keyConverter.getAsObject(context, this,
rowKeyString);
+ } catch (ConverterException e) {
+
+ // TODO: LOG error
+ }
+ }
+ }
+
+ setRowKey(context, newRowKey);
+
+ if (isRowAvailable()) {
+ Iterator<UIComponent> dataChildrenItr = dataChildren();
+
+ while (dataChildrenItr.hasNext() && !found) {
+ UIComponent dataChild = dataChildrenItr.next();
+
+ found = dataChild.invokeOnComponent(context, clientId,
callback);
+ }
+ }
+ }
+ } catch (Exception e) {
+ throw new FacesException(e);
+ } finally {
+
+ // if (null != oldRowKey) {
+ try {
+ setRowKey(context, oldRowKey);
+ restoreOrigValue(context);
+ } catch (Exception e) {
+ LOG.error(e.getMessage(), e);
+ }
+
+ // }
+ }
+
+ return found;
+ }
+
// Performs pre-phase initialization before visiting children
// (if necessary).
- //TODO - do we need this?
+ // TODO - do we need this?
private void preVisitChildren(VisitContext visitContext) {
-// // If EXECUTE_LIFECYCLE hint is set, we need to do
-// // lifecycle-related initialization before visiting children
-// if (visitContext.getHints().contains(VisitHint.EXECUTE_LIFECYCLE)) {
-// FacesContext facesContext = visitContext.getFacesContext();
-// PhaseId phaseId = facesContext.getCurrentPhaseId();
+// // If EXECUTE_LIFECYCLE hint is set, we need to do
+// // lifecycle-related initialization before visiting children
+// if (visitContext.getHints().contains(VisitHint.EXECUTE_LIFECYCLE)) {
+// FacesContext facesContext = visitContext.getFacesContext();
+// PhaseId phaseId = facesContext.getCurrentPhaseId();
//
-// if (phaseId == PhaseId.APPLY_REQUEST_VALUES)
-// preDecode(facesContext);
-// else if (phaseId == PhaseId.PROCESS_VALIDATIONS)
-// preValidate(facesContext);
-// else if (phaseId == PhaseId.UPDATE_MODEL_VALUES)
-// preUpdate(facesContext);
-// else if (phaseId == PhaseId.RENDER_RESPONSE)
-// preEncode(facesContext);
-// }
+// if (phaseId == PhaseId.APPLY_REQUEST_VALUES)
+// preDecode(facesContext);
+// else if (phaseId == PhaseId.PROCESS_VALIDATIONS)
+// preValidate(facesContext);
+// else if (phaseId == PhaseId.UPDATE_MODEL_VALUES)
+// preUpdate(facesContext);
+// else if (phaseId == PhaseId.RENDER_RESPONSE)
+// preEncode(facesContext);
+// }
}
// Tests whether we need to visit our children as part of
@@ -1055,64 +1084,64 @@
private boolean doVisitChildren(VisitContext context) {
// Just need to check whether there are any ids under this
- // subtree. Make sure row index is cleared out since
+ // subtree. Make sure row index is cleared out since
// getSubtreeIdsToVisit() needs our row-less client id.
setRowKey(null);
+
Collection<String> idsToVisit = context.getSubtreeIdsToVisit(this);
- assert (idsToVisit != null);
+ assert idsToVisit != null;
+
// All ids or non-empty collection means we need to visit our children.
- return (!idsToVisit.isEmpty());
+ return !idsToVisit.isEmpty();
}
- private boolean visitFixedChildren(VisitContext visitContext,
- VisitCallback callback) {
-
- Iterator<UIComponent> fixedChildrenItr = fixedChildren();
- while (fixedChildrenItr.hasNext()) {
- UIComponent fixedChild = fixedChildrenItr.next();
- if (fixedChild.visitTree(visitContext, callback)) {
- return true;
- }
- }
-
- return false;
+ private boolean visitFixedChildren(VisitContext visitContext, VisitCallback callback)
{
+ Iterator<UIComponent> fixedChildrenItr = fixedChildren();
+
+ while (fixedChildrenItr.hasNext()) {
+ UIComponent fixedChild = fixedChildrenItr.next();
+
+ if (fixedChild.visitTree(visitContext, callback)) {
+ return true;
+ }
+ }
+
+ return false;
}
- private boolean visitDataChildren(final VisitContext visitContext,
- final VisitCallback callback) {
-
- FacesContext facesContext = visitContext.getFacesContext();
- final boolean[] singleBoolean = new boolean[]{false};
+ private boolean visitDataChildren(final VisitContext visitContext, final
VisitCallback callback) {
+ FacesContext facesContext = visitContext.getFacesContext();
+ final boolean[] singleBoolean = new boolean[] {false};
- this.walk(facesContext, new DataVisitor() {
-
- public DataVisitResult process(FacesContext context, Object rowKey, Object argument)
{
+ this.walk(facesContext, new DataVisitor() {
+ public DataVisitResult process(FacesContext context, Object rowKey, Object
argument) {
+ setRowKey(context, rowKey);
- setRowKey(context, rowKey);
-
- if (isRowAvailable()) {
- Iterator<UIComponent> dataChildrenItr = dataChildren();
- while (dataChildrenItr.hasNext()) {
- UIComponent dataChild = dataChildrenItr.next();
- if (dataChild.visitTree(visitContext, callback)) {
- singleBoolean[0] = true;
-
- return DataVisitResult.STOP;
- }
- }
- }
-
- return DataVisitResult.CONTINUE;
- }
- }, null);
+ if (isRowAvailable()) {
+ Iterator<UIComponent> dataChildrenItr = dataChildren();
- return singleBoolean[0];
+ while (dataChildrenItr.hasNext()) {
+ UIComponent dataChild = dataChildrenItr.next();
+
+ if (dataChild.visitTree(visitContext, callback)) {
+ singleBoolean[0] = true;
+
+ return DataVisitResult.STOP;
+ }
+ }
+ }
+
+ return DataVisitResult.CONTINUE;
+ }
+ }, null);
+
+ return singleBoolean[0];
}
-
+
@Override
- public boolean visitTree(VisitContext visitContext,
- VisitCallback callback) {
+ public boolean visitTree(VisitContext visitContext, VisitCallback callback) {
+
// First check to see whether we are visitable. If not
// short-circuit out of this subtree, though allow the
// visit to proceed through to other subtrees.
@@ -1127,6 +1156,7 @@
captureOrigValue(facesContext);
Object oldRowKey = getRowKey();
+
setRowKey(facesContext, null);
// Push ourselves to EL
@@ -1134,7 +1164,7 @@
try {
- // Visit ourselves. Note that we delegate to the
+ // Visit ourselves. Note that we delegate to the
// VisitContext to actually perform the visit.
VisitResult result = visitContext.invokeVisitCallback(this, callback);
@@ -1142,10 +1172,9 @@
if (result == VisitResult.COMPLETE) {
return true;
}
-
+
// Visit children, short-circuiting as necessary
if ((result == VisitResult.ACCEPT) && doVisitChildren(visitContext))
{
-
if (visitFixedChildren(visitContext, callback)) {
return true;
}
@@ -1154,30 +1183,58 @@
return true;
}
}
- }
- finally {
+ } finally {
+
// Clean up - pop EL and restore old row index
popComponentFromEL(facesContext);
+
try {
setRowKey(oldRowKey);
restoreOrigValue(facesContext);
} catch (Exception e) {
- // TODO: handle exception
- log.error(e.getMessage(), e);
- }
+
+ // TODO: handle exception
+ LOG.error(e.getMessage(), e);
+ }
}
// Return false to allow the visit to continue
return false;
}
-
- /**
- * @param context
- * @param substring
- * @return
- */
- protected String extractKeySegment(FacesContext context, String substring) {
- return null;
- }
+ /**
+ * @param context
+ * @param substring
+ * @return
+ */
+ protected String extractKeySegment(FacesContext context, String substring) {
+ return null;
+ }
+
+ /**
+ * Base class for visit data model at phases decode, validation and update
+ * model
+ *
+ * @author shura
+ *
+ */
+ protected abstract class ComponentVisitor implements DataVisitor {
+ public DataVisitResult process(FacesContext context, Object rowKey, Object
argument) {
+ setRowKey(context, rowKey);
+
+ if (isRowAvailable()) {
+ Iterator<UIComponent> childIterator = dataChildren();
+
+ while (childIterator.hasNext()) {
+ UIComponent component = childIterator.next();
+
+ processComponent(context, component, argument);
+ }
+ }
+
+ return DataVisitResult.CONTINUE;
+ }
+
+ public abstract void processComponent(FacesContext context, UIComponent c, Object
argument);
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/component/UIRangedNumberInput.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/UIRangedNumberInput.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/UIRangedNumberInput.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,87 +19,107 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component;
+import org.richfaces.component.util.MessageUtil;
+
import javax.faces.application.FacesMessage;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
-import org.richfaces.component.util.MessageUtil;
-
/**
* @author Nick - mailto:nbelaevski@exadel.com
* created 20.02.2007
- *
+ *
*/
public abstract class UIRangedNumberInput extends UIInput {
+ public abstract String getMaxValue();
- public abstract String getMaxValue();
public abstract void setMaxValue(String value);
public abstract String getMinValue();
+
public abstract void setMinValue(String value);
-
+
public abstract boolean isDisabled();
- public abstract void setDisabled(boolean disabled);
-
- public void decode(FacesContext arg0) {
- if (this.isDisabled())
- return;
- super.decode(arg0);
- }
-
+
+ public abstract void setDisabled(boolean disabled);
+
+ @Override
+ public void decode(FacesContext arg0) {
+ if (this.isDisabled()) {
+ return;
+ }
+
+ super.decode(arg0);
+ }
+
+ @Override
protected void validateValue(FacesContext context, Object newValue) {
- if (isValid() && !isEmpty(newValue)) {
- String label = MessageUtil.getLabel(context, this).toString();
-
- Double minValue = null, maxValue = null, value = null;
- try {
- minValue = convert(getMinValue());
- maxValue = convert(getMaxValue());
-
- //convert value and check if it is in range
- value = convert(newValue);
- } catch ( Exception e ) {
- setValid(false);
- FacesMessage mess = new FacesMessage(label + ": " +
e.getLocalizedMessage());
- mess.setSeverity(FacesMessage.SEVERITY_ERROR);
- context.addMessage(this.getClientId(context), mess);
- }
+ if (isValid() && !isEmpty(newValue)) {
+ String label = MessageUtil.getLabel(context, this).toString();
+ Double minValue = null;
+ Double maxValue = null;
+ Double value = null;
- if (value != null) {
- if (null == minValue || null == maxValue) {
- setValid(false);
- FacesMessage mess = new FacesMessage(label + ": conversation error,
maxValue or minValue is null!");
- mess.setSeverity(FacesMessage.SEVERITY_ERROR);
- context.addMessage(this.getClientId(context), mess);
- } else if (minValue.doubleValue() > value.doubleValue()) {
- setValid(false);
- FacesMessage mess = new FacesMessage(label + ": input value is less than
minimal value!");
- mess.setSeverity(FacesMessage.SEVERITY_ERROR);
- context.addMessage(this.getClientId(context), mess);
- } else if (maxValue.doubleValue() < value.doubleValue()) {
- setValid(false);
- FacesMessage mess = new FacesMessage(label + ": input value is more than
maximum value!");
- mess.setSeverity(FacesMessage.SEVERITY_ERROR);
- context.addMessage(this.getClientId(context), mess);
- }
- } else {
- setValid(false);
- FacesMessage mess = new FacesMessage(label + ": input value can't be
null!");
- mess.setSeverity(FacesMessage.SEVERITY_ERROR);
- context.addMessage(this.getClientId(context), mess);
- }
- }
+ try {
+ minValue = convert(getMinValue());
+ maxValue = convert(getMaxValue());
- super.validateValue(context, newValue);
+ // convert value and check if it is in range
+ value = convert(newValue);
+ } catch (Exception e) {
+ setValid(false);
+
+ FacesMessage mess = new FacesMessage(label + ": " +
e.getLocalizedMessage());
+
+ mess.setSeverity(FacesMessage.SEVERITY_ERROR);
+ context.addMessage(this.getClientId(context), mess);
+ }
+
+ if (value != null) {
+ if ((null == minValue) || (null == maxValue)) {
+ setValid(false);
+
+ FacesMessage mess = new FacesMessage(label + ": conversation
error, maxValue or minValue is null!");
+
+ mess.setSeverity(FacesMessage.SEVERITY_ERROR);
+ context.addMessage(this.getClientId(context), mess);
+ } else if (minValue.doubleValue() > value.doubleValue()) {
+ setValid(false);
+
+ FacesMessage mess = new FacesMessage(label + ": input value is
less than minimal value!");
+
+ mess.setSeverity(FacesMessage.SEVERITY_ERROR);
+ context.addMessage(this.getClientId(context), mess);
+ } else if (maxValue.doubleValue() < value.doubleValue()) {
+ setValid(false);
+
+ FacesMessage mess = new FacesMessage(label + ": input value is
more than maximum value!");
+
+ mess.setSeverity(FacesMessage.SEVERITY_ERROR);
+ context.addMessage(this.getClientId(context), mess);
+ }
+ } else {
+ setValid(false);
+
+ FacesMessage mess = new FacesMessage(label + ": input value
can't be null!");
+
+ mess.setSeverity(FacesMessage.SEVERITY_ERROR);
+ context.addMessage(this.getClientId(context), mess);
+ }
+ }
+
+ super.validateValue(context, newValue);
}
-
+
private Double convert(Object object) {
- if (object == null) {
- return null;
- }
- return new Double(object.toString());
+ if (object == null) {
+ return null;
+ }
+
+ return new Double(object.toString());
}
-
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/component/UISequence.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/UISequence.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/UISequence.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -18,11 +18,19 @@
* 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.component;
+import org.ajax4jsf.model.DataComponentState;
+import org.ajax4jsf.model.ExtendedDataModel;
+import org.ajax4jsf.model.RepeatState;
+import org.ajax4jsf.model.SequenceDataModel;
+
import java.sql.ResultSet;
+
import java.util.Collections;
import java.util.List;
@@ -35,27 +43,20 @@
import javax.faces.model.ResultDataModel;
import javax.faces.model.ResultSetDataModel;
import javax.faces.model.ScalarDataModel;
+
import javax.servlet.jsp.jstl.sql.Result;
-import org.ajax4jsf.model.DataComponentState;
-import org.ajax4jsf.model.ExtendedDataModel;
-import org.ajax4jsf.model.RepeatState;
-import org.ajax4jsf.model.SequenceDataModel;
-
/**
* @author Nick Belaevski
- *
+ *
*/
public class UISequence extends UIDataAdaptor {
+ protected enum PropertyKeys {first, rows, value}
- protected enum PropertyKeys {
- first, rows, value
- }
+ @SuppressWarnings("unchecked")
+ protected DataModel<?> createFacesModel(Object value) {
+ DataModel<?> model = null;
- @SuppressWarnings("unchecked")
- protected DataModel<?> createFacesModel(Object value) {
- DataModel<?> model = null;
-
if (value == null) {
model = new ListDataModel(Collections.EMPTY_LIST);
} else if (value instanceof DataModel) {
@@ -71,83 +72,84 @@
} else {
model = new ScalarDataModel(value);
}
-
- return model;
- }
- @Override
- protected ExtendedDataModel<?> createExtendedDataModel() {
+ return model;
+ }
+
+ @Override
+ protected ExtendedDataModel<?> createExtendedDataModel() {
ExtendedDataModel<?> model = null;
-
+
// Synthesize a DataModel around our current value if possible
Object value = getValue();
+
if (value instanceof ExtendedDataModel<?>) {
- model = (ExtendedDataModel<?>) value;
- } else {
- model = new SequenceDataModel(createFacesModel(value));
- }
-
- return model;
- }
-
- @Override
- protected String extractKeySegment(FacesContext context, String clientIdSubstring) {
- char separatorChar = UINamingContainer.getSeparatorChar(context);
-
- int separatorIndex = clientIdSubstring.indexOf(separatorChar);
- if (separatorIndex < 0) {
- return clientIdSubstring;
- } else {
- return clientIdSubstring.substring(0, separatorIndex);
- }
- }
-
- @Override
- protected DataComponentState createComponentState() {
- return new RepeatState() {
+ model = (ExtendedDataModel<?>) value;
+ } else {
+ model = new SequenceDataModel(createFacesModel(value));
+ }
- @Override
- public int getFirst() {
- return UISequence.this.getFirst();
- }
-
- @Override
- public int getRows() {
- return UISequence.this.getRows();
- }
- };
- }
+ return model;
+ }
- /* (non-Javadoc)
- * @see org.richfaces.component.UIDataAdaptor#getRowKeyConverter()
- */
- //TODO make this a property of model
- @Override
- public Converter getRowKeyConverter() {
- return getFacesContext().getApplication().createConverter(Integer.class);
- }
-
- public int getFirst() {
+ @Override
+ protected String extractKeySegment(FacesContext context, String clientIdSubstring) {
+ char separatorChar = UINamingContainer.getSeparatorChar(context);
+ int separatorIndex = clientIdSubstring.indexOf(separatorChar);
+
+ if (separatorIndex < 0) {
+ return clientIdSubstring;
+ } else {
+ return clientIdSubstring.substring(0, separatorIndex);
+ }
+ }
+
+ @Override
+ protected DataComponentState createComponentState() {
+ return new RepeatState() {
+ @Override
+ public int getFirst() {
+ return UISequence.this.getFirst();
+ }
+ @Override
+ public int getRows() {
+ return UISequence.this.getRows();
+ }
+ };
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.component.UIDataAdaptor#getRowKeyConverter()
+ */
+
+ // TODO make this a property of model
+ @Override
+ public Converter getRowKeyConverter() {
+ return getFacesContext().getApplication().createConverter(Integer.class);
+ }
+
+ public int getFirst() {
return (Integer) getStateHelper().eval(PropertyKeys.first, 0);
- }
-
- public void setFirst(int first) {
- getStateHelper().put(PropertyKeys.first, first);
- }
-
- public int getRows() {
+ }
+
+ public void setFirst(int first) {
+ getStateHelper().put(PropertyKeys.first, first);
+ }
+
+ public int getRows() {
return (Integer) getStateHelper().eval(PropertyKeys.rows, 0);
- }
+ }
- public void setRows(int rows) {
- getStateHelper().put(PropertyKeys.rows, rows);
- }
+ public void setRows(int rows) {
+ getStateHelper().put(PropertyKeys.rows, rows);
+ }
- public Object getValue() {
- return getStateHelper().eval(PropertyKeys.value);
- }
+ public Object getValue() {
+ return getStateHelper().eval(PropertyKeys.value);
+ }
- public void setValue(Object value) {
- getStateHelper().put(PropertyKeys.value, value);
- }
+ public void setValue(Object value) {
+ getStateHelper().put(PropertyKeys.value, value);
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/component/UISwitchablePanel.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/UISwitchablePanel.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/UISwitchablePanel.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,11 +19,18 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component;
+import org.ajax4jsf.renderkit.AjaxRendererUtils;
+
+import org.richfaces.event.SwitchablePanelSwitchEvent;
+
import java.util.Iterator;
import javax.el.ValueExpression;
+
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
@@ -33,192 +40,197 @@
import javax.faces.event.PhaseId;
import javax.faces.event.ValueChangeEvent;
-import org.ajax4jsf.renderkit.AjaxRendererUtils;
-import org.richfaces.event.SwitchablePanelSwitchEvent;
-
/**
* @author Nick Belaevski - nbelaevski(a)exadel.com
* created 23.01.2007
- *
+ *
*/
public abstract class UISwitchablePanel extends UIInput {
- /**
- * value for tab change method for - client-side tabs.
- */
- public static final String CLIENT_METHOD = "client";
- /**
- * value for tab change method - server-side tabs
- */
- public static final String SERVER_METHOD = "server";
- /**
- * value for tab change method - ajax tabs
- */
- public static final String AJAX_METHOD = "ajax";
+ /**
+ * value for tab change method - ajax tabs
+ */
+ public static final String AJAX_METHOD = "ajax";
- /**
- * default tab change method - server.
- */
- public static final String DEFAULT_METHOD = SERVER_METHOD;
+ /**
+ * value for tab change method for - client-side tabs.
+ */
+ public static final String CLIENT_METHOD = "client";
- private String switchType;
-
- public String getSwitchType() {
- if (this.switchType != null) {
- return switchType;
- }
+ /**
+ * value for tab change method - server-side tabs
+ */
+ public static final String SERVER_METHOD = "server";
- ValueExpression switchTypeExpression = getValueExpression("switchType");
- if (switchTypeExpression != null) {
- return (String)
switchTypeExpression.getValue(FacesContext.getCurrentInstance().getELContext());
- }
-
- return DEFAULT_METHOD;
- }
-
- public void setSwitchType(String switchType) {
- this.switchType = switchType;
- }
+ /**
+ * default tab change method - server.
+ */
+ public static final String DEFAULT_METHOD = SERVER_METHOD;
+ private String switchType;
- public Object convertSwitchValue(UIComponent component, Object object) {
- return object;
- }
-
- public void queueEvent(FacesEvent event) {
-
- if (event instanceof SwitchablePanelSwitchEvent &&
this.equals(event.getComponent())) {
- if (isImmediate()) {
- event.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
- } else {
- event.setPhaseId(PhaseId.UPDATE_MODEL_VALUES);
- }
- }
+ public String getSwitchType() {
+ if (this.switchType != null) {
+ return switchType;
+ }
- super.queueEvent(event);
- }
-
- public void broadcast(FacesEvent facesEvent) throws AbortProcessingException {
-
- if(facesEvent instanceof ActionEvent){
- //TODO invoke action listener or remove it
- if (isImmediate()) {
- FacesContext facesContext = FacesContext.getCurrentInstance();
- facesContext.renderResponse();
- }
- } //TODO else here
-
- if (facesEvent instanceof SwitchablePanelSwitchEvent) {
- if (isRendered()) {
- FacesContext facesContext = FacesContext.getCurrentInstance();
-
- SwitchablePanelSwitchEvent switchEvent = (SwitchablePanelSwitchEvent) facesEvent;
- Object newValue = convertSwitchValue(switchEvent.getEventSource(),
- switchEvent.getValue());
-
- Object oldValue = getValue();
- if ((oldValue == null && newValue != null) ||
- (oldValue != null && !oldValue.equals(newValue))) {
-
- queueEvent(new ValueChangeEvent(this, oldValue, newValue));
- }
-
- //TODO UIInput should update the model, not the switchable panel itself
- ValueExpression valueBinding = getValueExpression("value");
- if (valueBinding != null) {
- valueBinding.setValue(facesContext.getELContext(), newValue);
- setValue(null);
- setLocalValueSet(false);
- } else {
- setValue(newValue);
- }
-
- if (AjaxRendererUtils.isAjaxRequest(facesContext)
- /* && this.getSwitchType().equals(AJAX_METHOD)*/) { // RF-7292
-
- AjaxRendererUtils.addRegionByName(facesContext, this, this.getId());
- }
- }
- } else /* component should throw IllegalArgumentException for unknown events - RF-30 */
{
- super.broadcast(facesEvent);
- }
- }
-
- public void updateModel(FacesContext context) {
- //no processing here
- }
+ ValueExpression switchTypeExpression =
getValueExpression("switchType");
- protected Iterator<UIComponent> getSwitchedFacetsAndChildren() {
- return getFacetsAndChildren();
- }
-
- public void processDecodes(FacesContext context) {
- if (context == null) {
- throw new NullPointerException("FacesContext is null!");
- }
+ if (switchTypeExpression != null) {
+ return (String)
switchTypeExpression.getValue(FacesContext.getCurrentInstance().getELContext());
+ }
- if (!isRendered()) {
- return ;
- }
-
+ return DEFAULT_METHOD;
+ }
+
+ public void setSwitchType(String switchType) {
+ this.switchType = switchType;
+ }
+
+ public Object convertSwitchValue(UIComponent component, Object object) {
+ return object;
+ }
+
+ public void queueEvent(FacesEvent event) {
+ if ((event instanceof SwitchablePanelSwitchEvent) &&
this.equals(event.getComponent())) {
+ if (isImmediate()) {
+ event.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
+ } else {
+ event.setPhaseId(PhaseId.UPDATE_MODEL_VALUES);
+ }
+ }
+
+ super.queueEvent(event);
+ }
+
+ public void broadcast(FacesEvent facesEvent) throws AbortProcessingException {
+ if (facesEvent instanceof ActionEvent) {
+
+ // TODO invoke action listener or remove it
+ if (isImmediate()) {
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+
+ facesContext.renderResponse();
+ }
+ } // TODO else here
+
+ if (facesEvent instanceof SwitchablePanelSwitchEvent) {
+ if (isRendered()) {
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ SwitchablePanelSwitchEvent switchEvent = (SwitchablePanelSwitchEvent)
facesEvent;
+ Object newValue = convertSwitchValue(switchEvent.getEventSource(),
switchEvent.getValue());
+ Object oldValue = getValue();
+
+ if (((oldValue == null) && (newValue != null)) || ((oldValue !=
null) && !oldValue.equals(newValue))) {
+ queueEvent(new ValueChangeEvent(this, oldValue, newValue));
+ }
+
+ // TODO UIInput should update the model, not the switchable panel itself
+ ValueExpression valueBinding = getValueExpression("value");
+
+ if (valueBinding != null) {
+ valueBinding.setValue(facesContext.getELContext(), newValue);
+ setValue(null);
+ setLocalValueSet(false);
+ } else {
+ setValue(newValue);
+ }
+
+ if (AjaxRendererUtils.isAjaxRequest(facesContext)
+
+ /* && this.getSwitchType().equals(AJAX_METHOD) */
+ ) { // RF-7292
+ AjaxRendererUtils.addRegionByName(facesContext, this, this.getId());
+ }
+ }
+ } else /* component should throw IllegalArgumentException for unknown events -
RF-30 */ {
+ super.broadcast(facesEvent);
+ }
+ }
+
+ public void updateModel(FacesContext context) {
+
+ // no processing here
+ }
+
+ protected Iterator<UIComponent> getSwitchedFacetsAndChildren() {
+ return getFacetsAndChildren();
+ }
+
+ public void processDecodes(FacesContext context) {
+ if (context == null) {
+ throw new NullPointerException("FacesContext is null!");
+ }
+
+ if (!isRendered()) {
+ return;
+ }
+
// Process all facets and children of this component
Iterator<UIComponent> kids = getSwitchedFacetsAndChildren();
+
while (kids.hasNext()) {
UIComponent kid = kids.next();
+
kid.processDecodes(context);
}
try {
decode(context);
-
+
if (isImmediate()) {
- validate(context);
+ validate(context);
}
} catch (RuntimeException e) {
context.renderResponse();
+
throw e;
}
- }
+ }
- public void processUpdates(FacesContext context) {
- if (context == null) {
+ public void processUpdates(FacesContext context) {
+ if (context == null) {
throw new NullPointerException("FacesContext is null!");
}
-
+
if (!isRendered()) {
return;
}
-
+
Iterator<UIComponent> kids = getSwitchedFacetsAndChildren();
+
while (kids.hasNext()) {
UIComponent kid = kids.next();
+
kid.processUpdates(context);
}
-
+
try {
updateModel(context);
-
+
if (!isValid()) {
context.renderResponse();
}
-
} catch (RuntimeException e) {
context.renderResponse();
+
throw e;
}
- }
+ }
- public void processValidators(FacesContext context) {
- if (context == null) {
- throw new NullPointerException("FacesContext is null!");
- }
+ public void processValidators(FacesContext context) {
+ if (context == null) {
+ throw new NullPointerException("FacesContext is null!");
+ }
- if (!isRendered()) {
- return ;
- }
+ if (!isRendered()) {
+ return;
+ }
Iterator<UIComponent> kids = getSwitchedFacetsAndChildren();
+
while (kids.hasNext()) {
UIComponent kid = (UIComponent) kids.next();
+
kid.processValidators(context);
}
@@ -232,22 +244,24 @@
}
} catch (RuntimeException e) {
context.renderResponse();
+
throw e;
}
- }
-
- public Object saveState(FacesContext context) {
- Object[] states = new Object[2];
- states[0] = super.saveState(context);
- states[1] = switchType;
+ }
- return states;
- }
-
- public void restoreState(FacesContext context, Object state) {
- Object[] states = (Object[]) state;
- super.restoreState(context, states[0]);
-
- this.switchType = (String) states[1];
- }
+ public Object saveState(FacesContext context) {
+ Object[] states = new Object[2];
+
+ states[0] = super.saveState(context);
+ states[1] = switchType;
+
+ return states;
+ }
+
+ public void restoreState(FacesContext context, Object state) {
+ Object[] states = (Object[]) state;
+
+ super.restoreState(context, states[0]);
+ this.switchType = (String) states[1];
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/component/nsutils/NSUtils.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/nsutils/NSUtils.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/nsutils/NSUtils.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component.nsutils;
import java.io.IOException;
@@ -29,19 +31,16 @@
/**
* @author Nick Belaevski - nbelaevski(a)exadel.com
* created 21.12.2006
- *
+ *
*/
-public class NSUtils {
- public static final String XMLNS_PREFIX = "rich";
- public static final String XMLNS_VALUE = "xmlns:" + XMLNS_PREFIX;
- public static final String XMLNS_URI = "http://richfaces.ajax4jsf.org/rich";
+public final class NSUtils {
+ public static final String XMLNS_PREFIX = "rich";
+ public static final String XMLNS_URI =
"http://richfaces.ajax4jsf.org/rich";
+ public static final String XMLNS_VALUE = "xmlns:" + XMLNS_PREFIX;
- public static void writeNameSpace(FacesContext context, UIComponent component) throws
IOException {
- context
- .getResponseWriter()
- .writeAttribute(
- NSUtils.XMLNS_VALUE,
- NSUtils.XMLNS_URI,
- null);
- }
+ private NSUtils() {}
+
+ public static void writeNameSpace(FacesContext context, UIComponent component) throws
IOException {
+ context.getResponseWriter().writeAttribute(NSUtils.XMLNS_VALUE,
NSUtils.XMLNS_URI, null);
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/component/nsutils/package-info.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/nsutils/package-info.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/nsutils/package-info.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -1,3 +1,4 @@
+
/**
* Custom XML namespace utility classes
*/
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/component/package-info.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/package-info.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/package-info.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -1,3 +1,4 @@
+
/**
* Base RichFaces component classes
*/
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/AbstractMessageUtil.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/AbstractMessageUtil.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/AbstractMessageUtil.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,9 +19,12 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component.util;
import java.text.MessageFormat;
+
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
@@ -36,89 +39,93 @@
* @author Nick Belaevski
* @since 3.2.2
*/
+public final class AbstractMessageUtil {
+ private AbstractMessageUtil() {}
-public class AbstractMessageUtil {
- private static final ResourceBundle getResourceBundle(String baseName, Locale locale,
ClassLoader loader) {
- if (loader != null) {
- return ResourceBundle.getBundle(baseName, locale, loader);
- } else {
- return ResourceBundle.getBundle(baseName, locale);
- }
- }
-
- private static final FacesMessage getMessage(FacesContext context, String messageId,
- Object[] parameters, Locale locale, String baseBundleName) {
- String summary = null;
- String detail = null;
-
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
-
- if (context != null) {
- Application application = context.getApplication();
- if (application != null) {
- String messageBundleName = application.getMessageBundle();
-
- if (messageBundleName != null) {
- ResourceBundle bundle = getResourceBundle(messageBundleName, locale, loader);
- if (bundle != null) {
- try {
- summary = bundle.getString(messageId);
- detail = bundle.getString(messageId + "_detail");
- } catch (MissingResourceException e) {
- //do nothing
- }
- }
- }
- }
- }
+ private static ResourceBundle getResourceBundle(String baseName, Locale locale,
ClassLoader loader) {
+ if (loader != null) {
+ return ResourceBundle.getBundle(baseName, locale, loader);
+ } else {
+ return ResourceBundle.getBundle(baseName, locale);
+ }
+ }
- if (summary == null) {
- ResourceBundle bundle = getResourceBundle(baseBundleName, locale, loader);
- try {
- summary = bundle.getString(messageId);
-
- if (summary == null) {
- return null;
- }
+ private static FacesMessage getMessage(FacesContext context, String messageId,
Object[] parameters, Locale locale,
+ String baseBundleName) {
+ String summary = null;
+ String detail = null;
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
- detail = bundle.getString(messageId + "_detail");
- } catch (MissingResourceException e) {
- //do nothing
- }
- }
-
- String formattedSummary = MessageFormat.format(summary, parameters);
- String formattedDetail = null;
- if (detail != null) {
- formattedDetail = MessageFormat.format(detail, parameters);
- }
-
- return new FacesMessage(formattedSummary, formattedDetail);
- }
-
- protected static final FacesMessage getMessage(FacesContext context, String messageId,
- Object[] parameters, String baseBundleName) {
-
- Locale locale;
- FacesMessage result = null;
-
- if (context != null) {
- UIViewRoot viewRoot = context.getViewRoot();
- if (viewRoot != null) {
- locale = viewRoot.getLocale();
-
- if (locale != null) {
- result = getMessage(context, messageId, parameters, locale, baseBundleName);
- }
- }
- }
-
- if (result == null) {
- locale = Locale.getDefault();
- result = getMessage(context, messageId, parameters, locale, baseBundleName);
- }
+ if (context != null) {
+ Application application = context.getApplication();
- return result;
- }
-
+ if (application != null) {
+ String messageBundleName = application.getMessageBundle();
+
+ if (messageBundleName != null) {
+ ResourceBundle bundle = getResourceBundle(messageBundleName, locale,
loader);
+
+ if (bundle != null) {
+ try {
+ summary = bundle.getString(messageId);
+ detail = bundle.getString(messageId + "_detail");
+ } catch (MissingResourceException e) {
+
+ // do nothing
+ }
+ }
+ }
+ }
+ }
+
+ if (summary == null) {
+ ResourceBundle bundle = getResourceBundle(baseBundleName, locale, loader);
+
+ try {
+ summary = bundle.getString(messageId);
+
+ if (summary == null) {
+ return null;
+ }
+
+ detail = bundle.getString(messageId + "_detail");
+ } catch (MissingResourceException e) {
+
+ // do nothing
+ }
+ }
+
+ String formattedSummary = MessageFormat.format(summary, parameters);
+ String formattedDetail = null;
+
+ if (detail != null) {
+ formattedDetail = MessageFormat.format(detail, parameters);
+ }
+
+ return new FacesMessage(formattedSummary, formattedDetail);
+ }
+
+ static FacesMessage getMessage(FacesContext context, String messageId, Object[]
parameters, String baseBundleName) {
+ Locale locale;
+ FacesMessage result = null;
+
+ if (context != null) {
+ UIViewRoot viewRoot = context.getViewRoot();
+
+ if (viewRoot != null) {
+ locale = viewRoot.getLocale();
+
+ if (locale != null) {
+ result = getMessage(context, messageId, parameters, locale,
baseBundleName);
+ }
+ }
+ }
+
+ if (result == null) {
+ locale = Locale.getDefault();
+ result = getMessage(context, messageId, parameters, locale, baseBundleName);
+ }
+
+ return result;
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/ComponentMessageUtil.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/ComponentMessageUtil.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/ComponentMessageUtil.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component.util;
import javax.faces.application.FacesMessage;
@@ -28,14 +30,12 @@
* @author Nick Belaevski
* @since 3.2.2
*/
+public final class ComponentMessageUtil {
+ public static final String MESSAGE_BUNDLE_NAME =
"org.richfaces.component.messages";
-public class ComponentMessageUtil extends AbstractMessageUtil {
+ private ComponentMessageUtil() {}
- public static final String MESSAGE_BUNDLE_NAME =
"org.richfaces.component.messages";
-
- public static final FacesMessage getMessage(FacesContext context, String messageId,
- Object[] parameters) {
-
- return AbstractMessageUtil.getMessage(context, messageId, parameters,
MESSAGE_BUNDLE_NAME);
- }
+ public static FacesMessage getMessage(FacesContext context, String messageId,
Object[] parameters) {
+ return AbstractMessageUtil.getMessage(context, messageId, parameters,
MESSAGE_BUNDLE_NAME);
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/ComponentUtil.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/ComponentUtil.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/ComponentUtil.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -18,6 +18,9 @@
* 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.component.util;
import java.util.Collection;
@@ -29,48 +32,54 @@
* created 20.07.2007
*
*/
-public class ComponentUtil {
- public static String[] asArray(Object object) {
- if (object == null) {
- return null;
- }
-
- Class componentType = object.getClass().getComponentType();
-
- if (String.class.equals(componentType)) {
- return (String[]) object;
- } else if (componentType != null) {
- Object[] objects = (Object[]) object;
- String[] result = new String[objects.length];
- for (int i = 0; i < objects.length; i++) {
- Object o = objects[i];
- if (o == null) {
- continue;
- }
-
- result[i] = o.toString();
- }
-
- return result;
- } else if (object instanceof Collection) {
- Collection collection = (Collection) object;
- String[] result = new String[collection.size()];
- Iterator iterator = collection.iterator();
-
- for (int i = 0; i < result.length; i++) {
- Object next = iterator.next();
- if (next == null) {
- continue;
- }
-
- result[i] = next.toString();
- }
-
- return result;
- } else {
- String string = object.toString().trim();
- String[] split = string.split("\\s*,\\s*");
- return split;
- }
- }
+public final class ComponentUtil {
+ private ComponentUtil() {}
+
+ public static String[] asArray(Object object) {
+ if (object == null) {
+ return null;
+ }
+
+ Class componentType = object.getClass().getComponentType();
+
+ if (String.class.equals(componentType)) {
+ return (String[]) object;
+ } else if (componentType != null) {
+ Object[] objects = (Object[]) object;
+ String[] result = new String[objects.length];
+
+ for (int i = 0; i < objects.length; i++) {
+ Object o = objects[i];
+
+ if (o == null) {
+ continue;
+ }
+
+ result[i] = o.toString();
+ }
+
+ return result;
+ } else if (object instanceof Collection) {
+ Collection collection = (Collection) object;
+ String[] result = new String[collection.size()];
+ Iterator iterator = collection.iterator();
+
+ for (int i = 0; i < result.length; i++) {
+ Object next = iterator.next();
+
+ if (next == null) {
+ continue;
+ }
+
+ result[i] = next.toString();
+ }
+
+ return result;
+ } else {
+ String string = object.toString().trim();
+ String[] split = string.split("\\s*,\\s*");
+
+ return split;
+ }
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/FormUtil.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/FormUtil.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/FormUtil.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,31 +19,38 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component.util;
+import org.ajax4jsf.renderkit.RendererUtils;
+
+import org.richfaces.component.EnclosingFormRequiredException;
+
import javax.faces.component.UIComponent;
import javax.faces.component.UIForm;
import javax.faces.context.FacesContext;
-import org.ajax4jsf.renderkit.RendererUtils;
-
-import org.richfaces.component.EnclosingFormRequiredException;
-
/**
* @author Filip Antonov - mailto:fantonov@exadel.com
* created 08.02.2007
- *
+ *
*/
-public class FormUtil {
-
- public static void throwEnclFormReqExceptionIfNeed(FacesContext context, UIComponent
component) throws EnclosingFormRequiredException {
- UIForm form= RendererUtils.getInstance().getNestingForm(context, component);
- //TODO nick -> nick - switchType checking can be harmful here
- String switchType = (String) component.getAttributes().get("switchType");
- boolean isSwitchTypeClient = switchType == null ? false :
switchType.equalsIgnoreCase("client") ;
- if (form == null && !isSwitchTypeClient){
- throw new EnclosingFormRequiredException(component.getClass().toString()+"
(id=\"" + component.getId() + "\") did not find parent form.");
- }
- }
+public final class FormUtil {
+ private FormUtil() {}
+ public static void throwEnclFormReqExceptionIfNeed(FacesContext context, UIComponent
component)
+ throws EnclosingFormRequiredException {
+
+ UIForm form = RendererUtils.getInstance().getNestingForm(context, component);
+
+ // TODO nick -> nick - switchType checking can be harmful here
+ String switchType = (String)
component.getAttributes().get("switchType");
+ boolean isSwitchTypeClient = (switchType == null) ? false :
switchType.equalsIgnoreCase("client");
+
+ if ((form == null) && !isSwitchTypeClient) {
+ throw new EnclosingFormRequiredException(component.getClass().toString() +
" (id=\"" + component.getId()
+ + "\") did not find parent form.");
+ }
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/HtmlUtil.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/HtmlUtil.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/HtmlUtil.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,8 +19,13 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component.util;
+import org.ajax4jsf.renderkit.RendererUtils;
+import org.ajax4jsf.util.HtmlDimensions;
+
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -28,131 +33,128 @@
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
-import org.ajax4jsf.renderkit.RendererUtils;
-import org.ajax4jsf.util.HtmlDimensions;
-
/**
* @author Nick Belaevski - nbelaevski(a)exadel.com created 09.02.2007
- *
+ *
*/
-public class HtmlUtil {
-
+public final class HtmlUtil {
+ public static final Pattern ID_SELECTOR_PATTERN =
+ Pattern.compile(
+
"#((?:-[A-Za-z_-]|[A-Za-z_]|\\\\[^A-F0-9U]|\\\\[A-F0-9]{1,6}\\s?|\\\\U[0-9A-F]{2}(?:A[1-9A-F]|[B-F][0-9A-F]))(?:\\\\[A-F0-9]{1,6}\\s?|[A-Za-z0-9_-]|\\\\:)*)");
+ private static final String ORG_AJAX4JSF = "org.ajax4jsf.";
private static final String ORG_RICHFACES = "org.richfaces.";
- private static final String ORG_AJAX4JSF = "org.ajax4jsf.";
-
+ private HtmlUtil() {}
+
public static String qualifySize(String sizeDeclaration) {
- String trimmedValue = sizeDeclaration.trim();
- if (trimmedValue.length() != 0) {
- char lastChar = trimmedValue.charAt(trimmedValue.length() - 1);
- if (Character.isDigit(lastChar)) {
- return sizeDeclaration + "px";
- }
- }
+ String trimmedValue = sizeDeclaration.trim();
- return sizeDeclaration;
- }
+ if (trimmedValue.length() != 0) {
+ char lastChar = trimmedValue.charAt(trimmedValue.length() - 1);
- public static String addToSize(String declaration, String delta) {
- Double doubleDelta = HtmlDimensions.decode(delta);
- Double decoded = HtmlDimensions.decode(declaration);
+ if (Character.isDigit(lastChar)) {
+ return sizeDeclaration + "px";
+ }
+ }
- return HtmlDimensions.formatPx(new Double(decoded.doubleValue()
- + doubleDelta.doubleValue()));
- }
+ return sizeDeclaration;
+ }
- public static final Pattern idSelectorPattern = Pattern
- .compile("#((?:-[A-Za-z_-]|[A-Za-z_]|\\\\[^A-F0-9U]|\\\\[A-F0-9]{1,6}\\s?|\\\\U[0-9A-F]{2}(?:A[1-9A-F]|[B-F][0-9A-F]))(?:\\\\[A-F0-9]{1,6}\\s?|[A-Za-z0-9_-]|\\\\:)*)");
+ public static String addToSize(String declaration, String delta) {
+ Double doubleDelta = HtmlDimensions.decode(delta);
+ Double decoded = HtmlDimensions.decode(declaration);
- public static String expandIdSelector(String selector,
- UIComponent component, FacesContext context) {
- Matcher matcher = idSelectorPattern.matcher(selector);
- StringBuffer sb = new StringBuffer();
+ return HtmlDimensions.formatPx(new Double(decoded.doubleValue() +
doubleDelta.doubleValue()));
+ }
- while (matcher.find()) {
- // make new id selector here using matcher.group(1)
- String unescaped = matcher.group(1).replaceAll("\\\\:", ":");
- UIComponent target = RendererUtils.getInstance().findComponentFor(context, component,
unescaped);
+ public static String expandIdSelector(String selector, UIComponent component,
FacesContext context) {
+ Matcher matcher = ID_SELECTOR_PATTERN.matcher(selector);
+ StringBuffer sb = new StringBuffer();
- if (target != null) {
- matcher.appendReplacement(sb, "#"
- + target.getClientId(context).replaceAll(":",
- "\\\\\\\\:"));
- }
- }
- matcher.appendTail(sb);
- return sb.toString();
- }
-
- public static String idsToIdSelector(String ids) {
- StringBuffer buffer = new StringBuffer();
- if (ids != null) {
- String[] idString = ids.split("\\s*,\\s*");
-
- for(int i = 0; i < idString.length; i++) {
- if (i > 0) {
- buffer.append(",");
- }
- idString[i] = idString[i].replaceAll(":", "\\\\:");
- buffer
- .append("#")
- .append(idString[i]);
- }
- }
- return buffer.toString();
- }
-
- public static boolean shouldWriteId(UIComponent component) {
- String rendererType = component.getRendererType();
+ while (matcher.find()) {
- String id = component.getId();
- if (id != null && !id.startsWith(UIViewRoot.UNIQUE_ID_PREFIX)) {
-
- return true;
- }
+ // make new id selector here using matcher.group(1)
+ String unescaped = matcher.group(1).replaceAll("\\\\:",
":");
+ UIComponent target = RendererUtils.getInstance().findComponentFor(context,
component, unescaped);
- if (rendererType != null &&
- (rendererType.startsWith(ORG_AJAX4JSF) || rendererType.startsWith(ORG_RICHFACES)))
{
-
- return true;
- }
-
- return false;
- }
-
- private static boolean isEmpty(String s) {
- return s == null || s.length() == 0;
- }
+ if (target != null) {
+ matcher.appendReplacement(sb, "#" +
target.getClientId(context).replaceAll(":", "\\\\\\\\:"));
+ }
+ }
- public static String concatClasses(String... classes) {
- StringBuilder result = new StringBuilder();
-
- for (String className : classes) {
- if (!isEmpty(className)) {
- if (result.length() != 0) {
- result.append(' ');
- }
-
- result.append(className.trim());
- }
- }
-
- return result.toString();
- }
+ matcher.appendTail(sb);
- public static String concatStyles(String... styles) {
- StringBuilder result = new StringBuilder();
+ return sb.toString();
+ }
- for (String style : styles) {
- if (!isEmpty(style)) {
- if (result.length() != 0) {
- result.append(';');
- }
-
- result.append(style.trim());
- }
- }
-
- return result.toString();
- }
+ public static String idsToIdSelector(String ids) {
+ StringBuffer buffer = new StringBuffer();
+
+ if (ids != null) {
+ String[] idString = ids.split("\\s*,\\s*");
+
+ for (int i = 0; i < idString.length; i++) {
+ if (i > 0) {
+ buffer.append(",");
+ }
+
+ idString[i] = idString[i].replaceAll(":", "\\\\:");
+ buffer.append("#").append(idString[i]);
+ }
+ }
+
+ return buffer.toString();
+ }
+
+ public static boolean shouldWriteId(UIComponent component) {
+ String rendererType = component.getRendererType();
+ String id = component.getId();
+
+ if ((id != null) && !id.startsWith(UIViewRoot.UNIQUE_ID_PREFIX)) {
+ return true;
+ }
+
+ if ((rendererType != null)
+ && (rendererType.startsWith(ORG_AJAX4JSF) ||
rendererType.startsWith(ORG_RICHFACES))) {
+ return true;
+ }
+
+ return false;
+ }
+
+ private static boolean isEmpty(String s) {
+ return (s == null) || (s.length() == 0);
+ }
+
+ public static String concatClasses(String... classes) {
+ StringBuilder result = new StringBuilder();
+
+ for (String className : classes) {
+ if (!isEmpty(className)) {
+ if (result.length() != 0) {
+ result.append(' ');
+ }
+
+ result.append(className.trim());
+ }
+ }
+
+ return result.toString();
+ }
+
+ public static String concatStyles(String... styles) {
+ StringBuilder result = new StringBuilder();
+
+ for (String style : styles) {
+ if (!isEmpty(style)) {
+ if (result.length() != 0) {
+ result.append(';');
+ }
+
+ result.append(style.trim());
+ }
+ }
+
+ return result.toString();
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/MessageUtil.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/MessageUtil.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/MessageUtil.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component.util;
import javax.faces.application.Application;
@@ -30,46 +32,49 @@
/**
* @author Nick - mailto:nbelaevski@exadel.com
* created 06.02.2007
- *
+ *
*/
-public class MessageUtil extends AbstractMessageUtil {
- private static final boolean IS_12;
-
- static {
- boolean is12;
- try {
- Application.class.getMethod("getExpressionFactory", null);
- is12 = true;
- } catch (NoSuchMethodException e) {
- is12 = false;
- }
-
- IS_12 = is12;
- }
-
-
- public static Object getLabel(FacesContext context, UIComponent component) {
- Object o = null;
- if (IS_12) {
- o = component.getAttributes().get("label");
- if (o == null || (o instanceof String && ((String) o).length() == 0)) {
- ValueBinding ex = component.getValueBinding("label");
- if (ex != null) {
- o = ex.getValue(context);
- }
- }
- }
+public final class MessageUtil {
+ private static final boolean IS_12;
- if (o == null) {
- o = component.getClientId(context);
- }
-
- return o;
- }
-
- public static final FacesMessage getMessage(FacesContext context, String messageId,
- Object[] parameters) {
+ static {
+ boolean is12;
- return AbstractMessageUtil.getMessage(context, messageId, parameters,
FacesMessage.FACES_MESSAGES);
- }
+ try {
+ Application.class.getMethod("getExpressionFactory", null);
+ is12 = true;
+ } catch (NoSuchMethodException e) {
+ is12 = false;
+ }
+
+ IS_12 = is12;
+ }
+
+ private MessageUtil() {}
+
+ public static Object getLabel(FacesContext context, UIComponent component) {
+ Object o = null;
+
+ if (IS_12) {
+ o = component.getAttributes().get("label");
+
+ if ((o == null) || ((o instanceof String) && ((String) o).length() ==
0)) {
+ ValueBinding ex = component.getValueBinding("label");
+
+ if (ex != null) {
+ o = ex.getValue(context);
+ }
+ }
+ }
+
+ if (o == null) {
+ o = component.getClientId(context);
+ }
+
+ return o;
+ }
+
+ public static FacesMessage getMessage(FacesContext context, String messageId,
Object[] parameters) {
+ return AbstractMessageUtil.getMessage(context, messageId, parameters,
FacesMessage.FACES_MESSAGES);
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/ViewUtil.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/ViewUtil.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/ViewUtil.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component.util;
import javax.faces.context.FacesContext;
@@ -26,19 +28,28 @@
/**
* @author Nick Belaevski - nbelaevski(a)exadel.com
* created 19.02.2007
- *
+ *
*/
-public class ViewUtil {
-
- public static String getResourceURL(String url) {
- if (null == url) return null;
- return ViewUtil.getResourceURL(url, FacesContext.getCurrentInstance());
- }
-
- public static String getResourceURL(String url, FacesContext context) {
- if (null == url) return null;
- String value = url;
- value = context.getApplication().getViewHandler().getResourceURL(context, value);
- return (context.getExternalContext().encodeResourceURL(value));
- }
+public final class ViewUtil {
+ private ViewUtil() {}
+
+ public static String getResourceURL(String url) {
+ if (null == url) {
+ return null;
+ }
+
+ return ViewUtil.getResourceURL(url, FacesContext.getCurrentInstance());
+ }
+
+ public static String getResourceURL(String url, FacesContext context) {
+ if (null == url) {
+ return null;
+ }
+
+ String value = url;
+
+ value = context.getApplication().getViewHandler().getResourceURL(context,
value);
+
+ return context.getExternalContext().encodeResourceURL(value);
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/package-info.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/package-info.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/component/util/package-info.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -1,3 +1,4 @@
+
/**
* Common utility classes
*/
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/context/AttributesContext.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/context/AttributesContext.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/context/AttributesContext.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -4,19 +4,17 @@
import java.util.Map;
public class AttributesContext {
+ private Map<String, Object> attributesMap = new HashMap<String,
Object>();
- private Map<String, Object> attributesMap = new HashMap<String, Object>();
+ public Object getAttribute(String name) {
+ return attributesMap.get(name);
+ }
- public Object getAttribute(String name) {
- return attributesMap.get(name);
- }
-
- public Object setAttribute(String name, Object value) {
- if (value != null) {
- return attributesMap.put(name, value);
- } else {
- return attributesMap.remove(name);
- }
- }
-
+ public Object setAttribute(String name, Object value) {
+ if (value != null) {
+ return attributesMap.put(name, value);
+ } else {
+ return attributesMap.remove(name);
+ }
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/context/ComponentCallback.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/context/ComponentCallback.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/context/ComponentCallback.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,67 +19,65 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.context;
import org.ajax4jsf.component.AjaxClientBehavior;
import org.ajax4jsf.renderkit.AjaxRendererUtils;
import org.ajax4jsf.renderkit.RendererUtils;
-import javax.faces.component.visit.VisitCallback;
-import javax.faces.component.visit.VisitResult;
-import javax.faces.component.visit.VisitContext;
-import javax.faces.component.UIComponent;
-import javax.faces.component.behavior.ClientBehaviorHolder;
-import javax.faces.component.behavior.ClientBehavior;
-import javax.faces.context.FacesContext;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
+import javax.faces.component.UIComponent;
+import javax.faces.component.behavior.ClientBehavior;
+import javax.faces.component.behavior.ClientBehaviorHolder;
+import javax.faces.component.visit.VisitCallback;
+import javax.faces.component.visit.VisitContext;
+import javax.faces.component.visit.VisitResult;
+import javax.faces.context.FacesContext;
+
/**
* User: akolonitsky
* Date: Oct 13, 2009
*/
abstract class ComponentCallback implements VisitCallback {
-
+ private Collection<String> componentIds = new LinkedHashSet<String>();
private final String behaviorEvent;
-
private boolean handleAll;
-
private boolean handleNone;
- private Collection<String> componentIds = new LinkedHashSet<String>();
-
- ComponentCallback(String behaviorEvent, boolean handleNone,
- boolean handleAll) {
+ ComponentCallback(String behaviorEvent, boolean handleNone, boolean handleAll) {
super();
this.behaviorEvent = behaviorEvent;
this.handleNone = handleNone;
this.handleAll = handleAll;
}
- protected void addDefaultComponents(Collection<String> ids) {
+ protected void addDefaultComponents(Collection<String> ids) {}
- }
-
private AjaxClientBehavior findBehavior(UIComponent target) {
- if (behaviorEvent == null || !(target instanceof ClientBehaviorHolder)) {
+ if ((behaviorEvent == null) || !(target instanceof ClientBehaviorHolder)) {
return null;
}
ClientBehaviorHolder behaviorHolder = (ClientBehaviorHolder) target;
List<ClientBehavior> behaviors =
behaviorHolder.getClientBehaviors().get(behaviorEvent);
+
if (behaviors == null) {
return null;
}
for (ClientBehavior behavior : behaviors) {
- if (behavior instanceof AjaxClientBehavior && !((AjaxClientBehavior)
behavior).isDisabled()) {
- //TODO need more reliable algorithm
+ if ((behavior instanceof AjaxClientBehavior) &&
!((AjaxClientBehavior) behavior).isDisabled()) {
+
+ // TODO need more reliable algorithm
return (AjaxClientBehavior) behavior;
}
}
-
+
return null;
}
@@ -89,6 +87,7 @@
protected void doVisit(FacesContext context, UIComponent target, AjaxClientBehavior
behavior) {
Object attributeObject;
+
if (behavior == null) {
attributeObject = getAttributeValue(target);
} else {
@@ -96,13 +95,15 @@
}
Collection<String> attributeIds =
AjaxRendererUtils.asSet(attributeObject);
- if (attributeIds == null || attributeIds.isEmpty()) {
+
+ if ((attributeIds == null) || attributeIds.isEmpty()) {
return;
}
-
+
if (attributeIds.contains(AjaxRendererUtils.ALL)) {
if (!AjaxRendererUtils.ALL_SET.equals(attributeIds)) {
- //TODO: log
+
+ // TODO: log
}
handleAll = true;
@@ -111,22 +112,23 @@
if (attributeIds.contains(AjaxRendererUtils.NONE)) {
if (!AjaxRendererUtils.NONE_SET.equals(attributeIds)) {
- //TODO: log
+
+ // TODO: log
}
handleNone = true;
} else {
- //asSet() returns copy of original set and we're free to modify it
+
+ // asSet() returns copy of original set and we're free to modify it
addDefaultComponents(attributeIds);
-
- componentIds.addAll(RendererUtils.getInstance().findComponentsFor(
- context, target, attributeIds));
+
componentIds.addAll(RendererUtils.getInstance().findComponentsFor(context, target,
attributeIds));
}
}
}
public final VisitResult visit(VisitContext visitContext, UIComponent target) {
AjaxClientBehavior ajaxBehavior = null;
+
if (behaviorEvent != null) {
ajaxBehavior = findBehavior(target);
}
@@ -148,5 +150,3 @@
return handleNone;
}
}
-
-
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/context/ContextProvider.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/context/ContextProvider.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/context/ContextProvider.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,17 +19,19 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.context;
-import javax.faces.context.FacesContext;
import java.util.Map;
+import javax.faces.context.FacesContext;
+
/**
* @author akolonitsky
* @since Oct 13, 2009
*/
public abstract class ContextProvider {
-
protected final String singletonContextAttributeName;
protected ContextProvider(String attributeSuffixName) {
@@ -44,6 +46,7 @@
protected AttributesContext createAndStoreContext(FacesContext context) {
AttributesContext instance = createContext();
+
getContextMap(context).put(singletonContextAttributeName, instance);
return instance;
@@ -51,8 +54,8 @@
public AttributesContext get(FacesContext context) {
Map<? super String, Object> contextMap = getContextMap(context);
+ AttributesContext instance = (AttributesContext)
contextMap.get(singletonContextAttributeName);
- AttributesContext instance = (AttributesContext)
contextMap.get(singletonContextAttributeName);
if (instance == null) {
instance = createAndStoreContext(context);
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/context/ExecuteComponentCallback.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/context/ExecuteComponentCallback.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/context/ExecuteComponentCallback.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,20 +19,22 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.context;
+import org.ajax4jsf.component.AjaxClientBehavior;
import org.ajax4jsf.renderkit.AjaxRendererUtils;
-import org.ajax4jsf.component.AjaxClientBehavior;
-import javax.faces.component.UIComponent;
import java.util.Collection;
+import javax.faces.component.UIComponent;
+
/**
* @author akolonitsky
* @since Oct 13, 2009
*/
class ExecuteComponentCallback extends ComponentCallback {
-
ExecuteComponentCallback(String behaviorEvent) {
super(behaviorEvent, false, true);
}
@@ -53,5 +55,3 @@
return behavior.getExecute();
}
}
-
-
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/context/PartialViewContextAjaxOutputTracker.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/context/PartialViewContextAjaxOutputTracker.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/context/PartialViewContextAjaxOutputTracker.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,8 +19,12 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.context;
+import org.ajax4jsf.component.AjaxOutput;
+
import java.util.ArrayList;
import java.util.Collection;
@@ -29,41 +33,42 @@
import javax.faces.event.SystemEvent;
import javax.faces.event.SystemEventListener;
-import org.ajax4jsf.component.AjaxOutput;
-
/**
* @author Nick Belaevski
- *
+ *
*/
public class PartialViewContextAjaxOutputTracker implements SystemEventListener {
-
- private static final String AJAX_OUTPUT_COMPONENTS_SET_ATTRIBUTE =
- PartialViewContextAjaxOutputTracker.class + ":AjaxOutputComponentsSet";
-
- static Collection<AjaxOutput> getAjaxOutputComponentsSet(FacesContext context) {
- AttributesContext attributes = SingletonsContext.FACES_CONTEXT.get(context);
- Collection<AjaxOutput> components = (Collection<AjaxOutput>)
attributes.getAttribute(AJAX_OUTPUT_COMPONENTS_SET_ATTRIBUTE);
- if (components == null) {
- components = new ArrayList<AjaxOutput>();
- attributes.setAttribute(AJAX_OUTPUT_COMPONENTS_SET_ATTRIBUTE, components);
- }
-
- return components;
- }
+ private static final String AJAX_OUTPUT_COMPONENTS_SET_ATTRIBUTE =
PartialViewContextAjaxOutputTracker.class
+ +
":AjaxOutputComponentsSet";
- /* (non-Javadoc)
- * @see javax.faces.event.SystemEventListener#isListenerForSource(java.lang.Object)
- */
- public boolean isListenerForSource(Object source) {
- return source instanceof AjaxOutput;
- }
+ static Collection<AjaxOutput> getAjaxOutputComponentsSet(FacesContext context)
{
+ AttributesContext attributes = SingletonsContext.FACES_CONTEXT.get(context);
+ Collection<AjaxOutput> components =
+ (Collection<AjaxOutput>)
attributes.getAttribute(AJAX_OUTPUT_COMPONENTS_SET_ATTRIBUTE);
- /* (non-Javadoc)
- * @see
javax.faces.event.SystemEventListener#processEvent(javax.faces.event.SystemEvent)
- */
- public void processEvent(SystemEvent event) throws AbortProcessingException {
- FacesContext facesContext = FacesContext.getCurrentInstance();
- getAjaxOutputComponentsSet(facesContext).add((AjaxOutput) event.getSource());
- }
+ if (components == null) {
+ components = new ArrayList<AjaxOutput>();
+ attributes.setAttribute(AJAX_OUTPUT_COMPONENTS_SET_ATTRIBUTE, components);
+ }
+ return components;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.event.SystemEventListener#isListenerForSource(java.lang.Object)
+ */
+ public boolean isListenerForSource(Object source) {
+ return source instanceof AjaxOutput;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see
javax.faces.event.SystemEventListener#processEvent(javax.faces.event.SystemEvent)
+ */
+ public void processEvent(SystemEvent event) throws AbortProcessingException {
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+
+ getAjaxOutputComponentsSet(facesContext).add((AjaxOutput) event.getSource());
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/context/PartialViewContextFactoryImpl.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/context/PartialViewContextFactoryImpl.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/context/PartialViewContextFactoryImpl.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.context;
import javax.faces.context.FacesContext;
@@ -30,31 +32,28 @@
* @since 4.0
*/
public class PartialViewContextFactoryImpl extends PartialViewContextFactory {
+ public static final String RICHFACES_AJAX = "RICHFACES_AJAX";
+ private PartialViewContextFactory parentFactory;
- public static final String RICHFACES_AJAX = "RICHFACES_AJAX";
-
- private PartialViewContextFactory parentFactory;
-
- public PartialViewContextFactoryImpl(PartialViewContextFactory parentFactory) {
- super();
- this.parentFactory = parentFactory;
- }
+ public PartialViewContextFactoryImpl(PartialViewContextFactory parentFactory) {
+ super();
+ this.parentFactory = parentFactory;
+ }
- @Override
- public PartialViewContext getPartialViewContext(final FacesContext context) {
- PartialViewContext partialViewContext = parentFactory.getPartialViewContext(context);
+ @Override
+ public PartialViewContext getPartialViewContext(final FacesContext context) {
+ PartialViewContext partialViewContext =
parentFactory.getPartialViewContext(context);
+ String clientId =
context.getExternalContext().getRequestParameterMap().get(RICHFACES_AJAX);
- String clientId =
context.getExternalContext().getRequestParameterMap().get(RICHFACES_AJAX);
- if (clientId != null) {
- partialViewContext = new PartialViewContextImpl(partialViewContext, clientId);
- }
+ if (clientId != null) {
+ partialViewContext = new PartialViewContextImpl(partialViewContext,
clientId);
+ }
- return partialViewContext;
- }
-
- @Override
- public PartialViewContextFactory getWrapped() {
- return parentFactory;
- }
+ return partialViewContext;
+ }
+ @Override
+ public PartialViewContextFactory getWrapped() {
+ return parentFactory;
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/context/PartialViewContextImpl.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/context/PartialViewContextImpl.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/context/PartialViewContextImpl.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,141 +19,134 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.context;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
+import org.ajax4jsf.component.AjaxOutput;
import javax.faces.component.UIComponent;
-import javax.faces.component.behavior.ClientBehavior;
-import javax.faces.component.behavior.ClientBehaviorHolder;
-import javax.faces.component.visit.VisitCallback;
import javax.faces.component.visit.VisitContext;
import javax.faces.component.visit.VisitHint;
-import javax.faces.component.visit.VisitResult;
import javax.faces.context.FacesContext;
import javax.faces.context.PartialViewContext;
import javax.faces.context.PartialViewContextWrapper;
import javax.faces.event.PhaseId;
-import org.ajax4jsf.component.AjaxClientBehavior;
-import org.ajax4jsf.component.AjaxOutput;
-import org.ajax4jsf.renderkit.AjaxRendererUtils;
-import org.ajax4jsf.renderkit.RendererUtils;
+import java.util.*;
/**
* @author Nick Belaevski
* @since 4.0
*/
public class PartialViewContextImpl extends PartialViewContextWrapper {
-
public static final String BEHAVIOR_EVENT_PARAMETER =
"javax.faces.behavior.event";
-
+ private String behaviorEvent = null;
+ private boolean hasProcessedExecute = false;
+ private boolean executeAll = true;
+ private final String activatorId;
private final PartialViewContext wrappedContext;
-
- private final String activatorId;
- private boolean hasProcessedExecute = false;
-
- private boolean executeAll = true;
-
- private String behaviorEvent = null;
-
- public PartialViewContextImpl(PartialViewContext wrappedContext, String activatorId) {
- super();
-
- this.wrappedContext = wrappedContext;
- this.activatorId = activatorId;
- }
-
- @Override
- public PartialViewContext getWrapped() {
- return wrappedContext;
- }
+ public PartialViewContextImpl(PartialViewContext wrappedContext, String activatorId)
{
+ super();
+ this.wrappedContext = wrappedContext;
+ this.activatorId = activatorId;
+ }
- private VisitContext createVisitContext(FacesContext facesContext) {
- return VisitContext.createVisitContext(facesContext,
- Collections.singleton(activatorId),
- Collections.singleton(VisitHint.SKIP_UNRENDERED)
- );
- }
-
- //TODO: data table support
- private static Collection<String> getAjaxOutputComponentIds(FacesContext
facesContext) {
- List<String> ids = new ArrayList<String>();
- Collection<AjaxOutput> ajaxOutputComponentsSet =
PartialViewContextAjaxOutputTracker.getAjaxOutputComponentsSet(facesContext);
- for (AjaxOutput ajaxOutput : ajaxOutputComponentsSet) {
- if (ajaxOutput.isAjaxRendered()) {
- UIComponent ajaxOutputComponent = (UIComponent) ajaxOutput;
- ids.add(ajaxOutputComponent.getClientId(facesContext));
- }
- }
-
- return ids;
- }
+ @Override
+ public PartialViewContext getWrapped() {
+ return wrappedContext;
+ }
- private void decodeBehaviorEvent(FacesContext context) {
- Map<String, String> requestParameterMap =
context.getExternalContext().getRequestParameterMap();
- this.behaviorEvent = requestParameterMap.get(BEHAVIOR_EVENT_PARAMETER);
- }
-
- private void processExecute(PartialViewContext partialViewContext) {
- if (hasProcessedExecute) {
+ private VisitContext createVisitContext(FacesContext facesContext) {
+ return VisitContext.createVisitContext(facesContext,
Collections.singleton(activatorId),
+ Collections.singleton(VisitHint.SKIP_UNRENDERED));
+ }
+
+ // TODO: data table support
+ private static Collection<String> getAjaxOutputComponentIds(FacesContext
facesContext) {
+ List<String> ids = new ArrayList<String>();
+ Collection<AjaxOutput> ajaxOutputComponentsSet =
+
PartialViewContextAjaxOutputTracker.getAjaxOutputComponentsSet(facesContext);
+
+ for (AjaxOutput ajaxOutput : ajaxOutputComponentsSet) {
+ if (ajaxOutput.isAjaxRendered()) {
+ UIComponent ajaxOutputComponent = (UIComponent) ajaxOutput;
+
+ ids.add(ajaxOutputComponent.getClientId(facesContext));
+ }
+ }
+
+ return ids;
+ }
+
+ private void decodeBehaviorEvent(FacesContext context) {
+ Map<String, String> requestParameterMap =
context.getExternalContext().getRequestParameterMap();
+
+ this.behaviorEvent = requestParameterMap.get(BEHAVIOR_EVENT_PARAMETER);
+ }
+
+ private void processExecute(PartialViewContext partialViewContext) {
+ if (hasProcessedExecute) {
return;
}
+
hasProcessedExecute = true;
FacesContext facesContext = FacesContext.getCurrentInstance();
+
decodeBehaviorEvent(facesContext);
ComponentCallback executeCallback = new ExecuteComponentCallback(behaviorEvent);
+ boolean visitResult =
facesContext.getViewRoot().visitTree(createVisitContext(facesContext), executeCallback);
- boolean visitResult =
facesContext.getViewRoot().visitTree(createVisitContext(facesContext), executeCallback);
if (!visitResult) {
- //TODO:
+
+ // TODO:
}
executeAll = executeCallback.isHandleAll();
+
if (executeAll) {
return;
}
-
+
Collection<String> executeIds = partialViewContext.getExecuteIds();
+
executeIds.clear();
if (!executeCallback.isHandleNone()) {
executeIds.addAll(executeCallback.getComponentIds());
- //TODO ids from wrapped object?
+
+ // TODO ids from wrapped object?
}
}
-
- private void processRender(PartialViewContext partialViewContext) {
- FacesContext facesContext = FacesContext.getCurrentInstance();
- if (partialViewContext.isRenderAll()) {
+ private void processRender(PartialViewContext partialViewContext) {
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+
+ if (partialViewContext.isRenderAll()) {
return;
}
RenderComponentCallback renderCallback = new
RenderComponentCallback(behaviorEvent);
- boolean visitResult = facesContext.getViewRoot().visitTree(
- createVisitContext(facesContext),
- renderCallback);
+ boolean visitResult =
facesContext.getViewRoot().visitTree(createVisitContext(facesContext), renderCallback);
if (!visitResult) {
- //TODO:
+
+ // TODO:
}
boolean renderAll = renderCallback.isHandleAll();
+
partialViewContext.setRenderAll(renderAll);
+
if (renderAll) {
return;
}
Collection<String> renderIds = partialViewContext.getRenderIds();
+
renderIds.clear();
if (!renderCallback.isHandleNone()) {
@@ -161,60 +154,67 @@
if (!renderCallback.isLimitRender()) {
Collection<String> ajaxOutputComponentIds =
getAjaxOutputComponentIds(facesContext);
+
renderIds.addAll(ajaxOutputComponentIds);
- //TODO ids from wrapped object?
+
+ // TODO ids from wrapped object?
}
}
- }
-
- @Override
- public void processPartial(PhaseId phaseId) {
- PartialViewContext wrapped = getWrapped();
+ }
- if (PhaseId.APPLY_REQUEST_VALUES.equals(phaseId)) {
- processExecute(wrapped);
- } else if (PhaseId.RENDER_RESPONSE.equals(phaseId)) {
- processRender(wrapped);
- }
-
- wrapped.processPartial(phaseId);
- }
+ @Override
+ public void processPartial(PhaseId phaseId) {
+ PartialViewContext wrapped = getWrapped();
- @Override
- public void setPartialRequest(boolean isPartialRequest) {
- getWrapped().setPartialRequest(isPartialRequest);
- }
-
- /* (non-Javadoc)
- * @see javax.faces.context.PartialViewContextWrapper#getRenderIds()
- */
- @Override
- public Collection<String> getRenderIds() {
- return getWrapped().getRenderIds();
- }
-
- /* (non-Javadoc)
- * @see javax.faces.context.PartialViewContextWrapper#getExecuteIds()
- */
- @Override
- public Collection<String> getExecuteIds() {
- return getWrapped().getExecuteIds();
- }
-
- /* (non-Javadoc)
- * @see javax.faces.context.PartialViewContextWrapper#isExecuteAll()
- */
- @Override
- public boolean isExecuteAll() {
- processExecute(getWrapped());
- return executeAll;
- }
-
- /* (non-Javadoc)
- * @see javax.faces.context.PartialViewContextWrapper#isRenderAll()
- */
- @Override
- public boolean isRenderAll() {
- return getWrapped().isRenderAll();
- }
+ if (PhaseId.APPLY_REQUEST_VALUES.equals(phaseId)) {
+ processExecute(wrapped);
+ } else if (PhaseId.RENDER_RESPONSE.equals(phaseId)) {
+ processRender(wrapped);
+ }
+
+ wrapped.processPartial(phaseId);
+ }
+
+ @Override
+ public void setPartialRequest(boolean isPartialRequest) {
+ getWrapped().setPartialRequest(isPartialRequest);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.context.PartialViewContextWrapper#getRenderIds()
+ */
+ @Override
+ public Collection<String> getRenderIds() {
+ return getWrapped().getRenderIds();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.context.PartialViewContextWrapper#getExecuteIds()
+ */
+ @Override
+ public Collection<String> getExecuteIds() {
+ return getWrapped().getExecuteIds();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.context.PartialViewContextWrapper#isExecuteAll()
+ */
+ @Override
+ public boolean isExecuteAll() {
+ processExecute(getWrapped());
+
+ return executeAll;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.context.PartialViewContextWrapper#isRenderAll()
+ */
+ @Override
+ public boolean isRenderAll() {
+ return getWrapped().isRenderAll();
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/context/RenderComponentCallback.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/context/RenderComponentCallback.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/context/RenderComponentCallback.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,36 +19,36 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.context;
import org.ajax4jsf.component.AjaxClientBehavior;
import org.ajax4jsf.renderkit.AjaxRendererUtils;
+import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
-import javax.faces.component.UIComponent;
/**
* @author akolonitsky
* @since Oct 13, 2009
*/
class RenderComponentCallback extends ComponentCallback {
+ private boolean limitRender = false;
RenderComponentCallback(String behaviorEvent) {
super(behaviorEvent, false, false);
}
- private boolean limitRender = false;
-
public boolean isLimitRender() {
return limitRender;
}
@Override
- protected void doVisit(FacesContext context, UIComponent target,
- AjaxClientBehavior behavior) {
-
+ protected void doVisit(FacesContext context, UIComponent target, AjaxClientBehavior
behavior) {
super.doVisit(context, target, behavior);
limitRender = AjaxRendererUtils.isAjaxLimitRender(target);
+
if (behavior != null) {
limitRender = behavior.isLimitRender();
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/context/SingletonsContext.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/context/SingletonsContext.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/context/SingletonsContext.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.context;
import java.util.Map;
@@ -29,27 +31,19 @@
* @author Nick Belaevski
* @since 4.0
*/
-public class SingletonsContext {
-
- private SingletonsContext() {
- }
-
+public final class SingletonsContext {
public static final ContextProvider APPLICATION = new
ContextProvider("Application") {
+ @Override
+ protected Map<String, Object> getContextMap(FacesContext facesContext) {
+ return facesContext.getExternalContext().getApplicationMap();
+ }
+ };
+ public static final ContextProvider FACES_CONTEXT = new
ContextProvider("FacesContext") {
+ @Override
+ protected Map<? super String, Object> getContextMap(FacesContext
facesContext) {
+ return facesContext.getAttributes();
+ }
+ };
- @Override
- protected Map<String, Object> getContextMap(FacesContext facesContext) {
- return facesContext.getExternalContext().getApplicationMap();
- }
-
- };
-
- public static final ContextProvider FACES_CONTEXT = new
ContextProvider("FacesContext") {
-
- @Override
- protected Map<? super String, Object> getContextMap(FacesContext facesContext) {
- return facesContext.getAttributes();
- }
-
- };
-
+ private SingletonsContext() {}
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/event/SwitchablePanelSwitchEvent.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/event/SwitchablePanelSwitchEvent.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/event/SwitchablePanelSwitchEvent.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.event;
import javax.faces.component.UIComponent;
@@ -28,40 +30,36 @@
/**
* @author Nick Belaevski - nbelaevski(a)exadel.com
* created 23.01.2007
- *
+ *
*/
public class SwitchablePanelSwitchEvent extends FacesEvent {
- private Object value;
- private UIComponent eventSource;
-
-
- public SwitchablePanelSwitchEvent(UIComponent component,
- Object value, UIComponent eventSource) {
- super(component);
-
- this.value = value;
- this.eventSource = eventSource;
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = 8579050007143915239L;
+ private UIComponent eventSource;
+ private Object value;
- /**
- *
- */
- private static final long serialVersionUID = 8579050007143915239L;
+ public SwitchablePanelSwitchEvent(UIComponent component, Object value, UIComponent
eventSource) {
+ super(component);
+ this.value = value;
+ this.eventSource = eventSource;
+ }
- public Object getValue() {
- return value;
- }
-
- public UIComponent getEventSource() {
- return eventSource;
- }
-
- public boolean isAppropriateListener(FacesListener listener) {
- return false;
- }
+ public Object getValue() {
+ return value;
+ }
- public void processListener(FacesListener listener) {
- throw new UnsupportedOperationException();
- }
+ public UIComponent getEventSource() {
+ return eventSource;
+ }
+
+ public boolean isAppropriateListener(FacesListener listener) {
+ return false;
+ }
+
+ public void processListener(FacesListener listener) {
+ throw new UnsupportedOperationException();
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/event/package-info.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/event/package-info.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/event/package-info.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -1,3 +1,4 @@
+
/**
* Base RichFaces component events classes
*/
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/json/CDL.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/json/CDL.java 2009-11-01
17:06:52 UTC (rev 15799)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/json/CDL.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -43,7 +43,8 @@
* @author
JSON.org
* @version 2
*/
-public class CDL {
+public final class CDL {
+ private CDL() {}
/**
* Get the next value. The value can be wrapped in quotes. The value can
@@ -54,21 +55,28 @@
*/
private static String getValue(JSONTokener x) throws JSONException {
char c;
+
do {
c = x.next();
- } while (c <= ' ' && c != 0);
+ } while ((c <= ' ') && (c != 0));
+
switch (c) {
- case 0:
- return null;
- case '"':
- case '\'':
- return x.nextString(c);
- case ',':
- x.back();
- return "";
- default:
- x.back();
- return x.nextTo(',');
+ case 0 :
+ return null;
+
+ case '"' :
+ case '\'' :
+ return x.nextString(c);
+
+ case ',' :
+ x.back();
+
+ return "";
+
+ default :
+ x.back();
+
+ return x.nextTo(',');
}
}
@@ -80,23 +88,29 @@
*/
public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException {
JSONArray ja = new JSONArray();
+
for (;;) {
String value = getValue(x);
+
if (value == null) {
return null;
}
+
ja.put(value);
+
for (;;) {
char c = x.next();
+
if (c == ',') {
break;
}
+
if (c != ' ') {
- if (c == '\n' || c == '\r' || c == 0) {
+ if ((c == '\n') || (c == '\r') || (c == 0)) {
return ja;
}
- throw x.syntaxError("Bad character '" + c + "'
(" +
- (int)c + ").");
+
+ throw x.syntaxError("Bad character '" + c + "'
(" + (int) c + ").");
}
}
}
@@ -112,10 +126,10 @@
* @return A JSONObject combining the names and values.
* @throws JSONException
*/
- public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x)
- throws JSONException {
+ public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) throws
JSONException {
JSONArray ja = rowToJSONArray(x);
- return ja != null ? ja.toJSONObject(names) : null;
+
+ return (ja != null) ? ja.toJSONObject(names) : null;
}
/**
@@ -148,8 +162,7 @@
* @return A JSONArray of JSONObjects.
* @throws JSONException
*/
- public static JSONArray toJSONArray(JSONArray names, String string)
- throws JSONException {
+ public static JSONArray toJSONArray(JSONArray names, String string) throws
JSONException {
return toJSONArray(names, new JSONTokener(string));
}
@@ -161,26 +174,30 @@
* @return A JSONArray of JSONObjects.
* @throws JSONException
*/
- public static JSONArray toJSONArray(JSONArray names, JSONTokener x)
- throws JSONException {
- if (names == null || names.length() == 0) {
+ public static JSONArray toJSONArray(JSONArray names, JSONTokener x) throws
JSONException {
+ if ((names == null) || (names.length() == 0)) {
return null;
}
+
JSONArray ja = new JSONArray();
+
for (;;) {
JSONObject jo = rowToJSONObject(names, x);
+
if (jo == null) {
break;
}
+
ja.put(jo);
}
+
if (ja.length() == 0) {
return null;
}
+
return ja;
}
-
/**
* Produce a comma delimited text row from a JSONArray. Values containing
* the comma character will be quoted.
@@ -189,13 +206,17 @@
*/
public static String rowToString(JSONArray ja) {
StringBuffer sb = new StringBuffer();
+
for (int i = 0; i < ja.length(); i += 1) {
if (i > 0) {
sb.append(',');
}
+
Object o = ja.opt(i);
+
if (o != null) {
String s = o.toString();
+
if (s.indexOf(',') >= 0) {
if (s.indexOf('"') >= 0) {
sb.append('\'');
@@ -211,9 +232,10 @@
}
}
}
+
sb.append('\n');
+
return sb.toString();
-
}
/**
@@ -226,12 +248,15 @@
*/
public static String toString(JSONArray ja) throws JSONException {
JSONObject jo = ja.optJSONObject(0);
+
if (jo != null) {
JSONArray names = jo.names();
+
if (names != null) {
return rowToString(names) + toString(names, ja);
}
}
+
return null;
}
@@ -244,18 +269,21 @@
* @return A comma delimited text.
* @throws JSONException
*/
- public static String toString(JSONArray names, JSONArray ja)
- throws JSONException {
- if (names == null || names.length() == 0) {
+ public static String toString(JSONArray names, JSONArray ja) throws JSONException {
+ if ((names == null) || (names.length() == 0)) {
return null;
}
+
StringBuffer sb = new StringBuffer();
+
for (int i = 0; i < ja.length(); i += 1) {
JSONObject jo = ja.optJSONObject(i);
+
if (jo != null) {
sb.append(rowToString(jo.toJSONArray(names)));
}
}
+
return sb.toString();
}
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/json/Cookie.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/json/Cookie.java 2009-11-01
17:06:52 UTC (rev 15799)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/json/Cookie.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -30,7 +30,8 @@
* @author
JSON.org
* @version 2
*/
-public class Cookie {
+public final class Cookie {
+ private Cookie() {}
/**
* Produce a copy of a string in which the characters '+', '%',
'=', ';'
@@ -45,24 +46,26 @@
* @return The escaped result.
*/
public static String escape(String string) {
- char c;
- String s = string.trim();
+ char c;
+ String s = string.trim();
StringBuffer sb = new StringBuffer();
- int len = s.length();
+ int len = s.length();
+
for (int i = 0; i < len; i += 1) {
c = s.charAt(i);
- if (c < ' ' || c == '+' || c == '%' || c ==
'=' || c == ';') {
+
+ if ((c < ' ') || (c == '+') || (c == '%') || (c ==
'=') || (c == ';')) {
sb.append('%');
- sb.append(Character.forDigit((char)((c >>> 4) & 0x0f),
16));
- sb.append(Character.forDigit((char)(c & 0x0f), 16));
+ sb.append(Character.forDigit((char) ((c >>> 4) & 0x0f),
16));
+ sb.append(Character.forDigit((char) (c & 0x0f), 16));
} else {
sb.append(c);
}
}
+
return sb.toString();
}
-
/**
* Convert a cookie specification string into a JSONObject. The string
* will contain a name value pair separated by '='. The name and the value
@@ -79,16 +82,19 @@
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
- String n;
- JSONObject o = new JSONObject();
- Object v;
+ String n;
+ JSONObject o = new JSONObject();
+ Object v;
JSONTokener x = new JSONTokener(string);
+
o.put("name", x.nextTo('='));
x.next('=');
o.put("value", x.nextTo(';'));
x.next();
+
while (x.more()) {
n = unescape(x.nextTo("=;"));
+
if (x.next() != '=') {
if (n.equals("secure")) {
v = Boolean.TRUE;
@@ -99,12 +105,13 @@
v = unescape(x.nextTo(';'));
x.next();
}
+
o.put(n, v);
}
+
return o;
}
-
/**
* Convert a JSONObject into a cookie specification string. The JSONObject
* must contain "name" and "value" members.
@@ -121,21 +128,26 @@
sb.append(escape(o.getString("name")));
sb.append("=");
sb.append(escape(o.getString("value")));
+
if (o.has("expires")) {
sb.append(";expires=");
sb.append(o.getString("expires"));
}
+
if (o.has("domain")) {
sb.append(";domain=");
sb.append(escape(o.getString("domain")));
}
+
if (o.has("path")) {
sb.append(";path=");
sb.append(escape(o.getString("path")));
}
+
if (o.optBoolean("secure")) {
sb.append(";secure");
}
+
return sb.toString();
}
@@ -150,20 +162,25 @@
public static String unescape(String s) {
int len = s.length();
StringBuffer b = new StringBuffer();
+
for (int i = 0; i < len; ++i) {
char c = s.charAt(i);
+
if (c == '+') {
c = ' ';
- } else if (c == '%' && i + 2 < len) {
+ } else if ((c == '%') && (i + 2 < len)) {
int d = JSONTokener.dehexchar(s.charAt(i + 1));
int e = JSONTokener.dehexchar(s.charAt(i + 2));
- if (d >= 0 && e >= 0) {
- c = (char)(d * 16 + e);
+
+ if ((d >= 0) && (e >= 0)) {
+ c = (char) (d * 16 + e);
i += 2;
}
}
+
b.append(c);
}
+
return b.toString();
}
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/json/CookieList.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/json/CookieList.java 2009-11-01
17:06:52 UTC (rev 15799)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/json/CookieList.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -23,7 +23,6 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
-
import java.util.Iterator;
/**
@@ -31,7 +30,8 @@
* @author
JSON.org
* @version 2
*/
-public class CookieList {
+public final class CookieList {
+ private CookieList() {}
/**
* Convert a cookie list into a JSONObject. A cookie list is a sequence
@@ -49,16 +49,18 @@
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject o = new JSONObject();
JSONTokener x = new JSONTokener(string);
+
while (x.more()) {
String name = Cookie.unescape(x.nextTo('='));
+
x.next('=');
o.put(name, Cookie.unescape(x.nextTo(';')));
x.next();
}
+
return o;
}
-
/**
* Convert a JSONObject into a cookie list. A cookie list is a sequence
* of name/value pairs. The names are separated from the values by '='.
@@ -69,22 +71,26 @@
* @throws JSONException
*/
public static String toString(JSONObject o) throws JSONException {
- boolean b = false;
- Iterator keys = o.keys();
- String s;
+ boolean b = false;
+ Iterator keys = o.keys();
+ String s;
StringBuffer sb = new StringBuffer();
+
while (keys.hasNext()) {
s = keys.next().toString();
+
if (!o.isNull(s)) {
if (b) {
sb.append(';');
}
+
sb.append(Cookie.escape(s));
sb.append("=");
sb.append(Cookie.escape(o.getString(s)));
b = true;
}
}
+
return sb.toString();
}
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/json/HTTP.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/json/HTTP.java 2009-11-01
17:06:52 UTC (rev 15799)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/json/HTTP.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -23,7 +23,6 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
-
import java.util.Iterator;
/**
@@ -31,11 +30,15 @@
* @author
JSON.org
* @version 2
*/
-public class HTTP {
+public final class HTTP {
- /** Carriage return/line feed. */
+ /**
+ * Carriage return/line feed.
+ */
public static final String CRLF = "\r\n";
+ private HTTP() {}
+
/**
* Convert an HTTP header string into a JSONObject. It can be a request
* header or a response header. A request header will contain
@@ -69,41 +72,39 @@
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
- JSONObject o = new JSONObject();
- HTTPTokener x = new HTTPTokener(string);
- String t;
+ JSONObject o = new JSONObject();
+ HTTPTokener x = new HTTPTokener(string);
+ String t;
t = x.nextToken();
+
if (t.toUpperCase().startsWith("HTTP")) {
-// Response
-
+// Response
o.put("HTTP-Version", t);
o.put("Status-Code", x.nextToken());
o.put("Reason-Phrase", x.nextTo('\0'));
x.next();
-
} else {
-// Request
-
+// Request
o.put("Method", t);
o.put("Request-URI", x.nextToken());
o.put("HTTP-Version", x.nextToken());
}
-// Fields
-
+// Fields
while (x.more()) {
String name = x.nextTo(':');
+
x.next(':');
o.put(name, x.nextTo('\0'));
x.next();
}
+
return o;
}
-
/**
* Convert a JSONObject into an HTTP header. A request header must contain
* <pre>{
@@ -125,9 +126,10 @@
* information.
*/
public static String toString(JSONObject o) throws JSONException {
- Iterator keys = o.keys();
- String s;
+ Iterator keys = o.keys();
+ String s;
StringBuffer sb = new StringBuffer();
+
if (o.has("Status-Code") && o.has("Reason-Phrase"))
{
sb.append(o.getString("HTTP-Version"));
sb.append(' ');
@@ -145,19 +147,23 @@
} else {
throw new JSONException("Not enough material for an HTTP
header.");
}
+
sb.append(CRLF);
+
while (keys.hasNext()) {
s = keys.next().toString();
- if (!s.equals("HTTP-Version") &&
!s.equals("Status-Code") &&
- !s.equals("Reason-Phrase") &&
!s.equals("Method") &&
- !s.equals("Request-URI") && !o.isNull(s)) {
+
+ if (!s.equals("HTTP-Version") &&
!s.equals("Status-Code") && !s.equals("Reason-Phrase")
+ && !s.equals("Method") &&
!s.equals("Request-URI") && !o.isNull(s)) {
sb.append(s);
sb.append(": ");
sb.append(o.getString(s));
sb.append(CRLF);
}
}
+
sb.append(CRLF);
+
return sb.toString();
}
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/json/HTTPTokener.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/json/HTTPTokener.java 2009-11-01
17:06:52 UTC (rev 15799)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/json/HTTPTokener.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -40,7 +40,6 @@
super(s);
}
-
/**
* Get the next token or string. This is used in parsing HTTP headers.
* @throws JSONException
@@ -50,26 +49,34 @@
char c;
char q;
StringBuffer sb = new StringBuffer();
+
do {
c = next();
} while (Character.isWhitespace(c));
- if (c == '"' || c == '\'') {
+
+ if ((c == '"') || (c == '\'')) {
q = c;
+
for (;;) {
c = next();
+
if (c < ' ') {
throw syntaxError("Unterminated string.");
}
+
if (c == q) {
return sb.toString();
}
+
sb.append(c);
}
- }
+ }
+
for (;;) {
- if (c == 0 || Character.isWhitespace(c)) {
+ if ((c == 0) || Character.isWhitespace(c)) {
return sb.toString();
}
+
sb.append(c);
c = next();
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSContentHandler.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSContentHandler.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSContentHandler.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,116 +19,88 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.json;
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Arrays;
-
import org.ajax4jsf.Messages;
import org.ajax4jsf.javascript.JSEncoder;
+
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
+import java.io.IOException;
+import java.io.Writer;
+import java.util.Arrays;
+
/**
* @author shura
* SAX content handler for serialise events as JavaScript function.
*/
-public class JSContentHandler implements ContentHandler,LexicalHandler {
-
- protected Writer outputWriter;
-
- private static final JSEncoder encoder = new JSEncoder();
-
- private static final char S_EOL[] = System.getProperty("line.separator")
- .toCharArray();
-
- private static final char S_DOCUMENT_START[] = "(".toCharArray();
-
- private static final char S_DOCUMENT_ENF[] = ");".toCharArray();
-
- private static final char S_DOCUMENT_3[] = "\"?>".toCharArray();
-
- private static final char S_OBJECT_START[] = "{".toCharArray();
+public class JSContentHandler implements ContentHandler, LexicalHandler {
+ private static final char C_COMMA = ',';
+ private static final char C_GT = '>';
+ private static final char C_LT = '<';
+ private static final char C_NSSEP = ':';
+ private static final char C_QUOTE = '\'';
+ private static final char C_SPACE = ' ';
+ public static final String DEFAULT_ENCODING = "ISO-8859-1";
+ private static final JSEncoder ENCODER = new JSEncoder();
+ private static final char[] S_TEXT_START = "new T(".toCharArray();
+ private static final char[] S_TEXT_END = ")".toCharArray();
+ private static final char[] S_PROCINSTR_START = "<?".toCharArray();
+ private static final char[] S_PROCINSTR_END = "?>".toCharArray();
+ private static final char[] S_OBJECT_START = "{".toCharArray();
private static final char[] S_OBJECT_END = "}".toCharArray();
-
- private static final char S_ELEMENT_START[] = "new E(".toCharArray();
-
+ private static final char[] S_EOL =
System.getProperty("line.separator").toCharArray();
+ private static final char[] S_ELEMENT_START = "new E(".toCharArray();
+ private static final char[] S_ELEMENT_END_START_TAG = ",[".toCharArray();
+ private static final char[] S_ELEMENT_END = "])".toCharArray();
private static final char[] S_ELEMENT_CLOSE = ")".toCharArray();
-
- private static final char S_ATTRIBUTES_END[] = "}".toCharArray();
-
- private static final char S_ATTRIBUTES_START[] = ",{".toCharArray();
-
- private static final char S_ELEMENT_END_START_TAG[] = ",[".toCharArray();
-
- private static final char S_ELEMENT_END[] = "])".toCharArray();
-
- private static final char S_TEXT_START[] = "new T(".toCharArray();
-
- private static final char S_TEXT_END[] = ")".toCharArray();
-
- private static final char S_CDATA_START[] = "new D('".toCharArray();
-
- private static final char S_CDATA_END[] = "')".toCharArray();
-
- private static final char S_COMMENT_START[] = "new C('".toCharArray();
-
- private static final char S_COMMENT_END[] = "')".toCharArray();
-
- private static final char S_PROCINSTR_START[] = "<?".toCharArray();
-
- private static final char S_PROCINSTR_END[] = "?>".toCharArray();
-
- private static final char C_LT = '<';
-
- private static final char C_GT = '>';
-
- private static final char C_SPACE = ' ';
-
- private static final char C_QUOTE = '\'';
-
- private static final char C_NSSEP = ':';
-
- private static final char C_COMMA = ',';
-
+ private static final char[] S_DOCUMENT_START = "(".toCharArray();
+ private static final char[] S_DOCUMENT_ENF = ");".toCharArray();
+ private static final char[] S_DOCUMENT_3 = "\"?>".toCharArray();
+ private static final char[] S_COMMENT_START = "new C('".toCharArray();
+ private static final char[] S_COMMENT_END = "')".toCharArray();
+ private static final char[] S_CDATA_START = "new D('".toCharArray();
+ private static final char[] S_CDATA_END = "')".toCharArray();
+ private static final char[] S_ATTRIBUTES_START = ",{".toCharArray();
+ private static final char[] S_ATTRIBUTES_END = "}".toCharArray();
private static final boolean DEBUG = false;
+ private boolean hangingElement = false;
- /* ====================================================================== */
- private boolean hanging_element = false;
-
/** True if we are processing the prolog. */
private boolean beforeDocumentStart = true;
/** True if we are processing the DTD. */
- private boolean processing_dtd = false;
+ private boolean processingDtd = false;
/** True if we are processing the DTD. */
- private boolean processing_cdata = false;
- /** The <code>DocType</code> instance representing the document. */
- // protected DocType doctype = null;
+ private boolean processingCdata = false;
- protected int level;
+ /* ====================================================================== */
+ // protected DocType doctype = null;
protected char[] indentBuffer;
+ protected int level;
-
+ /** The <code>DocType</code> instance representing the document. */
private Locator locator;
+ protected Writer outputWriter;
- public static final String DEFAULT_ENCODING = "ISO-8859-1";
-
- public JSContentHandler() {
- }
- /**
+ public JSContentHandler() {}
+
+ /**
* @param outputWriter
*/
public JSContentHandler(Writer outputWriter) {
this.outputWriter = outputWriter;
}
+
/**
* @throws java.io.IOException
*/
@@ -137,62 +109,75 @@
}
// ContentHandler Methods
- /* (non-Javadoc)
+
+ /*
+ * (non-Javadoc)
* @see org.xml.sax.ContentHandler#characters(char[], int, int)
*/
- public void characters(char[] ch, int start, int length)
- throws SAXException {
- if (this.beforeDocumentStart || level < 0)
+ public void characters(char[] ch, int start, int length) throws SAXException {
+ if (this.beforeDocumentStart || (level < 0)) {
return;
+ }
+
try {
- if (level != 0 && !this.closeElement(false) &&
this.processing_cdata == false) {
+ if ((level != 0) && !this.closeElement(false) &&
!this.processingCdata) {
this.outputWriter.write(C_COMMA);
}
+
if (DEBUG) {
this.outputWriter.write('[');
this.outputWriter.write(Integer.toString(level));
this.outputWriter.write(']');
}
- if (this.processing_cdata == false) {
+
+ if (!this.processingCdata) {
this.outputWriter.write(S_TEXT_START);
}
+
this.encodeText(ch, start, length);
- if (this.processing_cdata == false) {
+
+ if (!this.processingCdata) {
this.outputWriter.write(S_TEXT_END);
}
} catch (IOException e) {
- throw new SAXException("Write error",e);
+ throw new SAXException("Write error", e);
}
}
- /* (non-Javadoc)
+
+ /*
+ * (non-Javadoc)
* @see org.xml.sax.ContentHandler#endDocument()
*/
public void endDocument() throws SAXException {
this.beforeDocumentStart = true;
-
- if (this.level != 0) {
+
+ if (this.level != 0) {
throw new
SAXException(Messages.getMessage(Messages.OPEN_CLOSE_TAGS_DO_NOT_MATCH_ERROR));
}
+
// Write parameters after parsing and final function )
try {
- this.outputWriter.write(S_EOL);
+ this.outputWriter.write(S_EOL);
this.outputWriter.flush();
} catch (IOException e) {
- throw new SAXException("Write error",e);
+ throw new SAXException("Write error", e);
}
}
-
-
- /* (non-Javadoc)
+
+ /*
+ * (non-Javadoc)
* @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String,
java.lang.String)
*/
- public void endElement(String uri, String localName, String qName)
- throws SAXException {
+ public void endElement(String uri, String localName, String qName) throws
SAXException {
this.level--;
- if (closeElement(true))
+
+ if (closeElement(true)) {
return;
+ }
+
try {
this.outputWriter.write(S_ELEMENT_END); // [</]
+
if (DEBUG) {
this.outputWriter.write('[');
this.outputWriter.write(qName);
@@ -201,58 +186,66 @@
this.outputWriter.write(']');
}
} catch (IOException e) {
- throw new SAXException("Write error",e);
+ throw new SAXException("Write error", e);
}
- // this.outputWriter.write(qual);
- // this.outputWriter.write(C_GT); // [>]
+
+ // this.outputWriter.write(qual);
+ // this.outputWriter.write(C_GT); // [>]
}
/**
* Write the end part of a start element (if necessary).
- *
- * @param end_element
+ *
+ * @param endElement
* Whether this method was called because an element is being
* closed or not.
* @return <b>true </b> if this call successfully closed the element (and
no
* further <code></element></code> is required.
*/
- protected boolean closeElement(boolean end_element) throws SAXException {
- if (!hanging_element)
- return (false);
+ protected boolean closeElement(boolean endElement) throws SAXException {
+ if (!hangingElement) {
+ return false;
+ }
+
try {
- if (end_element)
+ if (endElement) {
this.outputWriter.write(S_ELEMENT_CLOSE); // [ />]
- else
+ } else {
this.outputWriter.write(S_ELEMENT_END_START_TAG); // [>]
+ }
} catch (IOException e) {
- throw new SAXException("Write error",e);
+ throw new SAXException("Write error", e);
}
- this.hanging_element = false;
- return (true);
+
+ this.hangingElement = false;
+
+ return true;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String)
*/
- public void endPrefixMapping(String prefix) throws SAXException {
+ public void endPrefixMapping(String prefix) throws SAXException {}
- }
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int)
*/
- public void ignorableWhitespace(char[] ch, int start, int length)
- throws SAXException {
+ public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException
{
+
// TODO Auto-generated method stub
+ }
- }
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String,
java.lang.String)
*/
- public void processingInstruction(String target, String data)
- throws SAXException {
+ public void processingInstruction(String target, String data) throws SAXException {
+
// TODO Auto-generated method stub
+ }
- }
/* ====================================================================== */
/**
@@ -269,7 +262,7 @@
* or <b>null</b> if none is available.
*/
public String getPublicId() {
- return(this.locator == null? null: this.locator.getPublicId());
+ return (this.locator == null) ? null : this.locator.getPublicId();
}
/**
@@ -279,16 +272,16 @@
* or <b>null</b> if none is available.
*/
public String getSystemId() {
- return(this.locator == null? null: this.locator.getSystemId());
+ return (this.locator == null) ? null : this.locator.getSystemId();
}
-
+
/**
* Return the line number where the current document event ends.
*
* @return The line number, or -1 if none is available.
*/
public int getLineNumber() {
- return(this.locator == null? -1: this.locator.getLineNumber());
+ return (this.locator == null) ? -1 : this.locator.getLineNumber();
}
/**
@@ -297,316 +290,373 @@
* @return The column number, or -1 if none is available.
*/
public int getColumnNumber() {
- return(this.locator == null? -1: this.locator.getColumnNumber());
+ return (this.locator == null) ? -1 : this.locator.getColumnNumber();
}
/**
* Return a <code>String</code> describing the current location.
*/
protected String getLocation() {
- if (this.locator == null) return("");
+ if (this.locator == null) {
+ return "";
+ }
+
StringBuffer buf = new StringBuffer(" (");
+
if (this.getSystemId() != null) {
buf.append(this.getSystemId());
buf.append(' ');
}
+
buf.append("line " + this.getLineNumber());
buf.append(" col " + this.getColumnNumber());
buf.append(')');
- return(buf.toString());
+
+ return buf.toString();
}
/* ====================================================================== */
- /* (non-Javadoc)
+
+ /*
+ * (non-Javadoc)
* @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String)
*/
public void skippedEntity(String name) throws SAXException {
+
// TODO Auto-generated method stub
+ }
- }
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see org.xml.sax.ContentHandler#startDocument()
*/
public void startDocument() throws SAXException {
this.beforeDocumentStart = false;
- this.processing_cdata = false;
+ this.processingCdata = false;
this.level = 0;
+
/* We have a document type. */
-// if (this.doctype != null) {
+
+// if (this.doctype != null) {
//
-// String root_name = this.doctype.getName();
-// /* Check the DTD and the root element */
-// if (!root_name.equals(qual)) {
-// throw new SAXException("Root element name \"" +
root_name
-// + "\" declared by document type declaration differs
"
-// + "from actual root element name \"" + qual +
"\"");
-// }
- /* Output the <!DOCTYPE ...> declaration. */
- // this.outputWriter.write(this.doctype.toString());
-// }
+// String root_name = this.doctype.getName();
+// /* Check the DTD and the root element */
+// if (!root_name.equals(qual)) {
+// throw new SAXException("Root element name \"" + root_name
+// + "\" declared by document type declaration differs
"
+// + "from actual root element name \"" + qual +
"\"");
+// }
+
+ /* Output the <!DOCTYPE ...> declaration. */
+
+ // this.outputWriter.write(this.doctype.toString());
+// }
}
- /* (non-Javadoc)
- * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String,
java.lang.String, org.xml.sax.Attributes)
+ /*
+ * (non-Javadoc)
+ * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String,
java.lang.String,
+ * org.xml.sax.Attributes)
*/
- public void startElement(String uri, String localName,
- String qName, Attributes attributes) throws SAXException {
+ public void startElement(String uri, String localName, String qName, Attributes
attributes) throws SAXException {
try {
- if (!this.closeElement(false) && this.level > 0) {
+ if (!this.closeElement(false) && (this.level > 0)) {
this.outputWriter.write(C_COMMA);
}
+
this.outputWriter.write(S_ELEMENT_START); // [<]
+
if (DEBUG) {
this.outputWriter.write('[');
this.outputWriter.write(uri);
this.outputWriter.write(']');
}
+
this.outputWriter.write(C_QUOTE);
this.outputWriter.write(qName);
this.outputWriter.write(C_QUOTE);
-// if (attributes.getLength() > 0) {
- this.outputWriter.write(S_ATTRIBUTES_START);
- // TODO - implementing namespaces !
- // for (int x = 0; x < namespaces.length; x++) {
- // this.outputWriter.write(S_ELEMENT_4); // [ xmlns]
- // if (namespaces[x][Namespaces.NAMESPACE_PREFIX].length()
> 0) {
- // this.outputWriter.write(C_NSSEP); // [:]
- //
this.outputWriter.write(namespaces[x][Namespaces.NAMESPACE_PREFIX]);
- // }
- // this.outputWriter.write(S_ELEMENT_1); // [="]
- // this.encode(namespaces[x][Namespaces.NAMESPACE_URI]);
- // this.outputWriter.write(C_QUOTE); // ["]
- // }
- for (int x = 0; x < attributes.getLength(); x++) {
- if (0 != x) {
- this.outputWriter.write(C_COMMA);
- this.outputWriter.write(C_SPACE); // [ ]
- }
- if (DEBUG) {
- this.outputWriter.write('[');
- this.outputWriter.write(attributes.getURI(x));
- this.outputWriter.write(']');
- }
- String attrName = attributes.getQName(x);
- // For JavaScript any attributes names illegal ...
- // replate with correct names.
- if (attrName.equalsIgnoreCase("class")) {
- attrName = "className";
- }
- this.outputWriter.write(C_QUOTE); // [']
- this.outputWriter.write(attrName);
- this.outputWriter.write(C_QUOTE); // [']
- this.outputWriter.write(C_NSSEP); // [:]
- //TODO by nick - fix namespace handling - they shouldn't be encoded
- this.encodeAttributeValue(attributes, x);
+// if (attributes.getLength() > 0) {
+ this.outputWriter.write(S_ATTRIBUTES_START);
+
+ // TODO - implementing namespaces !
+ // for (int x = 0; x < namespaces.length; x++) {
+ // this.outputWriter.write(S_ELEMENT_4); // [ xmlns]
+ // if (namespaces[x][Namespaces.NAMESPACE_PREFIX].length() > 0) {
+ // this.outputWriter.write(C_NSSEP); // [:]
+ // this.outputWriter.write(namespaces[x][Namespaces.NAMESPACE_PREFIX]);
+ // }
+ // this.outputWriter.write(S_ELEMENT_1); // [="]
+ // this.encode(namespaces[x][Namespaces.NAMESPACE_URI]);
+ // this.outputWriter.write(C_QUOTE); // ["]
+ // }
+ for (int x = 0; x < attributes.getLength(); x++) {
+ if (0 != x) {
+ this.outputWriter.write(C_COMMA);
+ this.outputWriter.write(C_SPACE); // [ ]
}
- this.outputWriter.write(S_ATTRIBUTES_END);
-// }
+ if (DEBUG) {
+ this.outputWriter.write('[');
+ this.outputWriter.write(attributes.getURI(x));
+ this.outputWriter.write(']');
+ }
+
+ String attrName = attributes.getQName(x);
+
+ // For JavaScript any attributes names illegal ...
+ // replate with correct names.
+ if (attrName.equalsIgnoreCase("class")) {
+ attrName = "className";
+ }
+
+ this.outputWriter.write(C_QUOTE); // [']
+ this.outputWriter.write(attrName);
+ this.outputWriter.write(C_QUOTE); // [']
+ this.outputWriter.write(C_NSSEP); // [:]
+
+ // TODO by nick - fix namespace handling - they shouldn't be encoded
+ this.encodeAttributeValue(attributes, x);
+ }
+
+ this.outputWriter.write(S_ATTRIBUTES_END);
+
+// }
this.level++;
- this.hanging_element = true;
+ this.hangingElement = true;
} catch (IOException e) {
-
- throw new SAXException("write error",e);
+ throw new SAXException("write error", e);
}
}
-
+
protected void encodeAttributeValue(Attributes attributes, int idx) throws
SAXException, IOException {
this.outputWriter.write(C_QUOTE); // [']
- this.encode(attributes.getValue(idx));
+ this.encode(attributes.getValue(idx));
this.outputWriter.write(C_QUOTE); // [']
}
-
+
protected void encodeText(char[] chars, int start, int length) throws SAXException,
IOException {
- this.encode(chars, start, length);
+ this.encode(chars, start, length);
}
-
- /* (non-Javadoc)
+
+ /*
+ * (non-Javadoc)
* @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String,
java.lang.String)
*/
- public void startPrefixMapping(String prefix, String uri)
- throws SAXException {
+ public void startPrefixMapping(String prefix, String uri) throws SAXException {}
- }
-
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see org.xml.sax.ext.LexicalHandler#comment(char[], int, int)
*/
public void comment(char[] ch, int start, int length) throws SAXException {
- if (this.beforeDocumentStart || level < 0)
+ if (this.beforeDocumentStart || (level < 0)) {
return;
+ }
+
try {
- if (!this.closeElement(false) && level != 0) {
+ if (!this.closeElement(false) && (level != 0)) {
this.outputWriter.write(C_COMMA);
}
+
if (DEBUG) {
this.outputWriter.write('[');
this.outputWriter.write(Integer.toString(level));
this.outputWriter.write(']');
}
-// this.outputWriter.write(C_QUOTE);
+
+// this.outputWriter.write(C_QUOTE);
this.outputWriter.write(S_COMMENT_START);
this.encode(ch, start, length);
this.outputWriter.write(S_COMMENT_END);
-// this.outputWriter.write(C_QUOTE);
+
+// this.outputWriter.write(C_QUOTE);
} catch (IOException e) {
- throw new SAXException("Write error",e);
+ throw new SAXException("Write error", e);
}
+ }
-
- }
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see org.xml.sax.ext.LexicalHandler#endCDATA()
*/
public void endCDATA() throws SAXException {
- if (this.beforeDocumentStart || level < 0)
+ if (this.beforeDocumentStart || (level < 0)) {
return;
+ }
+
try {
if (this.closeElement(false)) {
return;
}
+
if (DEBUG) {
this.outputWriter.write('[');
this.outputWriter.write(Integer.toString(level));
this.outputWriter.write(']');
}
+
this.outputWriter.write(S_CDATA_END);
- this.processing_cdata = false;
+ this.processingCdata = false;
} catch (IOException e) {
- throw new SAXException("Write error",e);
+ throw new SAXException("Write error", e);
}
}
- /* (non-Javadoc)
+
+ /*
+ * (non-Javadoc)
* @see org.xml.sax.ext.LexicalHandler#endDTD()
*/
public void endDTD() throws SAXException {
+
// TODO Auto-generated method stub
+ }
- }
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see org.xml.sax.ext.LexicalHandler#endEntity(java.lang.String)
*/
public void endEntity(String name) throws SAXException {
+
// TODO Auto-generated method stub
+ }
- }
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see org.xml.sax.ext.LexicalHandler#startCDATA()
*/
public void startCDATA() throws SAXException {
- if (this.beforeDocumentStart || level < 0)
+ if (this.beforeDocumentStart || (level < 0)) {
return;
+ }
+
try {
- if (!this.closeElement(false) && level != 0) {
+ if (!this.closeElement(false) && (level != 0)) {
this.outputWriter.write(C_COMMA);
}
+
if (DEBUG) {
this.outputWriter.write('[');
this.outputWriter.write(Integer.toString(level));
this.outputWriter.write(']');
}
+
this.outputWriter.write(S_CDATA_START);
- this.processing_cdata = true;
+ this.processingCdata = true;
} catch (IOException e) {
- throw new SAXException("Write error",e);
+ throw new SAXException("Write error", e);
}
}
- /* (non-Javadoc)
+
+ /*
+ * (non-Javadoc)
* @see org.xml.sax.ext.LexicalHandler#startDTD(java.lang.String, java.lang.String,
java.lang.String)
*/
- public void startDTD(String name, String publicId, String systemId)
- throws SAXException {
+ public void startDTD(String name, String publicId, String systemId) throws
SAXException {
+
// TODO Auto-generated method stub
+ }
- }
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see org.xml.sax.ext.LexicalHandler#startEntity(java.lang.String)
*/
public void startEntity(String name) throws SAXException {
+
// TODO Auto-generated method stub
-
}
/*
* (non-Javadoc)
- *
+ *
* @see org.apache.cocoon.components.serializers.EncodingSerializer#writeIndent(int)
*/
protected void writeIndent(int indent) throws SAXException {
try {
this.outputWriter.write("\n".toCharArray(), 0, 1);
+
if (indent > 0) {
this.outputWriter.write(assureIndentBuffer(indent), 0, indent);
}
} catch (IOException e) {
- throw new SAXException("Write error",e);
+ throw new SAXException("Write error", e);
}
-
}
private char[] assureIndentBuffer(int size) {
- if (indentBuffer == null || indentBuffer.length < size) {
+ if ((indentBuffer == null) || (indentBuffer.length < size)) {
indentBuffer = new char[size];
Arrays.fill(indentBuffer, ' ');
}
+
return indentBuffer;
}
-
+
/**
* Encode and write a <code>String</code>
*/
- protected void encode(String data)
- throws SAXException {
- char array[] = data.toCharArray();
+ protected void encode(String data) throws SAXException {
+ char[] array = data.toCharArray();
+
this.encode(array, 0, array.length);
}
-
+
/**
* Encode and write an array of characters.
*/
- protected void encode(char data[])
- throws SAXException {
+ protected void encode(char[] data) throws SAXException {
this.encode(data, 0, data.length);
}
-
+
/**
* Encode and write a specific part of an array of characters.
*/
- protected void encode(char data[], int start, int length)
- throws SAXException {
+ protected void encode(char[] data, int start, int length) throws SAXException {
int end = start + length;
-
- if (data == null) throw new NullPointerException("Null data");
- if ((start < 0) || (start > data.length) || (length < 0) ||
- (end > data.length) || (end < 0))
+
+ if (data == null) {
+ throw new NullPointerException("Null data");
+ }
+
+ if ((start < 0) || (start > data.length) || (length < 0) || (end >
data.length) || (end < 0)) {
throw new IndexOutOfBoundsException("Invalid data");
- if (length == 0) return;
-
+ }
+
+ if (length == 0) {
+ return;
+ }
+
try {
for (int x = start; x < end; x++) {
char c = data[x];
-
- if ( JSContentHandler.encoder.compile(c)) {
+
+ if (JSContentHandler.ENCODER.compile(c)) {
continue;
}
-
- if (start != x) this.outputWriter.write(data, start, x - start );
- this.outputWriter.write(JSContentHandler.encoder.encode(c));
+
+ if (start != x) {
+ this.outputWriter.write(data, start, x - start);
+ }
+
+ this.outputWriter.write(JSContentHandler.ENCODER.encode(c));
start = x + 1;
+
continue;
}
- if (start != end) this.outputWriter.write(data, start, end - start );
+
+ if (start != end) {
+ this.outputWriter.write(data, start, end - start);
+ }
} catch (IOException e) {
- throw new SAXException("Write error",e);
+ throw new SAXException("Write error", e);
}
}
-
+
protected boolean isProcessingCdata() {
- return processing_cdata;
+ return processingCdata;
}
protected boolean isBeforeDocumentStart() {
- return beforeDocumentStart;
+ return beforeDocumentStart;
}
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONAccessor.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONAccessor.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONAccessor.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,51 +19,54 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.json;
import java.util.Collection;
import java.util.Map;
+final class JSONAccessor {
+ private JSONAccessor() {}
-class JSONAccessor {
- static boolean putValue(JSONObject object, String key, Object value) {
- try {
- if (value instanceof Boolean) {
- object.put(key, ((Boolean) value).booleanValue());
- } else if (value instanceof Double) {
- object.put(key, ((Double) value).doubleValue());
- } else if (value instanceof Integer) {
- object.put(key, ((Integer) value).intValue());
- } else if (value instanceof Long) {
- object.put(key, ((Long) value).longValue());
- } else if (value instanceof Collection) {
- object.put(key, (Collection) value);
- } else if (value instanceof Map) {
- object.put(key, (Map) value);
- } else {
- object.put(key, value);
- }
- } catch (JSONException e) {
- e.printStackTrace();
+ static boolean putValue(JSONObject object, String key, Object value) {
+ try {
+ if (value instanceof Boolean) {
+ object.put(key, ((Boolean) value).booleanValue());
+ } else if (value instanceof Double) {
+ object.put(key, ((Double) value).doubleValue());
+ } else if (value instanceof Integer) {
+ object.put(key, ((Integer) value).intValue());
+ } else if (value instanceof Long) {
+ object.put(key, ((Long) value).longValue());
+ } else if (value instanceof Collection) {
+ object.put(key, (Collection) value);
+ } else if (value instanceof Map) {
+ object.put(key, (Map) value);
+ } else {
+ object.put(key, value);
+ }
+ } catch (JSONException e) {
+ e.printStackTrace();
- return false;
- }
-
- //no exception - suppose it's added
- return true;
- }
+ return false;
+ }
- static Object unwrapValue(Object value) throws JSONException {
- if (value instanceof JSONObject) {
- return new JSONMap((JSONObject) value);
- } else if (value instanceof JSONArray) {
- return new JSONCollection((JSONArray) value);
- }
+ // no exception - suppose it's added
+ return true;
+ }
- return value;
- }
-
- static Object getValue(JSONObject object, String key) throws JSONException {
- return unwrapValue(object.get(key));
- }
-}
\ No newline at end of file
+ static Object unwrapValue(Object value) throws JSONException {
+ if (value instanceof JSONObject) {
+ return new JSONMap((JSONObject) value);
+ } else if (value instanceof JSONArray) {
+ return new JSONCollection((JSONArray) value);
+ }
+
+ return value;
+ }
+
+ static Object getValue(JSONObject object, String key) throws JSONException {
+ return unwrapValue(object.get(key));
+ }
+}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONArray.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONArray.java 2009-11-01
17:06:52 UTC (rev 15799)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONArray.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -23,10 +23,10 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
-
import java.io.IOException;
import java.io.Serializable;
import java.io.Writer;
+
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
@@ -77,23 +77,22 @@
* <li>Comments written in the slashshlash, slashstar, and hash conventions
* will be ignored.</li>
* </ul>
-
+ *
* @author
JSON.org
* @version 2
*/
public class JSONArray implements Serializable {
/**
- *
- */
- private static final long serialVersionUID = -5128849901663778859L;
-
- /**
+ *
+ */
+ private static final long serialVersionUID = -5128849901663778859L;
+
+ /**
* The arrayList where the JSONArray's properties are kept.
*/
private ArrayList myArrayList;
-
/**
* Construct an empty JSONArray.
*/
@@ -102,19 +101,31 @@
}
/**
+ * Construct a JSONArray from a Collection.
+ * @param collection A Collection.
+ */
+ public JSONArray(Collection collection) {
+ this.myArrayList = (collection == null) ? new ArrayList() : new
ArrayList(collection);
+ }
+
+ /**
* Construct a JSONArray from a JSONTokener.
* @param x A JSONTokener
* @throws JSONException If there is a syntax error.
*/
public JSONArray(JSONTokener x) throws JSONException {
this();
+
if (x.nextClean() != '[') {
throw x.syntaxError("A JSONArray text must start with
'['");
}
+
if (x.nextClean() == ']') {
return;
}
+
x.back();
+
for (;;) {
if (x.nextClean() == ',') {
x.back();
@@ -123,23 +134,27 @@
x.back();
this.myArrayList.add(x.nextValue());
}
+
switch (x.nextClean()) {
- case ';':
- case ',':
- if (x.nextClean() == ']') {
+ case ';' :
+ case ',' :
+ if (x.nextClean() == ']') {
+ return;
+ }
+
+ x.back();
+
+ break;
+
+ case ']' :
return;
- }
- x.back();
- break;
- case ']':
- return;
- default:
- throw x.syntaxError("Expected a ',' or ']'");
+
+ default :
+ throw x.syntaxError("Expected a ',' or
']'");
}
}
}
-
/**
* Construct a JSONArray from a source sJSON text.
* @param string A string that begins with
@@ -151,19 +166,7 @@
this(new JSONTokener(string));
}
-
/**
- * Construct a JSONArray from a Collection.
- * @param collection A Collection.
- */
- public JSONArray(Collection collection) {
- this.myArrayList = (collection == null) ?
- new ArrayList() :
- new ArrayList(collection);
- }
-
-
- /**
* Get the object value associated with an index.
* @param index
* The index must be between 0 and length() - 1.
@@ -172,13 +175,14 @@
*/
public Object get(int index) throws JSONException {
Object o = opt(index);
+
if (o == null) {
throw new JSONException("JSONArray[" + index + "] not
found.");
}
+
return o;
}
-
/**
* Get the boolean value associated with an index.
* The string values "true" and "false" are converted to
boolean.
@@ -190,19 +194,16 @@
*/
public boolean getBoolean(int index) throws JSONException {
Object o = get(index);
- if (o.equals(Boolean.FALSE) ||
- (o instanceof String &&
- ((String)o).equalsIgnoreCase("false"))) {
+
+ if (o.equals(Boolean.FALSE) || ((o instanceof String) && ((String)
o).equalsIgnoreCase("false"))) {
return false;
- } else if (o.equals(Boolean.TRUE) ||
- (o instanceof String &&
- ((String)o).equalsIgnoreCase("true"))) {
+ } else if (o.equals(Boolean.TRUE) || ((o instanceof String) && ((String)
o).equalsIgnoreCase("true"))) {
return true;
}
+
throw new JSONException("JSONArray[" + index + "] is not a
Boolean.");
}
-
/**
* Get the double value associated with an index.
*
@@ -213,17 +214,14 @@
*/
public double getDouble(int index) throws JSONException {
Object o = get(index);
+
try {
- return o instanceof Number ?
- ((Number)o).doubleValue() :
- Double.valueOf((String)o).doubleValue();
+ return (o instanceof Number) ? ((Number) o).doubleValue() :
Double.valueOf((String) o).doubleValue();
} catch (Exception e) {
- throw new JSONException("JSONArray[" + index +
- "] is not a number.");
+ throw new JSONException("JSONArray[" + index + "] is not a
number.");
}
}
-
/**
* Get the int value associated with an index.
*
@@ -235,11 +233,10 @@
*/
public int getInt(int index) throws JSONException {
Object o = get(index);
- return o instanceof Number ?
- ((Number)o).intValue() : (int)getDouble(index);
+
+ return (o instanceof Number) ? ((Number) o).intValue() : (int) getDouble(index);
}
-
/**
* Get the JSONArray associated with an index.
* @param index The index must be between 0 and length() - 1.
@@ -249,14 +246,14 @@
*/
public JSONArray getJSONArray(int index) throws JSONException {
Object o = get(index);
+
if (o instanceof JSONArray) {
- return (JSONArray)o;
+ return (JSONArray) o;
}
- throw new JSONException("JSONArray[" + index +
- "] is not a JSONArray.");
+
+ throw new JSONException("JSONArray[" + index + "] is not a
JSONArray.");
}
-
/**
* Get the JSONObject associated with an index.
* @param index subscript
@@ -266,14 +263,14 @@
*/
public JSONObject getJSONObject(int index) throws JSONException {
Object o = get(index);
+
if (o instanceof JSONObject) {
- return (JSONObject)o;
+ return (JSONObject) o;
}
- throw new JSONException("JSONArray[" + index +
- "] is not a JSONObject.");
+
+ throw new JSONException("JSONArray[" + index + "] is not a
JSONObject.");
}
-
/**
* Get the long value associated with an index.
*
@@ -284,11 +281,10 @@
*/
public long getLong(int index) throws JSONException {
Object o = get(index);
- return o instanceof Number ?
- ((Number)o).longValue() : (long)getDouble(index);
+
+ return (o instanceof Number) ? ((Number) o).longValue() : (long)
getDouble(index);
}
-
/**
* Get the string associated with an index.
* @param index The index must be between 0 and length() - 1.
@@ -299,7 +295,6 @@
return get(index).toString();
}
-
/**
* Determine if the value is null.
* @param index The index must be between 0 and length() - 1.
@@ -309,7 +304,6 @@
return JSONObject.NULL.equals(opt(index));
}
-
/**
* Make a string from the contents of this JSONArray. The
* <code>separator</code> string is inserted between each element.
@@ -326,12 +320,13 @@
if (i > 0) {
sb.append(separator);
}
+
sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
}
+
return sb.toString();
}
-
/**
* Get the number of elements in the JSONArray, included nulls.
*
@@ -341,7 +336,6 @@
return this.myArrayList.size();
}
-
/**
* Get the optional object value associated with an index.
* @param index The index must be between 0 and length() - 1.
@@ -349,11 +343,9 @@
* object at that index.
*/
public Object opt(int index) {
- return (index < 0 || index >= length()) ?
- null : this.myArrayList.get(index);
+ return ((index < 0) || (index >= length())) ? null :
this.myArrayList.get(index);
}
-
/**
* Get the optional boolean value associated with an index.
* It returns false if there is no value at that index,
@@ -362,11 +354,10 @@
* @param index The index must be between 0 and length() - 1.
* @return The truth.
*/
- public boolean optBoolean(int index) {
+ public boolean optBoolean(int index) {
return optBoolean(index, false);
}
-
/**
* Get the optional boolean value associated with an index.
* It returns the defaultValue if there is no value at that index or if
@@ -376,7 +367,7 @@
* @param defaultValue A boolean default.
* @return The truth.
*/
- public boolean optBoolean(int index, boolean defaultValue) {
+ public boolean optBoolean(int index, boolean defaultValue) {
try {
return getBoolean(index);
} catch (Exception e) {
@@ -384,7 +375,6 @@
}
}
-
/**
* Get the optional double value associated with an index.
* NaN is returned if there is no value for the index,
@@ -397,7 +387,6 @@
return optDouble(index, Double.NaN);
}
-
/**
* Get the optional double value associated with an index.
* The defaultValue is returned if there is no value for the index,
@@ -415,7 +404,6 @@
}
}
-
/**
* Get the optional int value associated with an index.
* Zero is returned if there is no value for the index,
@@ -428,7 +416,6 @@
return optInt(index, 0);
}
-
/**
* Get the optional int value associated with an index.
* The defaultValue is returned if there is no value for the index,
@@ -445,7 +432,6 @@
}
}
-
/**
* Get the optional JSONArray associated with an index.
* @param index subscript
@@ -454,10 +440,10 @@
*/
public JSONArray optJSONArray(int index) {
Object o = opt(index);
- return o instanceof JSONArray ? (JSONArray)o : null;
+
+ return (o instanceof JSONArray) ? (JSONArray) o : null;
}
-
/**
* Get the optional JSONObject associated with an index.
* Null is returned if the key is not found, or null if the index has
@@ -468,10 +454,10 @@
*/
public JSONObject optJSONObject(int index) {
Object o = opt(index);
- return o instanceof JSONObject ? (JSONObject)o : null;
+
+ return (o instanceof JSONObject) ? (JSONObject) o : null;
}
-
/**
* Get the optional long value associated with an index.
* Zero is returned if there is no value for the index,
@@ -484,7 +470,6 @@
return optLong(index, 0);
}
-
/**
* Get the optional long value associated with an index.
* The defaultValue is returned if there is no value for the index,
@@ -501,7 +486,6 @@
}
}
-
/**
* Get the optional string value associated with an index. It returns an
* empty string if there is no value at that index. If the value
@@ -514,7 +498,6 @@
return optString(index, "");
}
-
/**
* Get the optional string associated with an index.
* The defaultValue is returned if the key is not found.
@@ -525,10 +508,10 @@
*/
public String optString(int index, String defaultValue) {
Object o = opt(index);
- return o != null ? o.toString() : defaultValue;
+
+ return (o != null) ? o.toString() : defaultValue;
}
-
/**
* Append a boolean value. This increases the array's length by one.
*
@@ -537,21 +520,21 @@
*/
public JSONArray put(boolean value) {
put(value ? Boolean.TRUE : Boolean.FALSE);
+
return this;
}
-
/**
* Put a value in the JSONArray, where the value will be a
* JSONArray which is produced from a Collection.
- * @param value A Collection value.
- * @return this.
+ * @param value A Collection value.
+ * @return this.
*/
public JSONArray put(Collection value) {
put(new JSONArray(value));
+
return this;
}
-
/**
* Append a double value. This increases the array's length by one.
@@ -562,12 +545,13 @@
*/
public JSONArray put(double value) throws JSONException {
Double d = new Double(value);
+
JSONObject.testValidity(d);
put(d);
+
return this;
}
-
/**
* Append an int value. This increases the array's length by one.
*
@@ -576,10 +560,10 @@
*/
public JSONArray put(int value) {
put(new Integer(value));
+
return this;
}
-
/**
* Append an long value. This increases the array's length by one.
*
@@ -588,22 +572,22 @@
*/
public JSONArray put(long value) {
put(new Long(value));
+
return this;
}
-
/**
* Put a value in the JSONArray, where the value will be a
* JSONObject which is produced from a Map.
- * @param value A Map value.
- * @return this.
+ * @param value A Map value.
+ * @return this.
*/
public JSONArray put(Map value) {
put(new JSONObject(value));
+
return this;
}
-
-
+
/**
* Append an object value. This increases the array's length by one.
* @param value An object value. The value should be a
@@ -613,10 +597,10 @@
*/
public JSONArray put(Object value) {
this.myArrayList.add(value);
+
return this;
}
-
/**
* Put or replace a boolean value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
@@ -628,25 +612,25 @@
*/
public JSONArray put(int index, boolean value) throws JSONException {
put(index, value ? Boolean.TRUE : Boolean.FALSE);
+
return this;
}
-
/**
* Put a value in the JSONArray, where the value will be a
* JSONArray which is produced from a Collection.
* @param index The subscript.
- * @param value A Collection value.
- * @return this.
+ * @param value A Collection value.
+ * @return this.
* @throws JSONException If the index is negative or if the value is
* not finite.
*/
public JSONArray put(int index, Collection value) throws JSONException {
put(index, new JSONArray(value));
+
return this;
}
-
/**
* Put or replace a double value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad
@@ -659,10 +643,10 @@
*/
public JSONArray put(int index, double value) throws JSONException {
put(index, new Double(value));
+
return this;
}
-
/**
* Put or replace an int value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad
@@ -674,10 +658,10 @@
*/
public JSONArray put(int index, int value) throws JSONException {
put(index, new Integer(value));
+
return this;
}
-
/**
* Put or replace a long value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad
@@ -689,25 +673,25 @@
*/
public JSONArray put(int index, long value) throws JSONException {
put(index, new Long(value));
+
return this;
}
-
/**
* Put a value in the JSONArray, where the value will be a
* JSONObject which is produced from a Map.
* @param index The subscript.
- * @param value The Map value.
- * @return this.
+ * @param value The Map value.
+ * @return this.
* @throws JSONException If the index is negative or if the the value is
* an invalid number.
*/
public JSONArray put(int index, Map value) throws JSONException {
put(index, new JSONObject(value));
+
return this;
}
-
-
+
/**
* Put or replace an object value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
@@ -722,21 +706,24 @@
*/
public JSONArray put(int index, Object value) throws JSONException {
JSONObject.testValidity(value);
+
if (index < 0) {
throw new JSONException("JSONArray[" + index + "] not
found.");
}
+
if (index < length()) {
this.myArrayList.set(index, value);
} else {
while (index != length()) {
put(JSONObject.NULL);
}
+
put(value);
}
+
return this;
}
-
/**
* Produce a JSONObject by combining a JSONArray of names with the values
* of this JSONArray.
@@ -747,17 +734,19 @@
* @throws JSONException If any of the names are null.
*/
public JSONObject toJSONObject(JSONArray names) throws JSONException {
- if (names == null || names.length() == 0 || length() == 0) {
+ if ((names == null) || (names.length() == 0) || (length() == 0)) {
return null;
}
+
JSONObject jo = new JSONObject();
+
for (int i = 0; i < names.length(); i += 1) {
jo.put(names.getString(i), this.opt(i));
}
+
return jo;
}
-
/**
* Make a JSON text of this JSONArray. For compactness, no
* unnecessary whitespace is added. If it is not possible to produce a
@@ -777,7 +766,6 @@
}
}
-
/**
* Make a prettyprinted JSON text of this JSONArray.
* Warning: This method assumes that the data structure is acyclical.
@@ -793,7 +781,6 @@
return toString(indentFactor, 0);
}
-
/**
* Make a prettyprinted JSON text of this JSONArray.
* Warning: This method assumes that the data structure is acyclical.
@@ -806,37 +793,45 @@
*/
String toString(int indentFactor, int indent) throws JSONException {
int len = length();
+
if (len == 0) {
return "[]";
}
+
int i;
StringBuffer sb = new StringBuffer("[");
+
if (len == 1) {
- sb.append(JSONObject.valueToString(this.myArrayList.get(0),
- indentFactor, indent));
+ sb.append(JSONObject.valueToString(this.myArrayList.get(0), indentFactor,
indent));
} else {
int newindent = indent + indentFactor;
+
sb.append('\n');
+
for (i = 0; i < len; i += 1) {
if (i > 0) {
sb.append(",\n");
}
+
for (int j = 0; j < newindent; j += 1) {
sb.append(' ');
}
- sb.append(JSONObject.valueToString(this.myArrayList.get(i),
- indentFactor, newindent));
+
+ sb.append(JSONObject.valueToString(this.myArrayList.get(i), indentFactor,
newindent));
}
+
sb.append('\n');
+
for (i = 0; i < indent; i += 1) {
sb.append(' ');
}
}
+
sb.append(']');
+
return sb.toString();
}
-
/**
* Write the contents of the JSONArray as JSON text to a writer.
* For compactness, no whitespace is added.
@@ -849,7 +844,7 @@
public Writer write(Writer writer) throws JSONException {
try {
boolean b = false;
- int len = length();
+ int len = length();
writer.write('[');
@@ -857,20 +852,25 @@
if (b) {
writer.write(',');
}
+
Object v = this.myArrayList.get(i);
+
if (v instanceof JSONObject) {
- ((JSONObject)v).write(writer);
+ ((JSONObject) v).write(writer);
} else if (v instanceof JSONArray) {
- ((JSONArray)v).write(writer);
+ ((JSONArray) v).write(writer);
} else {
writer.write(JSONObject.valueToString(v));
}
+
b = true;
}
+
writer.write(']');
+
return writer;
} catch (IOException e) {
- throw new JSONException(e);
+ throw new JSONException(e);
}
}
-}
\ No newline at end of file
+}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONCollection.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONCollection.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONCollection.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,73 +19,67 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.json;
import java.io.Serializable;
+
import java.util.AbstractCollection;
import java.util.Iterator;
-
/**
* @author Nick Belaevski - nbelaevski(a)exadel.com
* created 15.12.2006
- *
+ *
*/
public class JSONCollection extends AbstractCollection implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = 3192118108278773579L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = 3192118108278773579L;
+ private JSONArray array;
- private JSONArray array;
-
- public JSONCollection() throws JSONException {
- super();
-
- this.array = new JSONArray();
- }
-
- public JSONCollection(String jsonString) throws JSONException {
- super();
-
- this.array = new JSONArray(jsonString);
- }
+ public JSONCollection() throws JSONException {
+ super();
+ this.array = new JSONArray();
+ }
- public JSONCollection(JSONArray array) throws JSONException {
- super();
+ public JSONCollection(JSONArray array) throws JSONException {
+ super();
+ this.array = array;
+ }
- this.array = array;
- }
+ public JSONCollection(String jsonString) throws JSONException {
+ super();
+ this.array = new JSONArray(jsonString);
+ }
- public Iterator iterator() {
- return new Iterator() {
- int index = 0;
-
- public boolean hasNext() {
- return index < array.length();
- }
+ public Iterator iterator() {
+ return new Iterator() {
+ int index = 0;
+ public boolean hasNext() {
+ return index < array.length();
+ }
+ public Object next() {
+ try {
+ return JSONAccessor.unwrapValue(array.get(index++));
+ } catch (JSONException e) {
- public Object next() {
- try {
- return JSONAccessor.unwrapValue(array.get(index++));
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
+ // TODO Auto-generated catch block
+ e.printStackTrace();
- throw new RuntimeException();
- }
- }
+ throw new RuntimeException();
+ }
+ }
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ };
+ }
- public void remove() {
- throw new UnsupportedOperationException();
- }
-
- };
- }
-
- public int size() {
- return array.length();
- }
-
+ public int size() {
+ return array.length();
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONException.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONException.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONException.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.json;
/**
@@ -27,17 +29,17 @@
* @version 2
*/
public class JSONException extends Exception {
+
/**
- *
- */
- private static final long serialVersionUID = 2464742309018240317L;
-
- private Throwable cause;
+ *
+ */
+ private static final long serialVersionUID = 2464742309018240317L;
+ private Throwable cause;
- public JSONException() {
- super();
- }
-
+ public JSONException() {
+ super();
+ }
+
/**
* Constructs a JSONException with an explanatory message.
* @param message Detail about the reason for the exception.
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONMap.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONMap.java 2009-11-01
17:06:52 UTC (rev 15799)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONMap.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,133 +19,116 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.json;
import java.io.Serializable;
-import java.util.AbstractMap;
-import java.util.AbstractSet;
-import java.util.Iterator;
-import java.util.Set;
+import java.util.*;
/**
* @author Nick Belaevski - nbelaevski(a)exadel.com
* created 15.12.2006
- *
+ *
*/
public class JSONMap extends AbstractMap implements Serializable {
+ private static final long serialVersionUID = 2898468948832273123L;
+ private JSONObject jsonObject;
- /**
- *
- */
- private static final long serialVersionUID = 2898468948832273123L;
+ public JSONMap() throws JSONException {
+ super();
+ this.jsonObject = new JSONObject();
+ }
- private JSONObject jsonObject;
+ public JSONMap(JSONObject object) {
+ super();
+ this.jsonObject = object;
+ }
- public JSONMap() throws JSONException {
- super();
+ public JSONMap(String jsonString) throws JSONException {
+ super();
+ this.jsonObject = new JSONObject(jsonString);
+ }
- this.jsonObject = new JSONObject();
- }
+ @Override
+ public Set entrySet() {
+ return new MyAbstractSet();
+ }
- public JSONMap(String jsonString) throws JSONException {
- super();
+ @Override
+ public Object put(Object key, Object value) {
+ String keyString = key.toString();
- this.jsonObject = new JSONObject(jsonString);
- }
+ try {
+ Object previousValue = JSONAccessor.getValue(jsonObject, keyString);
- public JSONMap(JSONObject object) {
- super();
-
- this.jsonObject = object;
- }
+ JSONAccessor.putValue(jsonObject, keyString, value);
- public Set entrySet() {
- return new AbstractSet() {
+ return previousValue;
+ } catch (JSONException e) {
+ throw new RuntimeException(e.getMessage(), e);
+ }
+ }
- public Iterator iterator() {
- return new Iterator() {
+ public String getString() throws JSONException {
+ return jsonObject.toString(0);
+ }
- private Iterator keys = jsonObject.keys();
- private String currentName;
+ public String getString(int indentFactor) throws JSONException {
+ return jsonObject.toString(indentFactor);
+ }
- public boolean hasNext() {
- return keys.hasNext();
- }
+ private class MyAbstractSet extends AbstractSet {
+ @Override
+ public Iterator iterator() {
+ return new MyIterator();
+ }
- public Object next() {
- currentName = (String) keys.next();
+ @Override
+ public int size() {
+ return jsonObject.length();
+ }
- return new Entry() {
+ @Override
+ public boolean add(Object o) {
+ Entry entry = (Entry) o;
- private String key = currentName;
+ return JSONAccessor.putValue(jsonObject, (String) entry.getKey(),
entry.getValue());
+ }
- public Object getKey() {
- return key;
- }
+ private class MyIterator implements Iterator {
+ private Iterator keys = jsonObject.keys();
+ private String currentName;
- public Object getValue() {
- try {
- return JSONAccessor.getValue(jsonObject, this.key);
- } catch (JSONException e) {
- throw new RuntimeException(e.getMessage(), e);
- }
- }
+ public boolean hasNext() {
+ return keys.hasNext();
+ }
- public Object setValue(Object value) {
- throw new UnsupportedOperationException();
- }
+ public Object next() {
+ currentName = (String) keys.next();
- };
- }
+ return new Entry() {
+ private String key = currentName;
+ public Object getKey() {
+ return key;
+ }
+ public Object getValue() {
+ try {
+ return JSONAccessor.getValue(jsonObject, this.key);
+ } catch (JSONException e) {
+ throw new RuntimeException(e.getMessage(), e);
+ }
+ }
+ public Object setValue(Object value) {
+ throw new UnsupportedOperationException();
+ }
+ };
+ }
- public void remove() {
- throw new UnsupportedOperationException();
- }
-
- };
- }
-
- public int size() {
- return jsonObject.length();
- }
-
- public boolean add(Object o) {
- Entry entry = (Entry) o;
- return JSONAccessor.putValue(jsonObject, (String) entry.getKey(), entry.getValue());
- }
- };
- }
-
- public Object put(Object key, Object value) {
- String keyString = key.toString();
- try {
- Object previousValue = JSONAccessor.getValue(jsonObject, keyString);
- JSONAccessor.putValue(jsonObject, keyString, value);
-
- return previousValue;
- } catch (JSONException e) {
- throw new RuntimeException(e.getMessage(), e);
- }
- }
-
- public String getString() throws JSONException {
- return jsonObject.toString(0);
- }
-
- public String getString(int indentFactor) throws JSONException {
- return jsonObject.toString(indentFactor);
- }
-
-// public static void main(String[] args) throws Exception {
-// String json = "{ test1: 'test string', test2: [15, 45, 28], test3: {
innerMap1: { prop1: '1', prop2: true }, innerProp1: [12, 2] } }";
-// JSONMap map = new JSONMap(json);
-// System.out.println(map.get("test1"));
-// System.out.println("next >>>>>>>>");
-// System.out.println(map.get("test2"));
-// System.out.println("next >>>>>>>>");
-// System.out.println(map.get("test3"));
-// }
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ }
+ }
}
-
-
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONObject.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONObject.java 2009-11-01
17:06:52 UTC (rev 15799)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONObject.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -23,12 +23,13 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
-
import java.io.IOException;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.io.Writer;
+
import java.lang.reflect.Field;
+
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
@@ -90,69 +91,6 @@
public class JSONObject implements Serializable {
/**
- *
- */
- private static final long serialVersionUID = -3779657348977645510L;
-
- /**
- * JSONObject.NULL is equivalent to the value that JavaScript calls null,
- * whilst Java's null is equivalent to the value that JavaScript calls
- * undefined.
- */
- private static final class Null implements Serializable {
-
- /**
- *
- */
- private static final long serialVersionUID = -1155578668810010644L;
-
- protected Null() {
- super();
- }
-
- /**
- * There is only intended to be a single instance of the NULL object,
- * so the clone method returns itself.
- * @return NULL.
- */
- protected final Object clone() {
- return this;
- }
-
-
- /**
- * A Null object is equal to the null value and to itself.
- * @param object An object to test for nullness.
- * @return true if the object parameter is the JSONObject.NULL object
- * or null.
- */
- public boolean equals(Object object) {
- return object == null || object == this;
- }
-
-
- /**
- * Get the "null" string value.
- * @return The string "null".
- */
- public String toString() {
- return "null";
- }
-
- private Object readResolve() throws ObjectStreamException {
- return NULL;
- }
-
- }
-
-
- /**
- * The hash map where the JSONObject's properties are kept.
- */
- private HashMap myHashMap;
-
-
- /**
* It is sometimes more convenient and less ambiguous to have a
* <code>NULL</code> object than to use Java's
<code>null</code> value.
* <code>JSONObject.NULL.equals(null)</code> returns
<code>true</code>.
@@ -160,61 +98,58 @@
*/
public static final Object NULL = new Null();
+ /**
+ *
+ */
+ private static final long serialVersionUID = -3779657348977645510L;
/**
+ * The hash map where the JSONObject's properties are kept.
+ */
+ private Map myHashMap;
+
+ /**
* Construct an empty JSONObject.
*/
public JSONObject() {
this.myHashMap = new HashMap();
}
-
/**
- * Construct a JSONObject from a subset of another JSONObject.
- * An array of strings is used to identify the keys that should be copied.
- * Missing keys are ignored.
- * @param jo A JSONObject.
- * @param sa An array of strings.
- * @exception JSONException If a value is a non-finite number.
- */
- public JSONObject(JSONObject jo, String[] sa) throws JSONException {
- this();
- for (int i = 0; i < sa.length; i += 1) {
- putOpt(sa[i], jo.opt(sa[i]));
- }
- }
-
-
- /**
* Construct a JSONObject from a JSONTokener.
* @param x A JSONTokener object containing the source string.
* @throws JSONException If there is a syntax error in the source string.
*/
public JSONObject(JSONTokener x) throws JSONException {
this();
+
char c;
String key;
if (x.nextClean() != '{') {
throw x.syntaxError("A JSONObject text must begin with
'{'");
}
+
for (;;) {
c = x.nextClean();
+
switch (c) {
- case 0:
- throw x.syntaxError("A JSONObject text must end with
'}'");
- case '}':
- return;
- default:
- x.back();
- key = x.nextValue().toString();
+ case 0 :
+ throw x.syntaxError("A JSONObject text must end with
'}'");
+
+ case '}' :
+ return;
+
+ default :
+ x.back();
+ key = x.nextValue().toString();
}
/*
* The key is followed by ':'. We will also tolerate '=' or
'=>'.
*/
+ c = x.nextClean();
- c = x.nextClean();
if (c == '=') {
if (x.next() != '>') {
x.back();
@@ -222,42 +157,70 @@
} else if (c != ':') {
throw x.syntaxError("Expected a ':' after a key");
}
+
put(key, x.nextValue());
/*
* Pairs are separated by ','. We will also tolerate ';'.
*/
+ switch (x.nextClean()) {
+ case ';' :
+ case ',' :
+ if (x.nextClean() == '}') {
+ return;
+ }
- switch (x.nextClean()) {
- case ';':
- case ',':
- if (x.nextClean() == '}') {
+ x.back();
+
+ break;
+
+ case '}' :
return;
- }
- x.back();
- break;
- case '}':
- return;
- default:
- throw x.syntaxError("Expected a ',' or '}'");
+
+ default :
+ throw x.syntaxError("Expected a ',' or
'}'");
}
}
}
-
/**
* Construct a JSONObject from a Map.
* @param map A map object that can be used to initialize the contents of
* the JSONObject.
*/
public JSONObject(Map map) {
- this.myHashMap = (map == null) ?
- new HashMap() :
- new HashMap(map);
+ this.myHashMap = (map == null) ? new HashMap() : new HashMap(map);
}
-
/**
+ * Construct a JSONObject from a string.
+ * This is the most commonly used JSONObject constructor.
+ * @param string A string beginning
+ * with <code>{</code> <small>(left brace)</small>
and ending
+ * with <code>}</code> <small>(right
brace)</small>.
+ * @exception JSONException If there is a syntax error in the source string.
+ */
+ public JSONObject(String string) throws JSONException {
+ this(new JSONTokener(string));
+ }
+
+ /**
+ * Construct a JSONObject from a subset of another JSONObject.
+ * An array of strings is used to identify the keys that should be copied.
+ * Missing keys are ignored.
+ * @param jo A JSONObject.
+ * @param sa An array of strings.
+ * @exception JSONException If a value is a non-finite number.
+ */
+ public JSONObject(JSONObject jo, String[] sa) throws JSONException {
+ this();
+
+ for (int i = 0; i < sa.length; i += 1) {
+ putOpt(sa[i], jo.opt(sa[i]));
+ }
+ }
+
+ /**
* Construct a JSONObject from an Object, using reflection to find the
* public members. The resulting JSONObject's keys will be the strings
* from the names array, and the values will be the field values associated
@@ -268,35 +231,25 @@
* @param names An array of strings, the names of the fields to be used
* from the object.
*/
- public JSONObject(Object object, String names[]) {
- this();
- Class c = object.getClass();
- for (int i = 0; i < names.length; i += 1) {
- try {
- String name = names[i];
- Field field = c.getField(name);
- Object value = field.get(object);
- this.put(name, value);
- } catch (Exception e) {
- /* forget about it */
- }
- }
- }
+ public JSONObject(Object object, String[] names) {
+ this();
+ Class c = object.getClass();
- /**
- * Construct a JSONObject from a string.
- * This is the most commonly used JSONObject constructor.
- * @param string A string beginning
- * with <code>{</code> <small>(left brace)</small>
and ending
- * with <code>}</code> <small>(right
brace)</small>.
- * @exception JSONException If there is a syntax error in the source string.
- */
- public JSONObject(String string) throws JSONException {
- this(new JSONTokener(string));
+ for (int i = 0; i < names.length; i += 1) {
+ try {
+ String name = names[i];
+ Field field = c.getField(name);
+ Object value = field.get(object);
+
+ this.put(name, value);
+ } catch (Exception e) {
+
+ /* forget about it */
+ }
+ }
}
-
/**
* Accumulate values under a key. It is similar to the put method except
* that if there is already an object stored under the key then a
@@ -309,23 +262,22 @@
* @throws JSONException If the value is an invalid number
* or if the key is null.
*/
- public JSONObject accumulate(String key, Object value)
- throws JSONException {
+ public JSONObject accumulate(String key, Object value) throws JSONException {
testValidity(value);
+
Object o = opt(key);
+
if (o == null) {
- put(key, value instanceof JSONArray ?
- new JSONArray().put(value) :
- value);
+ put(key, (value instanceof JSONArray) ? new JSONArray().put(value) : value);
} else if (o instanceof JSONArray) {
- ((JSONArray)o).put(value);
+ ((JSONArray) o).put(value);
} else {
put(key, new JSONArray().put(o).put(value));
}
+
return this;
}
-
/**
* Append values to the array under a key. If the key does not exist in the
* JSONObject, then the key is put in the JSONObject with its value being a
@@ -334,51 +286,52 @@
* @param key A key string.
* @param value An object to be accumulated under the key.
* @return this.
- * @throws JSONException If the key is null or if the current value
- * associated with the key is not a JSONArray.
+ * @throws JSONException If the key is null or if the current value
+ * associated with the key is not a JSONArray.
*/
- public JSONObject append(String key, Object value)
- throws JSONException {
+ public JSONObject append(String key, Object value) throws JSONException {
testValidity(value);
+
Object o = opt(key);
+
if (o == null) {
put(key, new JSONArray().put(value));
} else if (o instanceof JSONArray) {
- put(key, ((JSONArray)o).put(value));
+ put(key, ((JSONArray) o).put(value));
} else {
- throw new JSONException("JSONObject[" + key +
- "] is not a JSONArray.");
+ throw new JSONException("JSONObject[" + key + "] is not a
JSONArray.");
}
+
return this;
}
-
/**
* Produce a string from a double. The string "null" will be returned if
* the number is not finite.
* @param d A double.
* @return A String.
*/
- static public String doubleToString(double d) {
+ public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
- return "null";
+ return "null";
}
-// Shave off trailing zeros and decimal point, if possible.
+// Shave off trailing zeros and decimal point, if possible.
+ String s = Double.toString(d);
- String s = Double.toString(d);
- if (s.indexOf('.') > 0 && s.indexOf('e') < 0
&& s.indexOf('E') < 0) {
+ if ((s.indexOf('.') > 0) && (s.indexOf('e') < 0)
&& (s.indexOf('E') < 0)) {
while (s.endsWith("0")) {
s = s.substring(0, s.length() - 1);
}
+
if (s.endsWith(".")) {
s = s.substring(0, s.length() - 1);
}
}
+
return s;
}
-
/**
* Get the value object associated with a key.
*
@@ -388,14 +341,14 @@
*/
public Object get(String key) throws JSONException {
Object o = opt(key);
+
if (o == null) {
- throw new JSONException("JSONObject[" + quote(key) +
- "] not found.");
+ throw new JSONException("JSONObject[" + quote(key) + "] not
found.");
}
+
return o;
}
-
/**
* Get the boolean value associated with a key.
*
@@ -406,20 +359,16 @@
*/
public boolean getBoolean(String key) throws JSONException {
Object o = get(key);
- if (o.equals(Boolean.FALSE) ||
- (o instanceof String &&
- ((String)o).equalsIgnoreCase("false"))) {
+
+ if (o.equals(Boolean.FALSE) || ((o instanceof String) && ((String)
o).equalsIgnoreCase("false"))) {
return false;
- } else if (o.equals(Boolean.TRUE) ||
- (o instanceof String &&
- ((String)o).equalsIgnoreCase("true"))) {
+ } else if (o.equals(Boolean.TRUE) || ((o instanceof String) && ((String)
o).equalsIgnoreCase("true"))) {
return true;
}
- throw new JSONException("JSONObject[" + quote(key) +
- "] is not a Boolean.");
+
+ throw new JSONException("JSONObject[" + quote(key) + "] is not a
Boolean.");
}
-
/**
* Get the double value associated with a key.
* @param key A key string.
@@ -429,17 +378,14 @@
*/
public double getDouble(String key) throws JSONException {
Object o = get(key);
+
try {
- return o instanceof Number ?
- ((Number)o).doubleValue() :
- Double.valueOf((String)o).doubleValue();
+ return (o instanceof Number) ? ((Number) o).doubleValue() :
Double.valueOf((String) o).doubleValue();
} catch (Exception e) {
- throw new JSONException("JSONObject[" + quote(key) +
- "] is not a number.");
+ throw new JSONException("JSONObject[" + quote(key) + "] is not
a number.");
}
}
-
/**
* Get the int value associated with a key. If the number value is too
* large for an int, it will be clipped.
@@ -451,11 +397,10 @@
*/
public int getInt(String key) throws JSONException {
Object o = get(key);
- return o instanceof Number ?
- ((Number)o).intValue() : (int)getDouble(key);
+
+ return (o instanceof Number) ? ((Number) o).intValue() : (int) getDouble(key);
}
-
/**
* Get the JSONArray value associated with a key.
*
@@ -466,14 +411,14 @@
*/
public JSONArray getJSONArray(String key) throws JSONException {
Object o = get(key);
+
if (o instanceof JSONArray) {
- return (JSONArray)o;
+ return (JSONArray) o;
}
- throw new JSONException("JSONObject[" + quote(key) +
- "] is not a JSONArray.");
+
+ throw new JSONException("JSONObject[" + quote(key) + "] is not a
JSONArray.");
}
-
/**
* Get the JSONObject value associated with a key.
*
@@ -484,14 +429,14 @@
*/
public JSONObject getJSONObject(String key) throws JSONException {
Object o = get(key);
+
if (o instanceof JSONObject) {
- return (JSONObject)o;
+ return (JSONObject) o;
}
- throw new JSONException("JSONObject[" + quote(key) +
- "] is not a JSONObject.");
+
+ throw new JSONException("JSONObject[" + quote(key) + "] is not a
JSONObject.");
}
-
/**
* Get the long value associated with a key. If the number value is too
* long for a long, it will be clipped.
@@ -503,11 +448,10 @@
*/
public long getLong(String key) throws JSONException {
Object o = get(key);
- return o instanceof Number ?
- ((Number)o).longValue() : (long)getDouble(key);
+
+ return (o instanceof Number) ? ((Number) o).longValue() : (long) getDouble(key);
}
-
/**
* Get the string associated with a key.
*
@@ -519,7 +463,6 @@
return get(key).toString();
}
-
/**
* Determine if the JSONObject contains a specific key.
* @param key A key string.
@@ -529,7 +472,6 @@
return this.myHashMap.containsKey(key);
}
-
/**
* Determine if the value associated with the key is null or if there is
* no value.
@@ -541,7 +483,6 @@
return JSONObject.NULL.equals(opt(key));
}
-
/**
* Get an enumeration of the keys of the JSONObject.
*
@@ -551,7 +492,6 @@
return this.myHashMap.keySet().iterator();
}
-
/**
* Get the number of keys stored in the JSONObject.
*
@@ -561,7 +501,6 @@
return this.myHashMap.size();
}
-
/**
* Produce a JSONArray containing the names of the elements of this
* JSONObject.
@@ -570,11 +509,13 @@
*/
public JSONArray names() {
JSONArray ja = new JSONArray();
- Iterator keys = keys();
+ Iterator keys = keys();
+
while (keys.hasNext()) {
ja.put(keys.next());
}
- return ja.length() == 0 ? null : ja;
+
+ return (ja.length() == 0) ? null : ja;
}
/**
@@ -583,38 +524,38 @@
* @return A String.
* @throws JSONException If n is a non-finite number.
*/
- static public String numberToString(Number n)
- throws JSONException {
+ public static String numberToString(Number n) throws JSONException {
if (n == null) {
throw new JSONException("Null pointer");
}
+
testValidity(n);
-// Shave off trailing zeros and decimal point, if possible.
+// Shave off trailing zeros and decimal point, if possible.
+ String s = n.toString();
- String s = n.toString();
- if (s.indexOf('.') > 0 && s.indexOf('e') < 0
&& s.indexOf('E') < 0) {
+ if ((s.indexOf('.') > 0) && (s.indexOf('e') < 0)
&& (s.indexOf('E') < 0)) {
while (s.endsWith("0")) {
s = s.substring(0, s.length() - 1);
}
+
if (s.endsWith(".")) {
s = s.substring(0, s.length() - 1);
}
}
+
return s;
}
-
/**
* Get an optional value associated with a key.
* @param key A key string.
* @return An object which is the value, or null if there is no value.
*/
public Object opt(String key) {
- return key == null ? null : this.myHashMap.get(key);
+ return (key == null) ? null : this.myHashMap.get(key);
}
-
/**
* Get an optional boolean associated with a key.
* It returns false if there is no such key, or if the value is not
@@ -627,7 +568,6 @@
return optBoolean(key, false);
}
-
/**
* Get an optional boolean associated with a key.
* It returns the defaultValue if there is no such key, or if it is not
@@ -645,21 +585,20 @@
}
}
-
/**
* Put a key/value pair in the JSONObject, where the value will be a
* JSONArray which is produced from a Collection.
- * @param key A key string.
- * @param value A Collection value.
- * @return this.
+ * @param key A key string.
+ * @param value A Collection value.
+ * @return this.
* @throws JSONException
*/
public JSONObject put(String key, Collection value) throws JSONException {
put(key, new JSONArray(value));
+
return this;
}
-
/**
* Get an optional double associated with a key,
* or NaN if there is no such key or if its value is not a number.
@@ -673,7 +612,6 @@
return optDouble(key, Double.NaN);
}
-
/**
* Get an optional double associated with a key, or the
* defaultValue if there is no such key or if its value is not a number.
@@ -687,14 +625,13 @@
public double optDouble(String key, double defaultValue) {
try {
Object o = opt(key);
- return o instanceof Number ? ((Number)o).doubleValue() :
- new Double((String)o).doubleValue();
+
+ return (o instanceof Number) ? ((Number) o).doubleValue() : new
Double((String) o).doubleValue();
} catch (Exception e) {
return defaultValue;
}
}
-
/**
* Get an optional int value associated with a key,
* or zero if there is no such key or if the value is not a number.
@@ -708,7 +645,6 @@
return optInt(key, 0);
}
-
/**
* Get an optional int value associated with a key,
* or the default if there is no such key or if the value is not a number.
@@ -727,7 +663,6 @@
}
}
-
/**
* Get an optional JSONArray associated with a key.
* It returns null if there is no such key, or if its value is not a
@@ -738,10 +673,10 @@
*/
public JSONArray optJSONArray(String key) {
Object o = opt(key);
- return o instanceof JSONArray ? (JSONArray)o : null;
+
+ return (o instanceof JSONArray) ? (JSONArray) o : null;
}
-
/**
* Get an optional JSONObject associated with a key.
* It returns null if there is no such key, or if its value is not a
@@ -752,10 +687,10 @@
*/
public JSONObject optJSONObject(String key) {
Object o = opt(key);
- return o instanceof JSONObject ? (JSONObject)o : null;
+
+ return (o instanceof JSONObject) ? (JSONObject) o : null;
}
-
/**
* Get an optional long value associated with a key,
* or zero if there is no such key or if the value is not a number.
@@ -769,7 +704,6 @@
return optLong(key, 0);
}
-
/**
* Get an optional long value associated with a key,
* or the default if there is no such key or if the value is not a number.
@@ -788,7 +722,6 @@
}
}
-
/**
* Get an optional string associated with a key.
* It returns an empty string if there is no such key. If the value is not
@@ -801,7 +734,6 @@
return optString(key, "");
}
-
/**
* Get an optional string associated with a key.
* It returns the defaultValue if there is no such key.
@@ -812,10 +744,10 @@
*/
public String optString(String key, String defaultValue) {
Object o = opt(key);
- return o != null ? o.toString() : defaultValue;
+
+ return (o != null) ? o.toString() : defaultValue;
}
-
/**
* Put a key/boolean pair in the JSONObject.
*
@@ -826,10 +758,10 @@
*/
public JSONObject put(String key, boolean value) throws JSONException {
put(key, value ? Boolean.TRUE : Boolean.FALSE);
+
return this;
}
-
/**
* Put a key/double pair in the JSONObject.
*
@@ -840,10 +772,10 @@
*/
public JSONObject put(String key, double value) throws JSONException {
put(key, new Double(value));
+
return this;
}
-
/**
* Put a key/int pair in the JSONObject.
*
@@ -854,10 +786,10 @@
*/
public JSONObject put(String key, int value) throws JSONException {
put(key, new Integer(value));
+
return this;
}
-
/**
* Put a key/long pair in the JSONObject.
*
@@ -868,24 +800,24 @@
*/
public JSONObject put(String key, long value) throws JSONException {
put(key, new Long(value));
+
return this;
}
-
/**
* Put a key/value pair in the JSONObject, where the value will be a
* JSONObject which is produced from a Map.
- * @param key A key string.
- * @param value A Map value.
- * @return this.
+ * @param key A key string.
+ * @param value A Map value.
+ * @return this.
* @throws JSONException
*/
public JSONObject put(String key, Map value) throws JSONException {
put(key, new JSONObject(value));
+
return this;
}
-
-
+
/**
* Put a key/value pair in the JSONObject. If the value is null,
* then the key will be removed from the JSONObject if it is present.
@@ -901,16 +833,17 @@
if (key == null) {
throw new JSONException("Null key.");
}
+
if (value != null) {
testValidity(value);
this.myHashMap.put(key, value);
} else {
remove(key);
}
+
return this;
}
-
/**
* Put a key/value pair in the JSONObject, but only if the
* key and the value are both non-null.
@@ -922,13 +855,13 @@
* @throws JSONException If the value is a non-finite number.
*/
public JSONObject putOpt(String key, Object value) throws JSONException {
- if (key != null && value != null) {
+ if ((key != null) && (value != null)) {
put(key, value);
}
+
return this;
}
-
/**
* Produce a string in double quotes with backslash sequences in all the
* right places. A backslash will be inserted within </, allowing JSON
@@ -938,58 +871,77 @@
* @return A String correctly formatted for insertion in a JSON text.
*/
public static String quote(String string) {
- if (string == null || string.length() == 0) {
+ if ((string == null) || (string.length() == 0)) {
return "\"\"";
}
- char b;
- char c = 0;
- int i;
- int len = string.length();
+ char b;
+ char c = 0;
+ int i;
+ int len = string.length();
StringBuffer sb = new StringBuffer(len + 4);
- String t;
+ String t;
sb.append('"');
+
for (i = 0; i < len; i += 1) {
b = c;
c = string.charAt(i);
+
switch (c) {
- case '\\':
- case '"':
- sb.append('\\');
- sb.append(c);
- break;
- case '/':
- if (b == '<') {
+ case '\\' :
+ case '"' :
sb.append('\\');
- }
- sb.append(c);
- break;
- case '\b':
- sb.append("\\b");
- break;
- case '\t':
- sb.append("\\t");
- break;
- case '\n':
- sb.append("\\n");
- break;
- case '\f':
- sb.append("\\f");
- break;
- case '\r':
- sb.append("\\r");
- break;
- default:
- if (c < ' ') {
- t = "000" + Integer.toHexString(c);
- sb.append("\\u" + t.substring(t.length() - 4));
- } else {
sb.append(c);
- }
+
+ break;
+
+ case '/' :
+ if (b == '<') {
+ sb.append('\\');
+ }
+
+ sb.append(c);
+
+ break;
+
+ case '\b' :
+ sb.append("\\b");
+
+ break;
+
+ case '\t' :
+ sb.append("\\t");
+
+ break;
+
+ case '\n' :
+ sb.append("\\n");
+
+ break;
+
+ case '\f' :
+ sb.append("\\f");
+
+ break;
+
+ case '\r' :
+ sb.append("\\r");
+
+ break;
+
+ default :
+ if (c < ' ') {
+ t = "000" + Integer.toHexString(c);
+ sb.append("\\u" + t.substring(t.length() - 4));
+ } else {
+ sb.append(c);
+ }
}
}
+
sb.append('"');
+
return sb.toString();
}
@@ -1003,7 +955,6 @@
return this.myHashMap.remove(key);
}
-
/**
* Throw an exception if the object is an NaN or infinite number.
* @param o The object to test.
@@ -1012,20 +963,17 @@
static void testValidity(Object o) throws JSONException {
if (o != null) {
if (o instanceof Double) {
- if (((Double)o).isInfinite() || ((Double)o).isNaN()) {
- throw new JSONException(
- "JSON does not allow non-finite numbers");
+ if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
+ throw new JSONException("JSON does not allow non-finite
numbers");
}
} else if (o instanceof Float) {
- if (((Float)o).isInfinite() || ((Float)o).isNaN()) {
- throw new JSONException(
- "JSON does not allow non-finite numbers.");
+ if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
+ throw new JSONException("JSON does not allow non-finite
numbers.");
}
}
}
}
-
/**
* Produce a JSONArray containing the values of the members of this
* JSONObject.
@@ -1035,13 +983,16 @@
* @throws JSONException If any of the values are non-finite numbers.
*/
public JSONArray toJSONArray(JSONArray names) throws JSONException {
- if (names == null || names.length() == 0) {
+ if ((names == null) || (names.length() == 0)) {
return null;
}
+
JSONArray ja = new JSONArray();
+
for (int i = 0; i < names.length(); i += 1) {
ja.put(this.opt(names.getString(i)));
}
+
return ja;
}
@@ -1059,26 +1010,29 @@
*/
public String toString() {
try {
- Iterator keys = keys();
+ Iterator keys = keys();
StringBuffer sb = new StringBuffer("{");
while (keys.hasNext()) {
if (sb.length() > 1) {
sb.append(',');
}
+
Object o = keys.next();
+
sb.append(quote(o.toString()));
sb.append(':');
sb.append(valueToString(this.myHashMap.get(o)));
}
+
sb.append('}');
+
return sb.toString();
} catch (Exception e) {
return null;
}
}
-
/**
* Make a prettyprinted JSON text of this JSONObject.
* <p>
@@ -1095,7 +1049,6 @@
return toString(indentFactor, 0);
}
-
/**
* Make a prettyprinted JSON text of this JSONObject.
* <p>
@@ -1110,49 +1063,56 @@
* @throws JSONException If the object contains an invalid number.
*/
String toString(int indentFactor, int indent) throws JSONException {
- int i;
- int n = length();
+ int i;
+ int n = length();
+
if (n == 0) {
return "{}";
}
- Iterator keys = keys();
+
+ Iterator keys = keys();
StringBuffer sb = new StringBuffer("{");
- int newindent = indent + indentFactor;
- Object o;
+ int newindent = indent + indentFactor;
+ Object o;
+
if (n == 1) {
o = keys.next();
sb.append(quote(o.toString()));
sb.append(": ");
- sb.append(valueToString(this.myHashMap.get(o), indentFactor,
- indent));
+ sb.append(valueToString(this.myHashMap.get(o), indentFactor, indent));
} else {
while (keys.hasNext()) {
o = keys.next();
+
if (sb.length() > 1) {
sb.append(",\n");
} else {
sb.append('\n');
}
+
for (i = 0; i < newindent; i += 1) {
sb.append(' ');
}
+
sb.append(quote(o.toString()));
sb.append(": ");
- sb.append(valueToString(this.myHashMap.get(o), indentFactor,
- newindent));
+ sb.append(valueToString(this.myHashMap.get(o), indentFactor,
newindent));
}
+
if (sb.length() > 1) {
sb.append('\n');
+
for (i = 0; i < indent; i += 1) {
sb.append(' ');
}
}
}
+
sb.append('}');
+
return sb.toString();
}
-
/**
* Make a JSON text of an Object value. If the object has an
* value.toJSONString() method, then that method will be used to produce
@@ -1170,32 +1130,37 @@
* @throws JSONException If the value is or contains an invalid number.
*/
static String valueToString(Object value) throws JSONException {
- if (value == null || value.equals(null)) {
+ if ((value == null) || value.equals(null)) {
return "null";
}
+
if (value instanceof JSONString) {
- Object o;
- try {
- o = ((JSONString)value).toJSONString();
+ Object o;
+
+ try {
+ o = ((JSONString) value).toJSONString();
} catch (Exception e) {
- throw new JSONException(e);
+ throw new JSONException(e);
}
+
if (o instanceof String) {
- return (String)o;
- }
+ return (String) o;
+ }
+
throw new JSONException("Bad value from toJSONString: " + o);
}
+
if (value instanceof Number) {
return numberToString((Number) value);
}
- if (value instanceof Boolean || value instanceof JSONObject ||
- value instanceof JSONArray) {
+
+ if ((value instanceof Boolean) || (value instanceof JSONObject) || (value
instanceof JSONArray)) {
return value.toString();
}
+
return quote(value.toString());
}
-
/**
* Make a prettyprinted JSON text of an object value.
* <p>
@@ -1210,73 +1175,139 @@
* with <code>}</code> <small>(right
brace)</small>.
* @throws JSONException If the object contains an invalid number.
*/
- static String valueToString(Object value, int indentFactor, int indent)
- throws JSONException {
- if (value == null || value.equals(null)) {
+ static String valueToString(Object value, int indentFactor, int indent) throws
JSONException {
+ if ((value == null) || value.equals(null)) {
return "null";
}
+
try {
- if (value instanceof JSONString) {
- Object o = ((JSONString)value).toJSONString();
- if (o instanceof String) {
- return (String)o;
- }
- }
+ if (value instanceof JSONString) {
+ Object o = ((JSONString) value).toJSONString();
+
+ if (o instanceof String) {
+ return (String) o;
+ }
+ }
} catch (Exception e) {
- /* forget about it */
+
+ /* forget about it */
}
+
if (value instanceof Number) {
return numberToString((Number) value);
}
+
if (value instanceof Boolean) {
return value.toString();
}
+
if (value instanceof JSONObject) {
- return ((JSONObject)value).toString(indentFactor, indent);
+ return ((JSONObject) value).toString(indentFactor, indent);
}
+
if (value instanceof JSONArray) {
- return ((JSONArray)value).toString(indentFactor, indent);
+ return ((JSONArray) value).toString(indentFactor, indent);
}
+
return quote(value.toString());
}
-
- /**
- * Write the contents of the JSONObject as JSON text to a writer.
- * For compactness, no whitespace is added.
- * <p>
- * Warning: This method assumes that the data structure is acyclical.
- *
- * @return The writer.
- * @throws JSONException
- */
- public Writer write(Writer writer) throws JSONException {
+ /**
+ * Write the contents of the JSONObject as JSON text to a writer.
+ * For compactness, no whitespace is added.
+ * <p>
+ * Warning: This method assumes that the data structure is acyclical.
+ *
+ * @return The writer.
+ * @throws JSONException
+ */
+ public Writer write(Writer writer) throws JSONException {
try {
- boolean b = false;
+ boolean b = false;
Iterator keys = keys();
+
writer.write('{');
while (keys.hasNext()) {
if (b) {
writer.write(',');
}
+
Object k = keys.next();
+
writer.write(quote(k.toString()));
writer.write(':');
+
Object v = this.myHashMap.get(k);
+
if (v instanceof JSONObject) {
- ((JSONObject)v).write(writer);
+ ((JSONObject) v).write(writer);
} else if (v instanceof JSONArray) {
- ((JSONArray)v).write(writer);
+ ((JSONArray) v).write(writer);
} else {
writer.write(valueToString(v));
}
+
b = true;
}
+
writer.write('}');
+
return writer;
} catch (IOException e) {
throw new JSONException(e);
}
- }
-}
\ No newline at end of file
+ }
+
+ /**
+ * JSONObject.NULL is equivalent to the value that JavaScript calls null,
+ * whilst Java's null is equivalent to the value that JavaScript calls
+ * undefined.
+ */
+ private static final class Null implements Serializable {
+ private static final long serialVersionUID = -1155578668810010644L;
+
+ private Null() {
+ super();
+ }
+
+ /**
+ * There is only intended to be a single instance of the NULL object,
+ * so the clone method returns itself.
+ * @return NULL.
+ */
+ @Override
+ protected Object clone() {
+ return this;
+ }
+
+ /**
+ * A Null object is equal to the null value and to itself.
+ * @param object An object to test for nullness.
+ * @return true if the object parameter is the JSONObject.NULL object
+ * or null.
+ */
+ @Override
+ public boolean equals(Object object) {
+ return (object == null) || (object == this);
+ }
+
+ @Override
+ public int hashCode() {
+ return super.hashCode();
+ }
+
+ /**
+ * Get the "null" string value.
+ * @return The string "null".
+ */
+ @Override
+ public String toString() {
+ return "null";
+ }
+
+ private Object readResolve() throws ObjectStreamException {
+ return NULL;
+ }
+ }
+}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONString.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONString.java 2009-11-01
17:06:52 UTC (rev 15799)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONString.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -19,21 +19,25 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.json;
+
/**
- * The <code>JSONString</code> interface allows a
<code>toJSONString()</code>
- * method so that a class can change the behavior of
+ * The <code>JSONString</code> interface allows a
<code>toJSONString()</code>
+ * method so that a class can change the behavior of
* <code>JSONObject.toString()</code>,
<code>JSONArray.toString()</code>,
- * and <code>JSONWriter.value(</code>Object<code>)</code>. The
- * <code>toJSONString</code> method will be used instead of the default
behavior
+ * and <code>JSONWriter.value(</code>Object<code>)</code>. The
+ * <code>toJSONString</code> method will be used instead of the default
behavior
* of using the Object's <code>toString()</code> method and quoting the
result.
*/
public interface JSONString {
- /**
- * The <code>toJSONString</code> method allows a class to produce its own
JSON
- * serialization.
- *
- * @return A strictly syntactically correct JSON text.
- */
- public String toJSONString();
+
+ /**
+ * The <code>toJSONString</code> method allows a class to produce its own
JSON
+ * serialization.
+ *
+ * @return A strictly syntactically correct JSON text.
+ */
+ public String toJSONString();
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONStringer.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONStringer.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONStringer.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -23,7 +23,6 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
-
import java.io.StringWriter;
/**
@@ -57,6 +56,7 @@
* @version 2
*/
public class JSONStringer extends JSONWriter {
+
/**
* Make a fresh JSONStringer. It can be used to build one JSON text.
*/
@@ -73,6 +73,6 @@
* @return The JSON text.
*/
public String toString() {
- return this.mode == 'd' ? this.writer.toString() : null;
+ return (this.mode == 'd') ? this.writer.toString() : null;
}
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONTokener.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONTokener.java 2009-11-01
17:06:52 UTC (rev 15799)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONTokener.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -38,13 +38,11 @@
*/
private int myIndex;
-
/**
* The source string being tokenized.
*/
private String mySource;
-
/**
* Construct a JSONTokener from a string.
*
@@ -55,7 +53,6 @@
this.mySource = s;
}
-
/**
* Back up one character. This provides a sort of lookahead capability,
* so that you can test for a digit or letter before attempting to parse
@@ -67,8 +64,6 @@
}
}
-
-
/**
* Get the hex value of a character (base16).
* @param c A character between '0' and '9' or between 'A'
and 'F' or
@@ -76,19 +71,21 @@
* @return An int between 0 and 15, or -1 if c was not a hex digit.
*/
public static int dehexchar(char c) {
- if (c >= '0' && c <= '9') {
+ if ((c >= '0') && (c <= '9')) {
return c - '0';
}
- if (c >= 'A' && c <= 'F') {
+
+ if ((c >= 'A') && (c <= 'F')) {
return c - ('A' - 10);
}
- if (c >= 'a' && c <= 'f') {
+
+ if ((c >= 'a') && (c <= 'f')) {
return c - ('a' - 10);
}
+
return -1;
}
-
/**
* Determine if the source string still contains characters that next()
* can consume.
@@ -98,7 +95,6 @@
return this.myIndex < this.mySource.length();
}
-
/**
* Get the next character in the source string.
*
@@ -107,13 +103,15 @@
public char next() {
if (more()) {
char c = this.mySource.charAt(this.myIndex);
+
this.myIndex += 1;
+
return c;
}
+
return 0;
}
-
/**
* Consume the next character, and check that it matches a specified
* character.
@@ -123,14 +121,14 @@
*/
public char next(char c) throws JSONException {
char n = next();
+
if (n != c) {
- throw syntaxError("Expected '" + c + "' and instead
saw '" +
- n + "'.");
+ throw syntaxError("Expected '" + c + "' and instead
saw '" + n + "'.");
}
+
return n;
}
-
/**
* Get the next n characters.
*
@@ -140,17 +138,19 @@
* Substring bounds error if there are not
* n characters remaining in the source string.
*/
- public String next(int n) throws JSONException {
- int i = this.myIndex;
- int j = i + n;
- if (j >= this.mySource.length()) {
+ public String next(int n) throws JSONException {
+ int i = this.myIndex;
+ int j = i + n;
+
+ if (j >= this.mySource.length()) {
throw syntaxError("Substring bounds error");
- }
- this.myIndex += n;
- return this.mySource.substring(i, j);
- }
+ }
+ this.myIndex += n;
+ return this.mySource.substring(i, j);
+ }
+
/**
* Get the next char in the string, skipping whitespace
* and comments (slashslash, slashstar, and hash).
@@ -160,42 +160,50 @@
public char nextClean() throws JSONException {
for (;;) {
char c = next();
+
if (c == '/') {
switch (next()) {
- case '/':
- do {
- c = next();
- } while (c != '\n' && c != '\r' && c
!= 0);
- break;
- case '*':
- for (;;) {
- c = next();
- if (c == 0) {
- throw syntaxError("Unclosed comment.");
- }
- if (c == '*') {
- if (next() == '/') {
- break;
+ case '/' :
+ do {
+ c = next();
+ } while ((c != '\n') && (c != '\r')
&& (c != 0));
+
+ break;
+
+ case '*' :
+ for (;;) {
+ c = next();
+
+ if (c == 0) {
+ throw syntaxError("Unclosed comment.");
}
- back();
+
+ if (c == '*') {
+ if (next() == '/') {
+ break;
+ }
+
+ back();
+ }
}
- }
- break;
- default:
- back();
- return '/';
+
+ break;
+
+ default :
+ back();
+
+ return '/';
}
} else if (c == '#') {
do {
c = next();
- } while (c != '\n' && c != '\r' && c !=
0);
- } else if (c == 0 || c > ' ') {
+ } while ((c != '\n') && (c != '\r') && (c
!= 0));
+ } else if ((c == 0) || (c > ' ')) {
return c;
}
}
}
-
/**
* Return the characters up to the next close quote character.
* Backslash processing is done. The formal JSON format does not
@@ -210,51 +218,71 @@
public String nextString(char quote) throws JSONException {
char c;
StringBuffer sb = new StringBuffer();
+
for (;;) {
c = next();
+
switch (c) {
- case 0:
- case '\n':
- case '\r':
- throw syntaxError("Unterminated string");
- case '\\':
- c = next();
- switch (c) {
- case 'b':
- sb.append('\b');
+ case 0 :
+ case '\n' :
+ case '\r' :
+ throw syntaxError("Unterminated string");
+
+ case '\\' :
+ c = next();
+
+ switch (c) {
+ case 'b' :
+ sb.append('\b');
+
+ break;
+
+ case 't' :
+ sb.append('\t');
+
+ break;
+
+ case 'n' :
+ sb.append('\n');
+
+ break;
+
+ case 'f' :
+ sb.append('\f');
+
+ break;
+
+ case 'r' :
+ sb.append('\r');
+
+ break;
+
+ case 'u' :
+ sb.append((char) Integer.parseInt(next(4), 16));
+
+ break;
+
+ case 'x' :
+ sb.append((char) Integer.parseInt(next(2), 16));
+
+ break;
+
+ default :
+ sb.append(c);
+ }
+
break;
- case 't':
- sb.append('\t');
- break;
- case 'n':
- sb.append('\n');
- break;
- case 'f':
- sb.append('\f');
- break;
- case 'r':
- sb.append('\r');
- break;
- case 'u':
- sb.append((char)Integer.parseInt(next(4), 16));
- break;
- case 'x' :
- sb.append((char) Integer.parseInt(next(2), 16));
- break;
- default:
+
+ default :
+ if (c == quote) {
+ return sb.toString();
+ }
+
sb.append(c);
- }
- break;
- default:
- if (c == quote) {
- return sb.toString();
- }
- sb.append(c);
}
}
}
-
/**
* Get the text up but not including the specified character or the
* end of line, whichever comes first.
@@ -263,19 +291,22 @@
*/
public String nextTo(char d) {
StringBuffer sb = new StringBuffer();
+
for (;;) {
char c = next();
- if (c == d || c == 0 || c == '\n' || c == '\r') {
+
+ if ((c == d) || (c == 0) || (c == '\n') || (c == '\r')) {
if (c != 0) {
back();
}
+
return sb.toString().trim();
}
+
sb.append(c);
}
}
-
/**
* Get the text up but not including one of the specified delimeter
* characters or the end of line, whichever comes first.
@@ -285,20 +316,22 @@
public String nextTo(String delimiters) {
char c;
StringBuffer sb = new StringBuffer();
+
for (;;) {
c = next();
- if (delimiters.indexOf(c) >= 0 || c == 0 ||
- c == '\n' || c == '\r') {
+
+ if ((delimiters.indexOf(c) >= 0) || (c == 0) || (c == '\n') || (c
== '\r')) {
if (c != 0) {
back();
}
+
return sb.toString().trim();
}
+
sb.append(c);
}
}
-
/**
* Get the next value. The value can be a Boolean, Double, Integer,
* JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
@@ -311,14 +344,18 @@
String s;
switch (c) {
- case '"':
- case '\'':
+ case '"' :
+ case '\'' :
return nextString(c);
- case '{':
+
+ case '{' :
back();
+
return new JSONObject(this);
- case '[':
+
+ case '[' :
back();
+
return new JSONArray(this);
}
@@ -330,29 +367,33 @@
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
-
StringBuffer sb = new StringBuffer();
char b = c;
- while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c)
< 0) {
+
+ while ((c >= ' ') &&
(",:]}/\\\"[{;=#".indexOf(c) < 0)) {
sb.append(c);
c = next();
}
+
back();
/*
* If it is true, false, or null, return the proper value.
*/
+ s = sb.toString().trim();
- s = sb.toString().trim();
if (s.equals("")) {
throw syntaxError("Missing value.");
}
+
if (s.equalsIgnoreCase("true")) {
return Boolean.TRUE;
}
+
if (s.equalsIgnoreCase("false")) {
return Boolean.FALSE;
}
+
if (s.equalsIgnoreCase("null")) {
return JSONObject.NULL;
}
@@ -364,25 +405,25 @@
* conventions are non-standard. A JSON parser is free to accept
* non-JSON forms as long as it accepts all correct JSON forms.
*/
-
- if ((b >= '0' && b <= '9') || b == '.' || b
== '-' || b == '+') {
+ if (((b >= '0') && (b <= '9')) || (b ==
'.') || (b == '-') || (b == '+')) {
if (b == '0') {
- if (s.length() > 2 &&
- (s.charAt(1) == 'x' || s.charAt(1) == 'X')) {
+ if ((s.length() > 2) && ((s.charAt(1) == 'x') ||
(s.charAt(1) == 'X'))) {
try {
- return new Integer(Integer.parseInt(s.substring(2),
- 16));
+ return new Integer(Integer.parseInt(s.substring(2), 16));
} catch (Exception e) {
+
/* Ignore the error */
}
} else {
try {
return new Integer(Integer.parseInt(s, 8));
} catch (Exception e) {
+
/* Ignore the error */
}
}
}
+
try {
return new Integer(s);
} catch (Exception e) {
@@ -391,16 +432,16 @@
} catch (Exception f) {
try {
return new Double(s);
- } catch (Exception g) {
+ } catch (Exception g) {
return s;
}
}
}
}
+
return s;
}
-
/**
* Skip characters until the next character is the requested character.
* If the requested character is not found, no characters are skipped.
@@ -411,18 +452,22 @@
public char skipTo(char to) {
char c;
int index = this.myIndex;
+
do {
c = next();
+
if (c == 0) {
this.myIndex = index;
+
return c;
}
} while (c != to);
+
back();
+
return c;
}
-
/**
* Skip characters until past the requested string.
* If it is not found, we are left at the end of the source.
@@ -430,6 +475,7 @@
*/
public void skipPast(String to) {
this.myIndex = this.mySource.indexOf(to, this.myIndex);
+
if (this.myIndex < 0) {
this.myIndex = this.mySource.length();
} else {
@@ -437,7 +483,6 @@
}
}
-
/**
* Make a JSONException to signal a syntax error.
*
@@ -448,7 +493,6 @@
return new JSONException(message + toString());
}
-
/**
* Make a printable string of this JSONTokener.
*
@@ -457,11 +501,11 @@
public String toString() {
return " at character " + this.myIndex + " of " +
this.mySource;
}
-
+
/**
* @return current index
*/
public int getMyIndex() {
- return myIndex;
- }
-}
\ No newline at end of file
+ return myIndex;
+ }
+}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONWriter.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONWriter.java 2009-11-01
17:06:52 UTC (rev 15799)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/json/JSONWriter.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -57,7 +57,7 @@
* @version 2
*/
public class JSONWriter {
- private static final int maxdepth = 20;
+ private static final int MAX_DEPTH = 20;
/**
* The comma flag determines if a comma should be output before the next
@@ -78,7 +78,7 @@
/**
* The object/array stack.
*/
- private char stack[];
+ private char[] stack;
/**
* The stack top index. A value of 0 indicates that the stack is empty.
@@ -96,7 +96,7 @@
public JSONWriter(Writer w) {
this.comma = false;
this.mode = 'i';
- this.stack = new char[maxdepth];
+ this.stack = new char[MAX_DEPTH];
this.top = 0;
this.writer = w;
}
@@ -111,21 +111,27 @@
if (s == null) {
throw new JSONException("Null pointer");
}
- if (this.mode == 'o' || this.mode == 'a') {
+
+ if ((this.mode == 'o') || (this.mode == 'a')) {
try {
- if (this.comma && this.mode == 'a') {
+ if (this.comma && (this.mode == 'a')) {
this.writer.write(',');
}
+
this.writer.write(s);
} catch (IOException e) {
throw new JSONException(e);
}
+
if (this.mode == 'o') {
this.mode = 'k';
}
+
this.comma = true;
+
return this;
}
+
throw new JSONException("Value out of sequence.");
}
@@ -139,12 +145,14 @@
* outermost array or object).
*/
public JSONWriter array() throws JSONException {
- if (this.mode == 'i' || this.mode == 'o' || this.mode ==
'a') {
+ if ((this.mode == 'i') || (this.mode == 'o') || (this.mode ==
'a')) {
this.push('a');
this.append("[");
this.comma = false;
+
return this;
}
+
throw new JSONException("Misplaced array.");
}
@@ -157,16 +165,19 @@
*/
private JSONWriter end(char m, char c) throws JSONException {
if (this.mode != m) {
- throw new JSONException(m == 'o' ? "Misplaced endObject."
:
- "Misplaced endArray.");
+ throw new JSONException((m == 'o') ? "Misplaced endObject."
: "Misplaced endArray.");
}
+
this.pop(m);
+
try {
this.writer.write(c);
} catch (IOException e) {
throw new JSONException(e);
}
+
this.comma = true;
+
return this;
}
@@ -202,24 +213,27 @@
if (s == null) {
throw new JSONException("Null key.");
}
+
if (this.mode == 'k') {
try {
if (this.comma) {
this.writer.write(',');
}
+
this.writer.write(JSONObject.quote(s));
this.writer.write(':');
this.comma = false;
this.mode = 'o';
+
return this;
} catch (IOException e) {
throw new JSONException(e);
}
}
+
throw new JSONException("Misplaced key.");
}
-
/**
* Begin appending a new object. All keys and values until the balancing
* <code>endObject</code> will be appended to this object. The
@@ -233,28 +247,30 @@
if (this.mode == 'i') {
this.mode = 'o';
}
- if (this.mode == 'o' || this.mode == 'a') {
+
+ if ((this.mode == 'o') || (this.mode == 'a')) {
this.append("{");
this.push('k');
this.comma = false;
+
return this;
}
+
throw new JSONException("Misplaced object.");
-
}
-
/**
* Pop an array or object scope.
* @param c The scope to close.
* @throws JSONException If nesting is wrong.
*/
private void pop(char c) throws JSONException {
- if (this.top <= 0 || this.stack[this.top - 1] != c) {
+ if ((this.top <= 0) || (this.stack[this.top - 1] != c)) {
throw new JSONException("Nesting error.");
}
+
this.top -= 1;
- this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1];
+ this.mode = (this.top == 0) ? 'd' : this.stack[this.top - 1];
}
/**
@@ -263,15 +279,15 @@
* @throws JSONException If nesting is too deep.
*/
private void push(char c) throws JSONException {
- if (this.top >= maxdepth) {
+ if (this.top >= MAX_DEPTH) {
throw new JSONException("Nesting too deep.");
}
+
this.stack[this.top] = c;
this.mode = c;
this.top += 1;
}
-
/**
* Append either the value <code>true</code> or the value
* <code>false</code>.
@@ -303,7 +319,6 @@
return this.append(Long.toString(l));
}
-
/**
* Append an object value.
* @param o The object to append. It can be null, or a Boolean, Number,
Deleted: root/framework/trunk/impl/src/main/java/org/richfaces/json/Test.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/json/Test.java 2009-11-01
17:06:52 UTC (rev 15799)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/json/Test.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -1,439 +0,0 @@
-/**
- * License Agreement.
- *
- * JBoss RichFaces - Ajax4jsf Component Library
- *
- * 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.json;
-
-import java.io.StringWriter;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Map;
-
-/**
- * Test class. This file is not formally a member of the org.json library.
- * It is just a casual test tool.
- */
-public class Test {
-
- /**
- * Entry point.
- * @param args
- */
- public static void main(String args[]) {
- Iterator it;
- JSONArray a;
- JSONObject j;
- JSONStringer jj;
- String s;
-
-// Obj is a typical class that implements JSONString.
-
- class Obj implements JSONString {
- public String aString;
- public double aNumber;
- public boolean aBoolean;
-
- public Obj(String string, double n, boolean b) {
- this.aString = string;
- this.aNumber = n;
- this.aBoolean = b;
- }
-
- public String toJSONString() {
- return "{" + JSONObject.quote(this.aString) + ":" +
- JSONObject.doubleToString(this.aNumber) + "}";
- }
- public String toString() {
- return this.aString + " " + this.aNumber + " " +
this.aBoolean;
- }
- }
-
-
- try {
- String sa[] = {"aString", "aNumber", "aBoolean"};
- Obj obj = new Obj("A string, a number, and a boolean", 42, true);
-
- j = XML.toJSONObject("<![CDATA[This is a collection of test patterns
and examples for org.json.]]>");
- System.out.println(j.toString());
-
- jj = new JSONStringer();
- s = jj.object()
- .key("foo")
- .value("bar")
- .key("baz")
- .array()
- .object()
- .key("quux")
- .value("Thanks, Josh!")
- .endObject()
- .endArray()
- .endObject()
- .toString();
- System.out.println(s);
-
- System.out.println(new JSONStringer()
- .object()
- .key("a")
- .array()
- .array()
- .array()
- .value("b")
- .endArray()
- .endArray()
- .endArray()
- .endObject()
- .toString());
-
- jj = new JSONStringer();
- jj.array();
- jj.value(1);
- jj.array();
- jj.value(null);
- jj.array();
- jj.object();
- jj.key("empty-array").array().endArray();
- jj.key("answer").value(42);
- jj.key("null").value(null);
- jj.key("false").value(false);
- jj.key("true").value(true);
- jj.key("big").value(123456789e+88);
- jj.key("small").value(123456789e-88);
- jj.key("empty-object").object().endObject();
- jj.key("long");
- jj.value(9223372036854775807L);
- jj.endObject();
- jj.value("two");
- jj.endArray();
- jj.value(true);
- jj.endArray();
- jj.value(98.6);
- jj.value(-100.0);
- jj.object();
- jj.endObject();
- jj.object();
- jj.key("one");
- jj.value(1.00);
- jj.endObject();
- jj.value(obj);
- jj.endArray();
- System.out.println(jj.toString());
-
- System.out.println(new JSONArray(jj.toString()).toString(4));
-
- j = new JSONObject(obj, sa);
- j.put("test", obj);
- j.put("comment", "This object contains a test object that
implements JSONString");
- System.out.println(j.toString(4));
-
- j = new JSONObject("{slashes: '///', closetag:
'</script>', backslash:'\\\\', ei: {quotes:
'\"\\''},eo: {a: '\"quoted\"',
b:\"don't\"}, quotes: [\"'\", '\"']}");
- System.out.println(j.toString(2));
- System.out.println(XML.toString(j));
- System.out.println("");
-
- j = new JSONObject(
- "/*comment*/{foo: [true, false,9876543210, 0.0, 1.00000001,
1.000000000001, 1.00000000000000001," +
- " .00000000000000001, 2.00, 0.1, 2e100, -32,[],{},
\"string\"], " +
- " to : null, op : 'Good'," +
- "ten:10} postfix comment");
- j.put("String", "98.6");
- j.put("JSONObject", new JSONObject());
- j.put("JSONArray", new JSONArray());
- j.put("int", 57);
- j.put("double", 123456789012345678901234567890.);
- j.put("true", true);
- j.put("false", false);
- j.put("null", JSONObject.NULL);
- j.put("bool", "true");
- j.put("zero", -0.0);
- a = j.getJSONArray("foo");
- a.put(666);
- a.put(2001.99);
- a.put("so \"fine\".");
- a.put("so <fine>.");
- a.put(true);
- a.put(false);
- a.put(new JSONArray());
- a.put(new JSONObject());
- System.out.println(j.toString(4));
- System.out.println(XML.toString(j));
-
- System.out.println("String: " + j.getDouble("String"));
- System.out.println(" bool: " + j.getBoolean("bool"));
- System.out.println(" to: " + j.getString("to"));
- System.out.println(" true: " + j.getString("true"));
- System.out.println(" foo: " + j.getJSONArray("foo"));
- System.out.println(" op: " + j.getString("op"));
- System.out.println(" ten: " + j.getInt("ten"));
- System.out.println(" oops: " + j.optBoolean("oops"));
-
- j = XML.toJSONObject("<xml one = 1 two=' \"2\"
'><five></five>First
\u0009<content><five></five> This is \"content\".
<three> 3 </three>JSON does not preserve the sequencing of elements and
contents.<three> III </three> <three> T H R E
E</three><four/>Content text is an implied structure in XML. <six
content=\"6\"/>JSON does not have implied
structure:<seven>7</seven>everything is explicit.<![CDATA[CDATA
blocks<are><supported>!]]></xml>");
- System.out.println(j.toString(2));
- System.out.println(XML.toString(j));
- System.out.println("");
-
- j = XML.toJSONObject("<mapping><empty/> <class name =
\"Customer\"> <field name = \"ID\" type =
\"string\"> <bind-xml name=\"ID\"
node=\"attribute\"/> </field> <field name =
\"FirstName\" type = \"FirstName\"/> <field name =
\"MI\" type = \"MI\"/> <field name = \"LastName\"
type = \"LastName\"/> </class> <class name =
\"FirstName\"> <field name = \"text\">
<bind-xml name = \"text\" node = \"text\"/> </field>
</class> <class name = \"MI\"> <field name =
\"text\"> <bind-xml name = \"text\" node =
\"text\"/> </field> </class> <class name =
\"LastName\"> <field name = \"text\">
<bind-xml name = \"text\" node = \"text\"/> </field>
</class></mapping>");
-
- System.out.println(j.toString(2));
- System.out.println(XML.toString(j));
- System.out.println("");
-
- j = XML.toJSONObject("<?xml version=\"1.0\" ?><Book
Author=\"Anonymous\"><Title>Sample Book</Title><Chapter
id=\"1\">This is chapter 1. It is not very long or
interesting.</Chapter><Chapter id=\"2\">This is chapter 2. Although
it is longer than chapter 1, it is not any more
interesting.</Chapter></Book>");
- System.out.println(j.toString(2));
- System.out.println(XML.toString(j));
- System.out.println("");
-
- j = XML.toJSONObject("<!DOCTYPE bCard
'http://www.cs.caltech.edu/~adam/schemas/bCard'><bCard><?xml default
bCard firstname = '' lastname = '' company = ''
email = '' homepage = ''?><bCard firstname = 'Rohit'
lastname = 'Khare' company = 'MCI' email =
'khare(a)mci.net' homepage = 'http://pest.w3.org/'/><bCard
firstname = 'Adam' lastname = 'Rifkin' company =
'Caltech Infospheres Project' email = 'adam(a)cs.caltech.edu'
homepage = 'http://www.cs.caltech.edu/~adam/'/></bCard>");
- System.out.println(j.toString(2));
- System.out.println(XML.toString(j));
- System.out.println("");
-
- j = XML.toJSONObject("<?xml
version=\"1.0\"?><customer> <firstName>
<text>Fred</text> </firstName> <ID>fbs0001</ID>
<lastName> <text>Scerbo</text> </lastName> <MI>
<text>B</text> </MI></customer>");
- System.out.println(j.toString(2));
- System.out.println(XML.toString(j));
- System.out.println("");
-
- j = XML.toJSONObject("<!ENTITY tp-address PUBLIC '-//ABC
University::Special Collections Library//TEXT (titlepage: name and address)//EN'
'tpspcoll.sgm'><list type='simple'><head>Repository Address
</head><item>Special Collections Library</item><item>ABC
University</item><item>Main Library, 40 Circle
Drive</item><item>Ourtown, Pennsylvania</item><item>17654
USA</item></list>");
- System.out.println(j.toString());
- System.out.println(XML.toString(j));
- System.out.println("");
-
- j = XML.toJSONObject("<test intertag
status=ok><empty/>deluxe<blip
sweet=true>&"toot"&toot;A</blip><x>eks</x><w>bonus</w><w>bonus2</w></test>");
- System.out.println(j.toString(2));
- System.out.println(XML.toString(j));
- System.out.println("");
-
- j = HTTP.toJSONObject("GET / HTTP/1.0\nAccept: image/gif,
image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint,
application/vnd.ms-excel, application/msword, */*\nAccept-Language: en-us\nUser-Agent:
Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; Win 9x 4.90; T312461; Q312461)\nHost:
www.nokko.com\nConnection: keep-alive\nAccept-encoding: gzip, deflate\n");
- System.out.println(j.toString(2));
- System.out.println(HTTP.toString(j));
- System.out.println("");
-
- j = HTTP.toJSONObject("HTTP/1.1 200 Oki Doki\nDate: Sun, 26 May 2002
17:38:52 GMT\nServer: Apache/1.3.23 (Unix) mod_perl/1.26\nKeep-Alive: timeout=15,
max=100\nConnection: Keep-Alive\nTransfer-Encoding: chunked\nContent-Type:
text/html\n");
- System.out.println(j.toString(2));
- System.out.println(HTTP.toString(j));
- System.out.println("");
-
- j = new JSONObject("{nix: null, nux: false, null: 'null',
'Request-URI': '/', Method: 'GET', 'HTTP-Version':
'HTTP/1.0'}");
- System.out.println(j.toString(2));
- System.out.println("isNull: " + j.isNull("nix"));
- System.out.println(" has: " + j.has("nix"));
- System.out.println(XML.toString(j));
- System.out.println(HTTP.toString(j));
- System.out.println("");
-
- j = XML.toJSONObject("<?xml version='1.0'
encoding='UTF-8'?>"+"\n\n"+"<SOAP-ENV:Envelope"+
- "
xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"&qu...
- "
xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\""+
- "
xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\">"+
- "<SOAP-ENV:Body><ns1:doGoogleSearch"+
- " xmlns:ns1=\"urn:GoogleSearch\""+
- "
SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\&...
- "<key xsi:type=\"xsd:string\">GOOGLEKEY</key>
<q"+
- " xsi:type=\"xsd:string\">'+search+'</q>
<start"+
- " xsi:type=\"xsd:int\">0</start>
<maxResults"+
- " xsi:type=\"xsd:int\">10</maxResults>
<filter"+
- " xsi:type=\"xsd:boolean\">true</filter>
<restrict"+
- " xsi:type=\"xsd:string\"></restrict>
<safeSearch"+
- " xsi:type=\"xsd:boolean\">false</safeSearch>
<lr"+
- " xsi:type=\"xsd:string\"></lr> <ie"+
- " xsi:type=\"xsd:string\">latin1</ie>
<oe"+
- " xsi:type=\"xsd:string\">latin1</oe>"+
- "</ns1:doGoogleSearch>"+
- "</SOAP-ENV:Body></SOAP-ENV:Envelope>");
- System.out.println(j.toString(2));
- System.out.println(XML.toString(j));
- System.out.println("");
-
- j = new JSONObject("{Envelope: {Body: {\"ns1:doGoogleSearch\":
{oe: \"latin1\", filter: true, q: \"'+search+'\", key:
\"GOOGLEKEY\", maxResults: 10, \"SOAP-ENV:encodingStyle\":
\"http://schemas.xmlsoap.org/soap/encoding/\", start: 0, ie:
\"latin1\", safeSearch:false, \"xmlns:ns1\":
\"urn:GoogleSearch\"}}}}");
- System.out.println(j.toString(2));
- System.out.println(XML.toString(j));
- System.out.println("");
-
- j = CookieList.toJSONObject(" f%oo = b+l=ah ; o;n%40e = t.wo ");
- System.out.println(j.toString(2));
- System.out.println(CookieList.toString(j));
- System.out.println("");
-
- j = Cookie.toJSONObject("f%oo=blah; secure ;expires = April 24,
2002");
- System.out.println(j.toString(2));
- System.out.println(Cookie.toString(j));
- System.out.println("");
-
- j = new JSONObject("{script: 'It is not allowed in HTML to send a
close script tag in a string<script>because it confuses browsers</script>so we
insert a backslash before the /'}");
- System.out.println(j.toString());
- System.out.println("");
-
- JSONTokener jt = new JSONTokener("{op:'test',
to:'session', pre:1}{op:'test', to:'session', pre:2}");
- j = new JSONObject(jt);
- System.out.println(j.toString());
- System.out.println("pre: " + j.optInt("pre"));
- int i = jt.skipTo('{');
- System.out.println(i);
- j = new JSONObject(jt);
- System.out.println(j.toString());
- System.out.println("");
-
- a = CDL.toJSONArray("No quotes, 'Single Quotes', \"Double
Quotes\"\n1,'2',\"3\"\n,'It is \"good,\"',
\"It works.\"\n\n");
-
- System.out.println(CDL.toString(a));
- System.out.println("");
- System.out.println(a.toString(4));
- System.out.println("");
-
- a = new JSONArray(" [\"<escape>\", next is an implied
null , , ok,] ");
- System.out.println(a.toString());
- System.out.println("");
- System.out.println(XML.toString(a));
- System.out.println("");
-
- j = new JSONObject("{ fun => with non-standard forms ; forgiving
=> This package can be used to parse formats that are similar to but not stricting
conforming to JSON; why=To make it easier to migrate existing data to JSON,one = [[1.00]];
uno=[[{1=>1}]];'+':+6e66 ;pluses=+++;empty = '' ,
'double':0.666,true: TRUE, false: FALSE, null=NULL;[true] = [[!,@;*]]; string=>
o. k. ; # comment\r oct=0666; hex=0x666; dec=666; o=0999; noh=0x0x}");
- System.out.println(j.toString(4));
- System.out.println("");
- if (j.getBoolean("true") &&
!j.getBoolean("false")) {
- System.out.println("It's all good");
- }
-
- System.out.println("");
- j = new JSONObject(j, new String[]{"dec", "oct",
"hex", "missing"});
- System.out.println(j.toString(4));
-
- System.out.println("");
- System.out.println(new JSONStringer().array().value(a).value(j).endArray());
-
- j = new JSONObject("{string: \"98.6\", long: 2147483648, int:
2147483647, longer: 9223372036854775807, double: 9223372036854775808}");
- System.out.println(j.toString(4));
-
- System.out.println("\ngetInt");
- System.out.println("int " + j.getInt("int"));
- System.out.println("long " + j.getInt("long"));
- System.out.println("longer " + j.getInt("longer"));
- System.out.println("double " + j.getInt("double"));
- System.out.println("string " + j.getInt("string"));
-
- System.out.println("\ngetLong");
- System.out.println("int " + j.getLong("int"));
- System.out.println("long " + j.getLong("long"));
- System.out.println("longer " + j.getLong("longer"));
- System.out.println("double " + j.getLong("double"));
- System.out.println("string " + j.getLong("string"));
-
- System.out.println("\ngetDouble");
- System.out.println("int " + j.getDouble("int"));
- System.out.println("long " + j.getDouble("long"));
- System.out.println("longer " + j.getDouble("longer"));
- System.out.println("double " + j.getDouble("double"));
- System.out.println("string " + j.getDouble("string"));
-
- j.put("good sized", 9223372036854775807L);
- System.out.println(j.toString(4));
-
- a = new JSONArray("[2147483647, 2147483648, 9223372036854775807,
9223372036854775808]");
- System.out.println(a.toString(4));
-
- System.out.println("\nKeys: ");
- it = j.keys();
- while (it.hasNext()) {
- s = (String)it.next();
- System.out.println(s + ": " + j.getString(s));
- }
-
-
- System.out.println("\naccumulate: ");
- j = new JSONObject();
- j.accumulate("stooge", "Curly");
- j.accumulate("stooge", "Larry");
- j.accumulate("stooge", "Moe");
- a = j.getJSONArray("stooge");
- a.put(5, "Shemp");
- System.out.println(j.toString(4));
-
- System.out.println("\nwrite:");
- System.out.println(j.write(new StringWriter()));
-
- s = "<xml
empty><a></a><a>1</a><a>22</a><a>333</a></xml>";
- j = XML.toJSONObject(s);
- System.out.println(j.toString(4));
- System.out.println(XML.toString(j));
-
- s = "<book><chapter>Content of the first
chapter</chapter><chapter>Content of the second chapter
<chapter>Content of the first subchapter</chapter> <chapter>Content
of the second subchapter</chapter></chapter><chapter>Third
Chapter</chapter></book>";
- j = XML.toJSONObject(s);
- System.out.println(j.toString(4));
- System.out.println(XML.toString(j));
-
- Collection c = null;
- Map m = null;
-
- j = new JSONObject(m);
- a = new JSONArray(c);
- j.append("stooge", "Joe DeRita");
- j.append("stooge", "Shemp");
- j.accumulate("stooges", "Curly");
- j.accumulate("stooges", "Larry");
- j.accumulate("stooges", "Moe");
- j.accumulate("stoogearray", j.get("stooges"));
- j.put("map", m);
- j.put("collection", c);
- j.put("array", a);
- a.put(m);
- a.put(c);
- System.out.println(j.toString(4));
-
- System.out.println("\nTesting Exceptions: ");
-
- System.out.print("Exception: ");
- try {
- System.out.println(j.getDouble("stooge"));
- } catch (Exception e) {
- System.out.println(e);
- }
- System.out.print("Exception: ");
- try {
- System.out.println(j.getDouble("howard"));
- } catch (Exception e) {
- System.out.println(e);
- }
- System.out.print("Exception: ");
- try {
- System.out.println(j.put(null, "howard"));
- } catch (Exception e) {
- System.out.println(e);
- }
- System.out.print("Exception: ");
- try {
- System.out.println(a.getDouble(0));
- } catch (Exception e) {
- System.out.println(e);
- }
- System.out.print("Exception: ");
- try {
- System.out.println(a.get(-1));
- } catch (Exception e) {
- System.out.println(e);
- }
- System.out.print("Exception: ");
- try {
- System.out.println(a.put(Double.NaN));
- } catch (Exception e) {
- System.out.println(e);
- }
- } catch (Exception e) {
- System.out.println(e.toString());
- }
- }
-}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/json/XML.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/json/XML.java 2009-11-01
17:06:52 UTC (rev 15799)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/json/XML.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -23,45 +23,45 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
-
import java.util.Iterator;
-
/**
* This provides static methods to convert an XML text into a JSONObject,
* and to covert a JSONObject into an XML text.
* @author
JSON.org
* @version 2
*/
-public class XML {
+public final class XML {
/** The Character '&'. */
- public static final Character AMP = new Character('&');
+ public static final Character AMP = new Character('&');
/** The Character '''. */
- public static final Character APOS = new Character('\'');
+ public static final Character APOS = new Character('\'');
/** The Character '!'. */
- public static final Character BANG = new Character('!');
+ public static final Character BANG = new Character('!');
/** The Character '='. */
- public static final Character EQ = new Character('=');
+ public static final Character EQ = new Character('=');
/** The Character '>'. */
- public static final Character GT = new Character('>');
+ public static final Character GT = new Character('>');
/** The Character '<'. */
- public static final Character LT = new Character('<');
+ public static final Character LT = new Character('<');
/** The Character '?'. */
public static final Character QUEST = new Character('?');
/** The Character '"'. */
- public static final Character QUOT = new Character('"');
+ public static final Character QUOT = new Character('"');
/** The Character '/'. */
public static final Character SLASH = new Character('/');
+ private XML() {}
+
/**
* Replace special characters with XML escapes:
* <pre>
@@ -75,25 +75,37 @@
*/
public static String escape(String string) {
StringBuffer sb = new StringBuffer();
- for (int i = 0, len = string.length(); i < len; i++) {
+ int len = string.length();
+
+ for (int i = 0; i < len; i++) {
char c = string.charAt(i);
+
switch (c) {
- case '&':
- sb.append("&");
- break;
- case '<':
- sb.append("<");
- break;
- case '>':
- sb.append(">");
- break;
- case '"':
- sb.append(""");
- break;
- default:
- sb.append(c);
+ case '&' :
+ sb.append("&");
+
+ break;
+
+ case '<' :
+ sb.append("<");
+
+ break;
+
+ case '>' :
+ sb.append(">");
+
+ break;
+
+ case '"' :
+ sb.append(""");
+
+ break;
+
+ default :
+ sb.append(c);
}
}
+
return sb.toString();
}
@@ -105,53 +117,60 @@
* @return true if the close tag is processed.
* @throws JSONException
*/
- private static boolean parse(XMLTokener x, JSONObject context,
- String name) throws JSONException {
- char c;
- int i;
- String n;
+ private static boolean parse(XMLTokener x, JSONObject context, String name) throws
JSONException {
+ char c;
+ int i;
+ String n;
JSONObject o = null;
- String s;
- Object t;
+ String s;
+ Object t;
-// Test for and skip past these forms:
-// <!-- ... -->
-// <! ... >
-// <![ ... ]]>
-// <? ... ?>
-// Report errors for these forms:
-// <>
-// <=
-// <<
-
+// Test for and skip past these forms:
+// <!-- ... -->
+// <! ... >
+// <![ ... ]]>
+// <? ... ?>
+// Report errors for these forms:
+// <>
+// <=
+// <<
t = x.nextToken();
-// <!
-
+// <!
if (t == BANG) {
c = x.next();
+
if (c == '-') {
if (x.next() == '-') {
x.skipPast("-->");
+
return false;
}
+
x.back();
} else if (c == '[') {
t = x.nextToken();
+
if (t.equals("CDATA")) {
if (x.next() == '[') {
s = x.nextCDATA();
+
if (s.length() > 0) {
context.accumulate("content", s);
}
+
return false;
}
}
+
throw x.syntaxError("Expected 'CDATA['");
}
+
i = 1;
+
do {
t = x.nextMeta();
+
if (t == null) {
throw x.syntaxError("Missing '>' after
'<!'.");
} else if (t == LT) {
@@ -160,92 +179,97 @@
i -= 1;
}
} while (i > 0);
+
return false;
} else if (t == QUEST) {
-// <?
+// <?
+ x.skipPast("?>");
- x.skipPast("?>");
return false;
} else if (t == SLASH) {
-// Close tag </
-
- if (name == null || !x.nextToken().equals(name)) {
+// Close tag </
+ if ((name == null) || !x.nextToken().equals(name)) {
throw x.syntaxError("Mismatched close tag");
}
+
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped close tag");
}
+
return true;
-
} else if (t instanceof Character) {
throw x.syntaxError("Misshaped tag");
-// Open tag <
-
+// Open tag <
} else {
- n = (String)t;
+ n = (String) t;
t = null;
o = new JSONObject();
+
for (;;) {
if (t == null) {
t = x.nextToken();
}
-// attribute = value
-
+// attribute = value
if (t instanceof String) {
- s = (String)t;
+ s = (String) t;
t = x.nextToken();
+
if (t == EQ) {
t = x.nextToken();
+
if (!(t instanceof String)) {
throw x.syntaxError("Missing value");
}
+
o.accumulate(s, t);
t = null;
} else {
o.accumulate(s, "");
}
-// Empty tag <.../>
-
+// Empty tag <.../>
} else if (t == SLASH) {
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped tag");
}
+
context.accumulate(n, o);
+
return false;
-// Content, between <...> and </...>
-
+// Content, between <...> and </...>
} else if (t == GT) {
for (;;) {
t = x.nextContent();
+
if (t == null) {
if (name != null) {
throw x.syntaxError("Unclosed tag " + name);
}
+
return false;
} else if (t instanceof String) {
- s = (String)t;
+ s = (String) t;
+
if (s.length() > 0) {
o.accumulate("content", s);
}
-// Nested element
-
+// Nested element
} else if (t == LT) {
if (parse(x, o, n)) {
if (o.length() == 0) {
context.accumulate(n, "");
- } else if (o.length() == 1 &&
- o.opt("content") != null) {
+ } else if ((o.length() == 1) &&
(o.opt("content") != null)) {
context.accumulate(n, o.opt("content"));
} else {
context.accumulate(n, o);
}
+
return false;
}
}
@@ -257,7 +281,6 @@
}
}
-
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject. Some information may be lost in this transformation
@@ -275,14 +298,15 @@
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject o = new JSONObject();
XMLTokener x = new XMLTokener(string);
+
while (x.more()) {
x.skipPast("<");
parse(x, o, null);
}
+
return o;
}
-
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
* @param o A JSONObject.
@@ -293,7 +317,6 @@
return toString(o, null);
}
-
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
* @param o A JSONObject.
@@ -301,61 +324,62 @@
* @return A string.
* @throws JSONException
*/
- public static String toString(Object o, String tagName)
- throws JSONException {
+ public static String toString(Object o, String tagName) throws JSONException {
StringBuffer b = new StringBuffer();
- int i;
- JSONArray ja;
- JSONObject jo;
- String k;
- Iterator keys;
- int len;
- String s;
- Object v;
+ int i;
+ JSONArray ja;
+ JSONObject jo;
+ String k;
+ Iterator keys;
+ int len;
+ String s;
+ Object v;
+
if (o instanceof JSONObject) {
-// Emit <tagName>
-
+// Emit <tagName>
if (tagName != null) {
b.append('<');
b.append(tagName);
b.append('>');
}
-// Loop thru the keys.
+// Loop thru the keys.
+ jo = (JSONObject) o;
+ keys = jo.keys();
- jo = (JSONObject)o;
- keys = jo.keys();
while (keys.hasNext()) {
k = keys.next().toString();
v = jo.get(k);
+
if (v instanceof String) {
- s = (String)v;
+ s = (String) v;
} else {
s = null;
}
-// Emit content in body
-
+// Emit content in body
if (k.equals("content")) {
if (v instanceof JSONArray) {
- ja = (JSONArray)v;
+ ja = (JSONArray) v;
len = ja.length();
+
for (i = 0; i < len; i += 1) {
if (i > 0) {
b.append('\n');
}
+
b.append(escape(ja.get(i).toString()));
}
} else {
b.append(escape(v.toString()));
}
-// Emit an array of similar keys
-
+// Emit an array of similar keys
} else if (v instanceof JSONArray) {
- ja = (JSONArray)v;
+ ja = (JSONArray) v;
len = ja.length();
+
for (i = 0; i < len; i += 1) {
b.append(toString(ja.get(i), k));
}
@@ -364,38 +388,39 @@
b.append(k);
b.append("/>");
-// Emit a new tag <k>
-
+// Emit a new tag <k>
} else {
b.append(toString(v, k));
}
}
+
if (tagName != null) {
-// Emit the </tagname> close tag
-
+// Emit the </tagname> close tag
b.append("</");
b.append(tagName);
b.append('>');
}
+
return b.toString();
-// XML does not have good support for arrays. If an array appears in a place
-// where XML is lacking, synthesize an <array> element.
-
+// XML does not have good support for arrays. If an array appears in a place
+// where XML is lacking, synthesize an <array> element.
} else if (o instanceof JSONArray) {
- ja = (JSONArray)o;
+ ja = (JSONArray) o;
len = ja.length();
+
for (i = 0; i < len; ++i) {
- b.append(toString(
- ja.opt(i), (tagName == null) ? "array" : tagName));
+ b.append(toString(ja.opt(i), (tagName == null) ? "array" :
tagName));
}
+
return b.toString();
} else {
s = (o == null) ? "null" : escape(o.toString());
- return (tagName == null) ? "\"" + s + "\"" :
- (s.length() == 0) ? "<" + tagName + "/>" :
- "<" + tagName + ">" + s + "</" +
tagName + ">";
+
+ return (tagName == null)
+ ? "\"" + s + "\""
+ : (s.length() == 0) ? "<" + tagName + "/>" :
"<" + tagName + ">" + s + "</" + tagName +
">";
}
}
-}
\ No newline at end of file
+}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/json/XMLTokener.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/json/XMLTokener.java 2009-11-01
17:06:52 UTC (rev 15799)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/json/XMLTokener.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -32,21 +32,21 @@
*/
public class XMLTokener extends JSONTokener {
+ /**
+ * The table of entity values. It initially contains Character values for
+ * amp, apos, gt, lt, quot.
+ */
+ public static final java.util.HashMap ENTITY;
- /** The table of entity values. It initially contains Character values for
- * amp, apos, gt, lt, quot.
- */
- public static final java.util.HashMap entity;
+ static {
+ ENTITY = new java.util.HashMap(8);
+ ENTITY.put("amp", XML.AMP);
+ ENTITY.put("apos", XML.APOS);
+ ENTITY.put("gt", XML.GT);
+ ENTITY.put("lt", XML.LT);
+ ENTITY.put("quot", XML.QUOT);
+ }
- static {
- entity = new java.util.HashMap(8);
- entity.put("amp", XML.AMP);
- entity.put("apos", XML.APOS);
- entity.put("gt", XML.GT);
- entity.put("lt", XML.LT);
- entity.put("quot", XML.QUOT);
- }
-
/**
* Construct an XMLTokener from a string.
* @param s A source string.
@@ -61,25 +61,28 @@
* @throws JSONException If the <code>]]></code> is not found.
*/
public String nextCDATA() throws JSONException {
- char c;
- int i;
+ char c;
+ int i;
StringBuffer sb = new StringBuffer();
+
for (;;) {
c = next();
+
if (c == 0) {
throw syntaxError("Unclosed CDATA.");
}
+
sb.append(c);
i = sb.length() - 3;
- if (i >= 0 && sb.charAt(i) == ']' &&
- sb.charAt(i + 1) == ']' && sb.charAt(i + 2) ==
'>') {
+
+ if ((i >= 0) && (sb.charAt(i) == ']') &&
(sb.charAt(i + 1) == ']') && (sb.charAt(i + 2) == '>')) {
sb.setLength(i);
+
return sb.toString();
}
}
}
-
/**
* Get the next XML outer token, trimming whitespace. There are two kinds
* of tokens: the '<' character which begins a markup tag, and the
content
@@ -90,33 +93,40 @@
* @throws JSONException
*/
public Object nextContent() throws JSONException {
- char c;
+ char c;
StringBuffer sb;
+
do {
c = next();
} while (Character.isWhitespace(c));
+
if (c == 0) {
return null;
}
+
if (c == '<') {
return XML.LT;
}
+
sb = new StringBuffer();
+
for (;;) {
- if (c == '<' || c == 0) {
+ if ((c == '<') || (c == 0)) {
back();
+
return sb.toString().trim();
}
+
if (c == '&') {
sb.append(nextEntity(c));
} else {
sb.append(c);
}
+
c = next();
}
}
-
/**
* Return the next entity. These entities are translated to Characters:
* <code>& ' > <
"</code>.
@@ -126,9 +136,11 @@
*/
public Object nextEntity(char a) throws JSONException {
StringBuffer sb = new StringBuffer();
+
for (;;) {
char c = next();
- if (Character.isLetterOrDigit(c) || c == '#') {
+
+ if (Character.isLetterOrDigit(c) || (c == '#')) {
sb.append(Character.toLowerCase(c));
} else if (c == ';') {
break;
@@ -136,12 +148,13 @@
throw syntaxError("Missing ';' in XML entity: &" +
sb);
}
}
+
String s = sb.toString();
- Object e = entity.get(s);
- return e != null ? e : a + s + ";";
+ Object e = ENTITY.get(s);
+
+ return (e != null) ? e : a + s + ";";
}
-
/**
* Returns the next XML meta token. This is used for skipping over <!...>
* and <?...?> structures.
@@ -154,60 +167,78 @@
public Object nextMeta() throws JSONException {
char c;
char q;
+
do {
c = next();
} while (Character.isWhitespace(c));
+
switch (c) {
- case 0:
- throw syntaxError("Misshaped meta tag.");
- case '<':
- return XML.LT;
- case '>':
- return XML.GT;
- case '/':
- return XML.SLASH;
- case '=':
- return XML.EQ;
- case '!':
- return XML.BANG;
- case '?':
- return XML.QUEST;
- case '"':
- case '\'':
- q = c;
- for (;;) {
- c = next();
- if (c == 0) {
- throw syntaxError("Unterminated string.");
+ case 0 :
+ throw syntaxError("Misshaped meta tag.");
+
+ case '<' :
+ return XML.LT;
+
+ case '>' :
+ return XML.GT;
+
+ case '/' :
+ return XML.SLASH;
+
+ case '=' :
+ return XML.EQ;
+
+ case '!' :
+ return XML.BANG;
+
+ case '?' :
+ return XML.QUEST;
+
+ case '"' :
+ case '\'' :
+ q = c;
+
+ for (;;) {
+ c = next();
+
+ if (c == 0) {
+ throw syntaxError("Unterminated string.");
+ }
+
+ if (c == q) {
+ return Boolean.TRUE;
+ }
}
- if (c == q) {
- return Boolean.TRUE;
+ default :
+ for (;;) {
+ c = next();
+
+ if (Character.isWhitespace(c)) {
+ return Boolean.TRUE;
+ }
+
+ switch (c) {
+ case 0 :
+ case '<' :
+ case '>' :
+ case '/' :
+ case '=' :
+ case '!' :
+ case '?' :
+ case '"' :
+ case '\'' :
+ back();
+
+ return Boolean.TRUE;
+
+ default :
+
+ // TODO Refactoring
+ }
}
- }
- default:
- for (;;) {
- c = next();
- if (Character.isWhitespace(c)) {
- return Boolean.TRUE;
- }
- switch (c) {
- case 0:
- case '<':
- case '>':
- case '/':
- case '=':
- case '!':
- case '?':
- case '"':
- case '\'':
- back();
- return Boolean.TRUE;
- }
- }
}
}
-
/**
* Get the next XML Token. These tokens are found inside of angle
* brackets. It may be one of these characters: <code>/ > = ! ?</code>
or it
@@ -220,73 +251,92 @@
char c;
char q;
StringBuffer sb;
+
do {
c = next();
} while (Character.isWhitespace(c));
+
switch (c) {
- case 0:
- throw syntaxError("Misshaped element.");
- case '<':
- throw syntaxError("Misplaced '<'.");
- case '>':
- return XML.GT;
- case '/':
- return XML.SLASH;
- case '=':
- return XML.EQ;
- case '!':
- return XML.BANG;
- case '?':
- return XML.QUEST;
+ case 0 :
+ throw syntaxError("Misshaped element.");
-// Quoted string
+ case '<' :
+ throw syntaxError("Misplaced '<'.");
- case '"':
- case '\'':
- q = c;
- sb = new StringBuffer();
- for (;;) {
- c = next();
- if (c == 0) {
- throw syntaxError("Unterminated string.");
+ case '>' :
+ return XML.GT;
+
+ case '/' :
+ return XML.SLASH;
+
+ case '=' :
+ return XML.EQ;
+
+ case '!' :
+ return XML.BANG;
+
+ case '?' :
+ return XML.QUEST;
+
+// Quoted string
+ case '"' :
+ case '\'' :
+ q = c;
+ sb = new StringBuffer();
+
+ for (;;) {
+ c = next();
+
+ if (c == 0) {
+ throw syntaxError("Unterminated string.");
+ }
+
+ if (c == q) {
+ return sb.toString();
+ }
+
+ if (c == '&') {
+ sb.append(nextEntity(c));
+ } else {
+ sb.append(c);
+ }
}
- if (c == q) {
- return sb.toString();
- }
- if (c == '&') {
- sb.append(nextEntity(c));
- } else {
+ default :
+
+// Name
+ sb = new StringBuffer();
+
+ for (;;) {
sb.append(c);
- }
- }
- default:
+ c = next();
-// Name
+ if (Character.isWhitespace(c)) {
+ return sb.toString();
+ }
- sb = new StringBuffer();
- for (;;) {
- sb.append(c);
- c = next();
- if (Character.isWhitespace(c)) {
- return sb.toString();
+ switch (c) {
+ case 0 :
+ case '>' :
+ case '/' :
+ case '=' :
+ case '!' :
+ case '?' :
+ case '[' :
+ case ']' :
+ back();
+
+ return sb.toString();
+
+ case '<' :
+ case '"' :
+ case '\'' :
+ throw syntaxError("Bad character in a name.");
+
+ default :
+
+ // TODO Refactoring
+ }
}
- switch (c) {
- case 0:
- case '>':
- case '/':
- case '=':
- case '!':
- case '?':
- case '[':
- case ']':
- back();
- return sb.toString();
- case '<':
- case '"':
- case '\'':
- throw syntaxError("Bad character in a name.");
- }
- }
}
}
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/json/package-info.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/json/package-info.java 2009-11-01
17:06:52 UTC (rev 15799)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/json/package-info.java 2009-11-01
17:10:42 UTC (rev 15800)
@@ -1,3 +1,4 @@
+
/**
* JSON handling classes. Contains <a
href="http://www.json.org">implementation</a> of JSON library together
with JSON-based basic container classes implementation
*/