Author: remy.maucherat(a)jboss.com
Date: 2008-09-18 21:53:57 -0400 (Thu, 18 Sep 2008)
New Revision: 784
Added:
trunk/java/org/apache/cometd/
trunk/java/org/apache/cometd/bayeux/
trunk/java/org/apache/cometd/bayeux/Bayeux.java
trunk/java/org/apache/cometd/bayeux/Channel.java
trunk/java/org/apache/cometd/bayeux/Client.java
trunk/java/org/apache/cometd/bayeux/DataFilter.java
trunk/java/org/apache/cometd/bayeux/Listener.java
trunk/java/org/apache/cometd/bayeux/Message.java
trunk/java/org/apache/cometd/bayeux/SecurityPolicy.java
trunk/java/org/apache/tomcat/bayeux/
trunk/java/org/apache/tomcat/bayeux/BayeuxException.java
trunk/java/org/apache/tomcat/bayeux/BayeuxRequest.java
trunk/java/org/apache/tomcat/bayeux/BayeuxServlet.java
trunk/java/org/apache/tomcat/bayeux/ChannelImpl.java
trunk/java/org/apache/tomcat/bayeux/ClientImpl.java
trunk/java/org/apache/tomcat/bayeux/HttpError.java
trunk/java/org/apache/tomcat/bayeux/MessageImpl.java
trunk/java/org/apache/tomcat/bayeux/RequestBase.java
trunk/java/org/apache/tomcat/bayeux/RequestFactory.java
trunk/java/org/apache/tomcat/bayeux/TomcatBayeux.java
trunk/java/org/apache/tomcat/bayeux/UUIDGenerator.java
trunk/java/org/apache/tomcat/bayeux/request/
trunk/java/org/apache/tomcat/bayeux/request/MetaConnectRequest.java
trunk/java/org/apache/tomcat/bayeux/request/MetaDisconnectRequest.java
trunk/java/org/apache/tomcat/bayeux/request/MetaHandshakeRequest.java
trunk/java/org/apache/tomcat/bayeux/request/MetaSubscribeRequest.java
trunk/java/org/apache/tomcat/bayeux/request/MetaUnsubscribeRequest.java
trunk/java/org/apache/tomcat/bayeux/request/PublishRequest.java
trunk/java/org/apache/tomcat/util/json/
trunk/java/org/apache/tomcat/util/json/JSONArray.java
trunk/java/org/apache/tomcat/util/json/JSONException.java
trunk/java/org/apache/tomcat/util/json/JSONObject.java
trunk/java/org/apache/tomcat/util/json/JSONString.java
trunk/java/org/apache/tomcat/util/json/JSONStringer.java
trunk/java/org/apache/tomcat/util/json/JSONTokener.java
trunk/java/org/apache/tomcat/util/json/JSONWriter.java
Modified:
trunk/NOTICE
trunk/build.xml
trunk/conf/web.xml
trunk/webapps/docs/changelog.xml
Log:
- Add the bayeux code, totally untested right now.
- Will add the example app later.
Modified: trunk/NOTICE
===================================================================
--- trunk/NOTICE 2008-09-18 15:57:52 UTC (rev 783)
+++ trunk/NOTICE 2008-09-19 01:53:57 UTC (rev 784)
@@ -7,13 +7,24 @@
This product includes software developed by
The Apache Software Foundation (
http://www.apache.org/).
-The Windows Installer is built with the Nullsoft
-Scriptable Install Sysem (NSIS), which is
-open source software. The original software and
+The Windows Installer is built with the
+Nullsoft Scriptable Install Sysem (NSIS), which is
+open source software. The original software and
related information is available at
http://nsis.sourceforge.net.
Java compilation software for JSP pages is provided by Eclipse,
-which is open source software. The orginal software and
+which is open source software. The orginal software and
related infomation is available at
http://www.eclipse.org.
+
+org.apache.tomcat.util.json
+Copyright (c) 2002
JSON.org
+
+org.apache.cometd.bayeux is derivative work originating at the Dojo Foundation
+
+org.apache.tomcat.bayeux
+Copyright 2007-2008 Guy Molinari
+Copyright 2007-2008 Filip Hanik
+Copyright 2007 Dojo Foundation
+Copyright 2007 Mort Bay Consulting Pty. Ltd.
Modified: trunk/build.xml
===================================================================
--- trunk/build.xml 2008-09-18 15:57:52 UTC (rev 783)
+++ trunk/build.xml 2008-09-19 01:53:57 UTC (rev 784)
@@ -50,6 +50,7 @@
<property name="catalina-ant.jar"
value="${tomcat.build}/lib/catalina-ant.jar"/>
<property name="catalina-optional.jar"
value="${tomcat.build}/lib/catalina-optional.jar"/>
<property name="tomcat-coyote.jar"
value="${tomcat.build}/lib/tomcat-coyote.jar"/>
+ <property name="tomcat-bayeux.jar"
value="${tomcat.build}/lib/tomcat-bayeux.jar"/>
<property name="jasper.jar"
value="${tomcat.build}/lib/jasper.jar"/>
<property name="jasper-el.jar"
value="${tomcat.build}/lib/jasper-el.jar"/>
@@ -249,6 +250,17 @@
</fileset>
</jar>
+ <!-- Bayeux -->
+ <jar jarfile="${tomcat-bayeux.jar}">
+ <fileset dir="${tomcat.classes}">
+ <include name="org/apache/cometd/**" />
+ <include name="org/apache/tomcat/bayeux/**" />
+ <!-- Javadoc and i18n exclusions -->
+ <exclude name="**/package.html" />
+ <exclude name="**/LocalStrings_*" />
+ </fileset>
+ </jar>
+
<!-- Jasper Implementation JAR File -->
<jar jarfile="${jasper.jar}">
<fileset dir="${tomcat.classes}">
@@ -574,9 +586,11 @@
<include name="org/apache/naming/**" />
<include name="org/apache/comet/**" />
<include name="org/apache/coyote/**" />
+ <include name="org/apache/tomcat/bayeux/**" />
<include name="org/apache/tomcat/jni/**" />
<include name="org/apache/tomcat/util/**" />
<include name="org/apache/jasper/**" />
+ <include name="org/apache/cometd/bayeux/**" />
<include name="org/apache/el/**" />
<include name="org/jboss/servlet/**" />
<include name="org/jboss/web/**" />
@@ -695,6 +709,13 @@
<param name="destfile" value="${tomcat-dbcp.jar}" />
</antcall>
+ <!-- Download json libraries
+ <antcall target="downloadfile">
+ <param name="sourcefile" value="${json-lib.loc}"/>
+ <param name="destfile" value="${json-lib.jar}"/>
+ <param name="destdir" value="${json-lib.home}"/>
+ </antcall> -->
+
<!-- Build Jasper JDT bundle -->
<antcall target="downloadzip">
<param name="sourcefile" value="${jdt.loc}"/>
Modified: trunk/conf/web.xml
===================================================================
--- trunk/conf/web.xml 2008-09-18 15:57:52 UTC (rev 783)
+++ trunk/conf/web.xml 2008-09-19 01:53:57 UTC (rev 784)
@@ -49,6 +49,9 @@
<!-- readmeFile File name to display with the directory -->
<!-- contents. [null] -->
<!-- -->
+ <!-- useAcceptRanges Should the Accept-Ranges header be included -->
+ <!-- in responses where appropriate? [true] -->
+ <!-- -->
<!-- sendfileSize If the connector used supports sendfile, this -->
<!-- represents the minimal file size in KB for -->
<!-- which sendfile will be used. Use a negative -->
Added: trunk/java/org/apache/cometd/bayeux/Bayeux.java
===================================================================
--- trunk/java/org/apache/cometd/bayeux/Bayeux.java (rev 0)
+++ trunk/java/org/apache/cometd/bayeux/Bayeux.java 2008-09-19 01:53:57 UTC (rev 784)
@@ -0,0 +1,242 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cometd.bayeux;
+
+import java.util.List;
+
+/** Bayeux Interface.<br/>
+ * This interface represents the server side API for the Bayeux messaging protocol.
+ * Bayeux is a simple subscribe/publish/receive methodology, not far from JMS, but much
simplified.<br/>
+ * It is used both by the actual implementation and by server side clients.<br/>
+ * Server side clients use this to create, retrieve and subscribe to channels.
+ * Server side clients are represented, just like remote clients, through the Client
interface.
+ * <br/>
+ * The Bayeux implementations is intended to be thread safe and multiple threads may
simultaneously call Bayeux methods.
+ * <br/>
+ * The Bayeux object, is the starting point for any cometd application relying on the
Bayeux object.
+ * Dependent on the container, the Bayeux object will be stored in the
<code>javax.servlet.ServletContext</code> object
+ * as an attribute under the name
<code>Bayeux.DOJOX_COMETD_BAYEUX</code><br/>
+ * To retrieve this object, one would simply call<br/>
+ * <code>Bayeux bx =
(Bayeux)getServletContext().getAttribute(Bayeux.DOJOX_COMETD_BAYEUX);
+ * <br/><br/>
+ * The Bayeux protocol is pretty straight forward and includes a bunch of messaging that
is not needed to be known to clients,
+ * both server side and remote clients.
+ * This object gets initialized by a container dependent servlet, and the servlet then
handles all Bayeux communication from the client.
+ * Remote messsages are delivered to channels, and to server side clients using the
<code>Listener</code> interface.<br/>
+ * <br/>
+ * A <code>Bayeux session</code> is active as long as the webapp hosting the
Bayeux object is active.<br/>
+ * When the webapplication shuts down, the Bayeux object will unsubscribe all clients and
remove all the active channels.
+ *
+ * @author Greg Wilkins
+ * @author Filip Hanik
+ */
+public interface Bayeux {
+
+ /**Meta definitions for channels*/
+ public static final String META="/meta";
+ /**Meta definitions for channels*/
+ public static final String META_SLASH="/meta/";
+ /**Meta definitions for channels - connect message*/
+ public static final String META_CONNECT="/meta/connect";
+ /**Meta definitions for channels - client messsage*/
+ public static final String META_CLIENT="/meta/client";
+ /**Meta definitions for channels - disconnect messsage*/
+ public static final String META_DISCONNECT="/meta/disconnect";
+ /**Meta definitions for channels - handshake messsage*/
+ public static final String META_HANDSHAKE="/meta/handshake";
+ /**Meta definitions for channels - ping messsage*/
+ public static final String META_PING="/meta/ping";
+ /**Meta definitions for channels - reconnect messsage
+ * @deprecated
+ */
+ public static final String META_RECONNECT="/meta/reconnect";
+ /**Meta definitions for channels - status messsage*/
+ public static final String META_STATUS="/meta/status";
+ /**Meta definitions for channels - subscribe messsage*/
+ public static final String META_SUBSCRIBE="/meta/subscribe";
+ /**Meta definitions for channels - unsubscribe messsage*/
+ public static final String META_UNSUBSCRIBE="/meta/unsubscribe";
+ /*Field names inside Bayeux messages*/
+ /**Field names inside Bayeux messages - clientId field*/
+ public static final String CLIENT_FIELD="clientId";
+ /**Field names inside Bayeux messages - data field*/
+ public static final String DATA_FIELD="data";
+ /**Field names inside Bayeux messages - channel field*/
+ public static final String CHANNEL_FIELD="channel";
+ /**Field names inside Bayeux messages - id field*/
+ public static final String ID_FIELD="id";
+ /**Field names inside Bayeux messages - error field*/
+ public static final String ERROR_FIELD="error";
+ /**Field names inside Bayeux messages - timestamp field*/
+ public static final String TIMESTAMP_FIELD="timestamp";
+ /**Field names inside Bayeux messages - transport field*/
+ public static final String TRANSPORT_FIELD="transport";
+ /**Field names inside Bayeux messages - advice field*/
+ public static final String ADVICE_FIELD="advice";
+ /**Field names inside Bayeux messages - successful field*/
+ public static final String SUCCESSFUL_FIELD="successful";
+ /**Field names inside Bayeux messages - subscription field*/
+ public static final String SUBSCRIPTION_FIELD="subscription";
+ /**Field names inside Bayeux messages - ext field*/
+ public static final String EXT_FIELD="ext";
+ /**Field names inside Bayeux messages - connectionType field*/
+ public static final String CONNECTION_TYPE_FIELD="connectionType";
+ /**Field names inside Bayeux messages - version field*/
+ public static final String VERSION_FIELD="version";
+ /**Field names inside Bayeux messages - minimumVersion field*/
+ public static final String MIN_VERSION_FIELD="minimumVersion";
+ /**Field names inside Bayeux messages - supportedConnectionTypes field*/
+ public static final String
SUPP_CONNECTION_TYPE_FIELD="supportedConnectionTypes";
+ /**Field names inside Bayeux messages - json-comment-filtered field*/
+ public static final String
JSON_COMMENT_FILTERED_FIELD="json-comment-filtered";
+ /**Field names inside Bayeux messages - reconnect field*/
+ public static final String RECONNECT_FIELD = "reconnect";
+ /**Field names inside Bayeux messages - interval field*/
+ public static final String INTERVAL_FIELD = "interval";
+ /**Field values inside Bayeux messages - retry response*/
+ public static final String RETRY_RESPONSE = "retry";
+ /**Field values inside Bayeux messages - handshake response*/
+ public static final String HANDSHAKE_RESPONSE = "handshake";
+ /**Field values inside Bayeux messages - none response*/
+ public static final String NONE_RESPONSE = "none";
+ /**Service channel names-starts with*/
+ public static final String SERVICE="/service";
+ /**Service channel names-trailing slash*/
+ public static final String SERVICE_SLASH="/service/";
+ /*Transport types*/
+ /**Transport types - long polling*/
+ public static final String TRANSPORT_LONG_POLL="long-polling";
+ /**Transport types - callback polling*/
+ public static final String TRANSPORT_CALLBACK_POLL="callback-polling";
+ /**Transport types - iframe*/
+ public static final String TRANSPORT_IFRAME="iframe";
+ /**Transport types - flash*/
+ public static final String TRANSPORT_FLASH="flash";
+ /** ServletContext attribute name used to obtain the Bayeux object */
+ public static final String DOJOX_COMETD_BAYEUX="dojox.cometd.bayeux";
+ /*http field names*/
+ /**http helpers - text/json content type*/
+ public static final String JSON_CONTENT_TYPE="text/json";
+ /**http helpers - parameter name for json message*/
+ public static final String MESSAGE_PARAMETER="message";
+ /**http helpers - name of the jsonp parameter*/
+ public static final String JSONP_PARAMETER="jsonp";
+ /**http helpers - default name of the jsonp callback function*/
+ public static final String JSONP_DEFAULT_NAME="jsonpcallback";
+
+ /*--Client----------------------------------------------------------- */
+ /**
+ * Creates a new server side client. This method is to be invoked
+ * by server side objects only. You cannot create a remote client by using this
method.
+ * A client represents an entity that can subscribe to channels and publish and
receive messages
+ * through these channels
+ * @param idprefix String - the prefix string for the id generated, can be null
+ * @param listener Listener - a callback object to be called when messages are to be
delivered to the new client
+ * @return Client - returns an implementation of the client interface.
+ */
+ public Client newClient(String idprefix, Listener listener);
+
+ /**
+ * retrieve a client based on an ID. Will return null if the client doesn't
exist.
+ * @param clientid String
+ * @return Client-null if the client doesn't exist.returns the client if it
does.
+ */
+ public Client getClient(String clientid);
+
+ /**
+ * Returns a non modifiable list of all the clients that are currently active
+ * in this Bayeux session
+ * @return List<Client> - a list containing all clients. The List can not be
modified.
+ */
+ public List<Client> getClients();
+
+ /**
+ * Returns true if a client with the given id exists.<br/>
+ * Same as executing <code>getClient(id)!=null</code>.
+ * @param clientId String
+ * @return boolean - true if the client exists
+ */
+ public boolean hasClient(String clientId);
+
+ /**
+ * Removes the client all together.
+ * This will unsubscribe the client to any channels it may be subscribed to
+ * and remove it from the list.
+ * @param client Client
+ * @return Client - returns the client that was removed, or null if no client was
removed.
+ */
+ public Client remove(Client client);
+
+
+ /*--Channel---------------------------------------------------------- */
+ /**
+ * Returns the channel for a given channel id.
+ * If the channel doesn't exist, and the <code>create</code>
parameter is set to true,
+ * the channel will be created and added to the list of active channels.<br/>
+ * if <code>create</code> is set to false, and the channel doesn't
exist, null will be returned.
+ * @param channelId String - the id of the channel to be retrieved or created
+ * @param create boolean - true if the Bayeux impl should create the channel
+ * @return Channel - null if <code>create</code> is set to false and the
channel doesn't exist,
+ * otherwise it returns a channel object.
+ */
+ public Channel getChannel(String channelId, boolean create);
+
+ /**
+ * Returns a list of currently active channels in this Bayeux session.
+ * @return List<Channel>
+ */
+ public List<Channel> getChannels();
+
+ /**
+ * Removes a channel from the Bayeux object.
+ * This will also unsubscribe all the clients currently subscribed to the
+ * the channel.
+ * @param channel Channel - the channel to be removed
+ * @return Channel - returns the channel that was removed, or null if no channel was
removed.
+ */
+ public Channel remove(Channel channel);
+
+ /**
+ * returns true if a channel with the given channelId exists.
+ * <br/>Same as executing
<code>Bayeux.getChannel(channelId,false)!=null</code>
+ * @param channelId String
+ * @return boolean - true if the channel exists.
+ */
+ public boolean hasChannel(String channelId);
+
+ /* --Message---------------------------------------------------------- */
+ /**
+ * Creates a new message to be sent by a server side client.
+ * @return Message - returns a new Message object, that has a unique id.
+ */
+ public Message newMessage(Client from);
+
+
+ /*--Security policy----------------------------------------------------------- */
+ /**
+ * Returns the security policy associated with this Bayeux session
+ * @return SecurityPolicy
+ */
+ public SecurityPolicy getSecurityPolicy();
+
+ /**
+ * Sets the security policy to be used in this Bayeux session
+ * @param securityPolicy SecurityPolicy
+ */
+ public void setSecurityPolicy(SecurityPolicy securityPolicy);
+
+}
\ No newline at end of file
Added: trunk/java/org/apache/cometd/bayeux/Channel.java
===================================================================
--- trunk/java/org/apache/cometd/bayeux/Channel.java (rev 0)
+++ trunk/java/org/apache/cometd/bayeux/Channel.java 2008-09-19 01:53:57 UTC (rev 784)
@@ -0,0 +1,103 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cometd.bayeux;
+
+import java.util.List;
+
+/**
+ * A Bayeux Channel represents a channel used to receive messages from and to publish
messages to.
+ * In order to publish messages to or receive messages from, one must subscribe to the
channel.
+ * This is easily done by invoking the <code>subscribe</code> method.
+ * A channel is created by calling the
<code>Bayeux.getChannel(channelId,true)</code> method.
+ * A channel can be created either server side by invoking the getChannel, or client
side
+ * by using the /meta/subscribe message without a wildcard.
+ * @author Greg Wilkins
+ * @author Filip Hanik
+ */
+public interface Channel
+{
+ /**
+ * Returns the id for this channel. The id is unique within bayeux session.
+ * @return String - will never be null.
+ */
+ public String getId();
+
+ /**
+ * Publishes a message to all the subscribers of this channel.
+ * The <code>from</code> is contained within the message, by calling
+ * <code>msg.getClient()</code>
+ * @param data - the message to be published, can not be null.
+ */
+ public void publish(Message msg);
+
+ /**
+ * Publishes more than one message to all the subscribers of this channel.
+ * The <code>from</code> is contained within the message, by calling
+ * <code>msg[x].getClient()</code>
+ * @param data - the message to be published, can not be null.
+ */
+ public void publish(Message[] msgs);
+
+ /**
+ * Non persistent channels are removed when the last subscription is
+ * removed. Persistent channels survive periods without any subscribers.
+ * @return true if the Channel will persist without any subscription.
+ */
+ public boolean isPersistent();
+
+ /**
+ * @param persistent true if the Channel will persist without any subscription.
+ * @see isPersistent
+ */
+ public void setPersistent(boolean persistent);
+
+ /**
+ * Subscribes a client to a channel.
+ * @param subscriber - the client to be subscribed. If the client
+ * already is subscribed, this call will not create a duplicate subscription.
+ */
+ public void subscribe(Client subscriber);
+
+ /**
+ * Unsubscribes a client from a channel
+ * @param subscriber - the client to be subscribed.
+ * @return - returns the client that was unsubscribed, or null if the client
wasn't subscribed.
+ */
+ public Client unsubscribe(Client subscriber);
+
+ /**
+ * returns a non modifiable list of all the subscribers to this
+ * channel.
+ * @return a list of subscribers
+ */
+ public List<Client> getSubscribers();
+
+ /**
+ * Adds a data filter to this channel. All messages received by this channel
+ * will run through this filter.
+ * @param filter Filter
+ */
+ public void addFilter(DataFilter filter);
+
+ /**
+ * Removes a filter from this channel.
+ * returns the filter that was removed, or null if the filter wasn't in the
channel.
+ * @param filter Filter
+ * @return Filter - null if no filter was removed otherwise it returns the filter
that was removed.
+ */
+ public DataFilter removeFilter(DataFilter filter);
+}
\ No newline at end of file
Added: trunk/java/org/apache/cometd/bayeux/Client.java
===================================================================
--- trunk/java/org/apache/cometd/bayeux/Client.java (rev 0)
+++ trunk/java/org/apache/cometd/bayeux/Client.java 2008-09-19 01:53:57 UTC (rev 784)
@@ -0,0 +1,91 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cometd.bayeux;
+
+
+
+/** A Bayeux Client.
+ * <p>
+ * A client may subscribe to channels and publish messages to channels.
+ * Client instances should not be directly created by uses, but should
+ * be obtained via the {@link Bayeux#getClient(String)} or {@link
Bayeux#newClient(String, Listener)}
+ * methods.
+ * </p>
+ * <p>
+ * Three types of client may be represented by this interface:<nl>
+ * <li>The server representation of a remote client connected via HTTP,
+ * automatically created by the Bayeux server when a connect message comes
in</li>
+ * <li>A server side client, created by the application using the {@link
Bayeux#newClient(String, Listener)} method</li>
+ * <li>A java client connected to a remote Bayeux server - not
implemented</li>
+ * </nl>
+ * @author Greg Wilkins
+ * @author Filip Hanik
+ */
+public interface Client
+{
+ /**
+ * Returns a unique id for this client. The id is unique within this Bayeux session.
+ * @return String - will not be null
+ */
+ public String getId();
+
+ /**
+ * Returns true if this client is holding messages to be delivered to the remote
client.
+ * This method always returns false for local clients, since messages are delivered
instantly using the
+ * Listener(callback) object
+ * @return boolean
+ */
+ public boolean hasMessages();
+
+ /**
+ * Deliver a message to this client only
+ * Deliver a message directly to the client. The message is not
+ * filtered or published to a channel.
+ * @param message
+ */
+ public void deliver(Message message);
+
+ /**
+ * Deliver a batch of messages to this client only
+ * Deliver a batch messages directly to the client. The messages are not
+ * filtered or published to a channel.
+ * @param message
+ */
+ public void deliver(Message[] message);
+
+ /**
+ * @return True if the client is local. False if this client is either a remote HTTP
client or
+ * a java client to a remote server.
+ */
+ public boolean isLocal();
+
+ /**
+ * Starts a batch, no messages will be delivered until endBatch is called.
+ * Batches can be nested, and messages will only be delivered after
+ * the last endBatch has been called.
+ */
+ public void startBatch();
+
+ /**
+ * Ends a batch. since batches can be nested, messages will only be delivered
+ * after the endBatch has been called as many times as startBatch has.
+ */
+ public void endBatch();
+
+
+}
\ No newline at end of file
Added: trunk/java/org/apache/cometd/bayeux/DataFilter.java
===================================================================
--- trunk/java/org/apache/cometd/bayeux/DataFilter.java (rev 0)
+++ trunk/java/org/apache/cometd/bayeux/DataFilter.java 2008-09-19 01:53:57 UTC (rev 784)
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cometd.bayeux;
+
+/**
+ * Data Filter<br/>
+ * Data filters are used to transform data as it is sent to a Channel.
+ * Messages are filtered as the message is published to a channel, invoking the
+ * {@link Channel#publish(Message)} method.<br/>
+ * This method gets invoked in two different scenarios, the first being when a message is
received from
+ * a remote client, and the Bayeux implementation invokes the publish method directly.
+ * The second scenario is when a local client invokes {@link Channel#publish(Message)}
directly in the local JVM.
+ * @author Greg Wilkins
+ * @author Filip Hanik
+ *
+ */
+public interface DataFilter
+{
+ /**
+ * Runs a message through the filter. Filtering can only modify an existing object,
it can not replace it.
+ * @param data Message - the message to be filtered, may not be null
+ */
+ public void filter(Message data);
+}
Added: trunk/java/org/apache/cometd/bayeux/Listener.java
===================================================================
--- trunk/java/org/apache/cometd/bayeux/Listener.java (rev 0)
+++ trunk/java/org/apache/cometd/bayeux/Listener.java 2008-09-19 01:53:57 UTC (rev 784)
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cometd.bayeux;
+
+/**
+ * Cometd Listener interface.<br/>
+ * For local clients, in order to receive messages, they pass in a callback object
+ * when the local client is created using the {@link Bayeux#newClient(String,Listener)}
method.
+ * This callback object, implementing the Listener interface, is used to deliver messages
to local, in JVM, clients.
+ * @author Greg Wilkins
+ * @author Filip Hanik
+ *
+ */
+public interface Listener
+{
+ /**
+ * This method is called when the client is removed (explicitly or from a timeout)
+ * @param timeout - true if the client was removed from a timeout
+ * false if it was removed explicitly.
+ */
+ public void removed(boolean timeout);
+
+ /**
+ * Invoked when a message is delivered to the client.
+ * The message contains the message itself, as well as what channel this message came
through
+ * and who the sender is. If someone invoked {@link Client#deliver(Message)} then the
channel reference will
+ * be null.
+ * @param msg
+ */
+ public void deliver(Message[] msg);
+}
Added: trunk/java/org/apache/cometd/bayeux/Message.java
===================================================================
--- trunk/java/org/apache/cometd/bayeux/Message.java (rev 0)
+++ trunk/java/org/apache/cometd/bayeux/Message.java 2008-09-19 01:53:57 UTC (rev 784)
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cometd.bayeux;
+
+import java.util.Map;
+
+/**
+ * A Bayeux Message<br/>
+ * A Bayeux message is a Map of String/Object key value pairs representing the data in
the message.
+ * The message contains information about the channel it was published through and who
the sender was
+ *
+ * @author Greg Wilkins
+ * @author Filip Hanik
+ */
+public interface Message extends Map<String,Object>
+{
+ /**
+ * Returns a reference to the client that sent this message
+ * @return Client - may be null
+ */
+ public Client getClient();
+ /**
+ * Returns a reference to the channel that this message was published throuhg
+ * @return Channel - may be null
+ */
+ public Channel getChannel();
+ /**
+ * Returns the unique id of this message
+ * @return String
+ */
+ public String getId();
+
+ /**
+ * Sets the time to live in milliseconds. If the message hasn't been delivered
+ * when the time passed after the creation time is longer than the TTL the message
will
+ * expire and removed from any delivery queues.
+ * @param ttl long
+ */
+ public void setTTL(long ttl);
+
+ /**
+ * Returns the time to live (in milliseconds) for this message
+ * @return long
+ */
+ public long getTTL();
+
+ /**
+ * returns the timestamp in milliseconds(System.currentTimeMillis()) of when this
message was created.
+ * @return long
+ */
+ public long getCreationTime();
+}
+
+
Added: trunk/java/org/apache/cometd/bayeux/SecurityPolicy.java
===================================================================
--- trunk/java/org/apache/cometd/bayeux/SecurityPolicy.java (rev
0)
+++ trunk/java/org/apache/cometd/bayeux/SecurityPolicy.java 2008-09-19 01:53:57 UTC (rev
784)
@@ -0,0 +1,28 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cometd.bayeux;
+
+/**
+ * @author Greg Wilkins
+ */
+public interface SecurityPolicy
+{
+ boolean canHandshake(Message message);
+ boolean canCreate(Client client,String channel,Message message);
+ boolean canSubscribe(Client client,String channel,Message messsage);
+ boolean canPublish(Client client,String channel,Message messsage);
+}
Added: trunk/java/org/apache/tomcat/bayeux/BayeuxException.java
===================================================================
--- trunk/java/org/apache/tomcat/bayeux/BayeuxException.java (rev
0)
+++ trunk/java/org/apache/tomcat/bayeux/BayeuxException.java 2008-09-19 01:53:57 UTC (rev
784)
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.bayeux;
+/**
+ *
+ * @author Filip Hanik
+ * @version 1.0
+ */
+public class BayeuxException extends Exception {
+ public BayeuxException() {
+ super();
+ }
+
+ public BayeuxException(String message) {
+ super(message);
+ }
+
+ public BayeuxException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public BayeuxException(Throwable cause) {
+ super(cause);
+ }
+}
\ No newline at end of file
Added: trunk/java/org/apache/tomcat/bayeux/BayeuxRequest.java
===================================================================
--- trunk/java/org/apache/tomcat/bayeux/BayeuxRequest.java (rev
0)
+++ trunk/java/org/apache/tomcat/bayeux/BayeuxRequest.java 2008-09-19 01:53:57 UTC (rev
784)
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.bayeux;
+
+import org.apache.tomcat.bayeux.HttpError;
+
+/**
+ * An interface that defines methods for managing Bayeux request meta
+ * messages.
+ *
+ * @author Guy A. Molinari
+ * @author Filip Hanik
+ * @version 0.9
+ */
+public interface BayeuxRequest {
+
+ public static final String LAST_REQ_ATTR =
"org.apache.cometd.bayeux.last_request";
+ public static final String CURRENT_REQ_ATTR =
"org.apache.cometd.bayeux.current_request";
+ public static final String JSON_MSG_ARRAY =
"org.apache.cometd.bayeux.json_msg_array";
+
+ /**
+ * Validates a specific request.
+ * This method must be called prior to process()
+ * as a request can do pre processing in the validate method.
+ * <br/>
+ * Should the validation fail, an error object is returned
+ * containing an error message, and potentially a stack trace
+ * if an exception was generated
+ * @return HttpError - null if no error was detected, an HttpError object containing
information about the error.
+ */
+ public HttpError validate();
+
+ /**
+ * processes a remote client Bayeux message
+ * @param prevops - the operation requested by the previous request, in case of
chained requests.
+ * @return int - returns the interest operation for a CometEvent. Currently not used
+ * @throws BayeuxException - if an error was detected, and the appropriate error
response couldn't be delivered to the client.
+ */
+ public int process(int prevops) throws BayeuxException;
+}
Added: trunk/java/org/apache/tomcat/bayeux/BayeuxServlet.java
===================================================================
--- trunk/java/org/apache/tomcat/bayeux/BayeuxServlet.java (rev
0)
+++ trunk/java/org/apache/tomcat/bayeux/BayeuxServlet.java 2008-09-19 01:53:57 UTC (rev
784)
@@ -0,0 +1,240 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.bayeux;
+
+import java.io.IOException;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.cometd.bayeux.Bayeux;
+import org.apache.tomcat.util.json.JSONArray;
+import org.apache.tomcat.util.json.JSONException;
+import org.apache.tomcat.util.json.JSONObject;
+import org.jboss.servlet.http.HttpEvent;
+import org.jboss.servlet.http.HttpEventServlet;
+
+/**
+ *
+ * @author Filip Hanik
+ * @author Guy Molinari
+ * @version 1.0
+ */
+public class BayeuxServlet implements HttpEventServlet {
+
+
+ /**
+ * The debugging detail level for this servlet.
+ */
+ protected int debug = 0;
+
+
+ /**
+ * Attribute to hold the TomcatBayeux object in the servlet context
+ */
+ public static final String TOMCAT_BAYEUX_ATTR = Bayeux.DOJOX_COMETD_BAYEUX;
+
+ /**
+ * Servlet config - for future use
+ */
+ protected ServletConfig servletConfig;
+
+ /**
+ * Reference to the global TomcatBayeux object
+ */
+ protected TomcatBayeux tb;
+
+ /**
+ * Upon servlet destruction, the servlet will clean up the
+ * TomcatBayeux object and terminate any outstanding events.
+ */
+ public void destroy() {
+ servletConfig = null;
+ //to do, close all outstanding comet events
+ //tb.destroy();
+ tb = null;//TO DO, close everything down
+
+ }
+
+ /**
+ * Returns the preconfigured connection timeout.
+ * If no timeout has been configured as a servlet init parameter named
<code>timeout</code>
+ * then the default of 2min will be used.
+ * @return int - the timeout for a connection in milliseconds
+ */
+ protected int getTimeout() {
+ String timeoutS = servletConfig.getInitParameter("timeout");
+ int timeout = 120*1000; //2 min
+ try {
+ timeout = Integer.parseInt(timeoutS);
+ }catch (NumberFormatException nfe) {
+ //ignore, we have a default value
+ }
+ return timeout;
+ }
+
+ protected int getReconnectInterval() {
+ String rs = servletConfig.getInitParameter("reconnectInterval");
+ int rct = 5000; //5 seconds
+ try {
+ rct = Integer.parseInt(rs);
+ }catch (NumberFormatException nfe) {
+ //ignore, we have a default value
+ }
+ return rct;
+ }
+
+
+ public void event(HttpEvent cometEvent) throws IOException, ServletException {
+ HttpEvent.EventType type = cometEvent.getType();
+ if (debug > 0) {
+
getServletConfig().getServletContext().log("["+Thread.currentThread().getName()+"]
Received Comet Event type="+type);
+ }
+ synchronized (cometEvent) {
+ switch (type) {
+ case BEGIN:
+ cometEvent.setTimeout(getTimeout());
+ break;
+ case READ:
+ checkBayeux(cometEvent);
+ break;
+ case EOF:
+ case EVENT:
+ case WRITE:
+ break;
+ case ERROR:
+ case END:
+ case TIMEOUT:
+ tb.remove(cometEvent);
+ cometEvent.close();
+ break;
+ }
+ }//synchronized
+ }//event
+
+ /**
+ *
+ * @param cometEvent CometEvent
+ * @return boolean - true if we comet event stays open
+ * @throws IOException
+ * @throws UnsupportedOperationException
+ */
+ protected void checkBayeux(HttpEvent cometEvent) throws IOException,
UnsupportedOperationException {
+ //we actually have data.
+ //data can be text/json or
+ if
(Bayeux.JSON_CONTENT_TYPE.equals(cometEvent.getHttpServletRequest().getContentType())) {
+ //read and decode the bytes according to content length
+
getServletConfig().getServletContext().log("["+Thread.currentThread().getName()+"]
JSON encoding not supported, will throw an exception and abort the request.");
+ int contentlength = cometEvent.getHttpServletRequest().getContentLength();
+ throw new UnsupportedOperationException("Decoding
"+Bayeux.JSON_CONTENT_TYPE+" not yet implemented.");
+ } else { //GET method or application/x-www-form-urlencoded
+ String message =
cometEvent.getHttpServletRequest().getParameter(Bayeux.MESSAGE_PARAMETER);
+ if (debug > 0) {
+
getServletConfig().getServletContext().log("["+Thread.currentThread().getName()+"]
Received JSON message:"+message);
+ }
+ try {
+ int action = handleBayeux(message, cometEvent);
+ if (debug > 0) {
+
getServletConfig().getServletContext().log("["+Thread.currentThread().getName()+"]
Bayeux handling complete, action result="+action);
+ }
+ if (action<=0) {
+ cometEvent.close();
+ }
+ }catch (Exception x) {
+ tb.remove(cometEvent);
+ getServletConfig().getServletContext().log(x, "Exception in
check");
+ cometEvent.close();
+ }
+ }
+ }
+
+ protected int handleBayeux(String message, HttpEvent event) throws IOException,
ServletException {
+ int result = 0;
+ if (message==null || message.length()==0) return result;
+ try {
+ BayeuxRequest request = null;
+ //a message can be an array of messages
+ JSONArray jsArray = new JSONArray(message);
+ for (int i = 0; i < jsArray.length(); i++) {
+ JSONObject msg = jsArray.getJSONObject(i);
+
+ if (debug > 0) {
+
getServletConfig().getServletContext().log("["+Thread.currentThread().getName()+"]
Processing bayeux message:"+msg);
+ }
+ request = RequestFactory.getRequest(tb,event,msg);
+ if (debug > 0) {
+
getServletConfig().getServletContext().log("["+Thread.currentThread().getName()+"]
Processing bayeux message using request:"+request);
+ }
+ result = request.process(result);
+ if (debug > 0) {
+
getServletConfig().getServletContext().log("["+Thread.currentThread().getName()+"]
Processing bayeux message result:"+result);
+ }
+ }
+ if (result>0 && request!=null) {
+ event.getHttpServletRequest().setAttribute(BayeuxRequest.LAST_REQ_ATTR,
request);
+ ClientImpl ci =
(ClientImpl)tb.getClient(((RequestBase)request).getClientId());
+ ci.addCometEvent(event);
+ if (debug > 0) {
+
getServletConfig().getServletContext().log("["+Thread.currentThread().getName()+"]
Done bayeux message added to request attribute");
+ }
+ } else if (result == 0 && request!=null) {
+
RequestBase.deliver(event,(ClientImpl)tb.getClient(((RequestBase)request).getClientId()));
+ if (debug > 0) {
+
getServletConfig().getServletContext().log("["+Thread.currentThread().getName()+"]
Done bayeux message, delivered to client");
+ }
+ }
+
+ }catch (JSONException x) {
+ getServletConfig().getServletContext().log(x, "Error");//to do impl
error handling
+ result = -1;
+ }catch (BayeuxException x) {
+ getServletConfig().getServletContext().log(x, "Error"); //to do
impl error handling
+ result = -1;
+ }
+ return result;
+ }
+
+ public ServletConfig getServletConfig() {
+ return servletConfig;
+ }
+
+ public String getServletInfo() {
+ return "Tomcat/BayeuxServlet/1.0";
+ }
+
+ public void init(ServletConfig servletConfig) throws ServletException {
+
+ this.servletConfig = servletConfig;
+ ServletContext ctx = servletConfig.getServletContext();
+ if (ctx.getAttribute(TOMCAT_BAYEUX_ATTR)==null)
+ ctx.setAttribute(TOMCAT_BAYEUX_ATTR,new TomcatBayeux());
+ this.tb = (TomcatBayeux)ctx.getAttribute(TOMCAT_BAYEUX_ATTR);
+ tb.setReconnectInterval(getReconnectInterval());
+ }
+
+ public void service(ServletRequest servletRequest, ServletResponse servletResponse)
throws ServletException, IOException {
+ if (servletResponse instanceof HttpServletResponse) {
+ ( (HttpServletResponse) servletResponse).sendError(500, "Misconfigured
Tomcat server, must be configured to support Comet operations.");
+ } else {
+ throw new ServletException("Misconfigured Tomcat server, must be
configured to support Comet operations for the Bayeux protocol.");
+ }
+ }
+}
Added: trunk/java/org/apache/tomcat/bayeux/ChannelImpl.java
===================================================================
--- trunk/java/org/apache/tomcat/bayeux/ChannelImpl.java (rev 0)
+++ trunk/java/org/apache/tomcat/bayeux/ChannelImpl.java 2008-09-19 01:53:57 UTC (rev
784)
@@ -0,0 +1,186 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.bayeux;
+
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.apache.cometd.bayeux.Channel;
+import org.apache.cometd.bayeux.Client;
+import org.apache.cometd.bayeux.DataFilter;
+import org.apache.cometd.bayeux.Message;
+
+/**
+ *
+ * @author Filip Hanik
+ * @version 1.0
+ */
+public class ChannelImpl implements Channel {
+
+ /**
+ * The unique id of this channel
+ */
+ protected String id = null;
+
+ /**
+ * A list of the current subscribers
+ */
+ protected LinkedList<Client> subscribers = new LinkedList<Client>();
+
+ /**
+ * A list of the current filters
+ */
+ protected LinkedList<DataFilter> filters = new LinkedList<DataFilter>();
+
+ /**
+ * Is this channel persistent, default value is true
+ */
+ protected boolean persistent = true;
+
+ /**
+ * Creates a new channel
+ * @param id String - the id of the channel, can not be null
+ */
+ protected ChannelImpl(String id) {
+ assert id != null;
+ this.id = id;
+ }
+
+ /**
+ * returns the id of this channel
+ * @return String
+ */
+ public String getId() {
+ return id;
+ }
+
+ /**
+ * Returns true if this channel matches the pattern to its id.
+ * The channel pattern can be a complete name like
<code>/service/mychannel</code>
+ * or it can be a wild card pattern like <code>/service/app2/**</code>
+ * @param pattern String according to the Bayeux specification section 2.2.1 Channel
Globbing, can not be null.
+ * @return boolean true if the id of this channel matches the pattern
+ */
+ public boolean matches(String pattern) {
+ if (pattern == null)
+ throw new NullPointerException("Channel pattern must not be
null.");
+ if (getId().equals(pattern))
+ return true;
+ int wildcardPos = pattern.indexOf("/*");
+ if (wildcardPos == -1)
+ return false;
+ boolean multiSegment = pattern.indexOf("**") != -1;
+ String leadSubstring = pattern.substring(0, wildcardPos);
+ if (leadSubstring == null)
+ return false;
+ if (multiSegment)
+ return getId().startsWith(leadSubstring);
+ else {
+ if (getId().length() <= wildcardPos + 2)
+ return false;
+ return !(getId().substring(wildcardPos + 2).contains("/"));
+ }
+ }
+
+
+
+ /**
+ * @return returns a non modifiable list of the subscribers for this channel.
+ */
+ public List<Client> getSubscribers() {
+ return Collections.unmodifiableList(subscribers);
+ }
+
+ /**
+ * @return true if the Channel will persist without any subscription.
+ */
+ public boolean isPersistent() {
+ return persistent;
+ }
+
+ public void publish(Message msg) {
+ publish(new Message[] {msg});
+ }
+
+ public void publish(Message[] msgs) {
+ if (msgs==null) return;
+ MessageImpl[] imsgs = new MessageImpl[msgs.length];
+ for (int i=0; msgs!=null && i<msgs.length; i++) {
+ Message data = msgs[i];
+
+ if (!(data instanceof MessageImpl))
+ throw new IllegalArgumentException("Invalid message class, you can
only publish messages "+
+ "created through the
Bayeux.newMessage() method");
+ /*if (log.isDebugEnabled()) {
+ log.debug("Publishing message:"+data+" to
channel:"+this);
+ }*/
+ //clone it so that we can set this channel as a reference
+ MessageImpl msg = (MessageImpl)((MessageImpl)data).clone();
+ //this is the channel it was delivered through
+ msg.setChannel(this);
+ //pass through filters
+ for (Iterator<DataFilter> it = filters.iterator(); it.hasNext(); ) {
+ it.next().filter(msg);
+ }
+ imsgs[i] = msg;
+ }
+ //deliver it to the clients
+ for (Iterator<Client> it = subscribers.iterator(); it.hasNext(); ) {
+ ClientImpl c = (ClientImpl)it.next();
+ c.deliverInternal(this,imsgs);
+ }
+
+ }
+
+ public void setPersistent(boolean persistent) {
+ this.persistent = persistent;
+ }
+
+ public void subscribe(Client subscriber) {
+ if (!subscribers.contains((subscriber))) {
+ subscribers.addLast(subscriber);
+ ((ClientImpl)subscriber).subscribed(this);
+ }
+ }
+
+ public Client unsubscribe(Client subscriber) {
+ if (subscribers.remove(subscriber)) {
+ ((ClientImpl)subscriber).unsubscribed(this);
+ return subscriber;
+ } else
+ return null;
+ }
+
+ public void addFilter(DataFilter filter) {
+ if (!filters.contains(filter))
+ filters.addLast(filter);
+ }
+
+ public DataFilter removeFilter(DataFilter filter) {
+ if ( filters.remove(filter) ) return filter;
+ else return null;
+ }
+
+ public String toString() {
+ StringBuffer buf = new StringBuffer(super.toString());
+ buf.append("; channelId=").append(getId());
+ return buf.toString();
+ }
+
+}
\ No newline at end of file
Added: trunk/java/org/apache/tomcat/bayeux/ClientImpl.java
===================================================================
--- trunk/java/org/apache/tomcat/bayeux/ClientImpl.java (rev 0)
+++ trunk/java/org/apache/tomcat/bayeux/ClientImpl.java 2008-09-19 01:53:57 UTC (rev 784)
@@ -0,0 +1,276 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.bayeux;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.cometd.bayeux.Bayeux;
+import org.apache.cometd.bayeux.Client;
+import org.apache.cometd.bayeux.Listener;
+import org.apache.cometd.bayeux.Message;
+import org.apache.tomcat.util.json.JSONObject;
+import org.jboss.servlet.http.HttpEvent;
+
+public class ClientImpl implements Client {
+
+ public static final int SUPPORT_CALLBACK_POLL = 0x1;
+ public static final int SUPPORT_LONG_POLL = 0x2;
+
+ public static final String COMET_EVENT_ATTR =
"org.apache.cometd.bayeux.client";
+
+ protected static LinkedList<Message> EMPTY_LIST = new
LinkedList<Message>();
+ /**
+ * queued message for remote clients.
+ */
+ protected LinkedList<Message> messages = null;
+
+ /**
+ *
+ */
+ protected Queue<HttpEvent> events = new LinkedList<HttpEvent>();
+
+ /**
+ * Unique id representing this client
+ */
+ protected String id;
+
+ /**
+ * supported connection types, defaults to long-polling
+ */
+ protected int supportedConnTypes = SUPPORT_LONG_POLL | SUPPORT_CALLBACK_POLL;
+
+ /**
+ * The desired connection type
+ */
+ protected int desirectConnType = SUPPORT_LONG_POLL;
+
+ /**
+ * Does this client use json-comment-filtered messages
+ */
+ protected boolean useJsonFiltered = false;
+
+ /**
+ * Same JVM clients, get local=true
+ */
+ protected boolean local;
+
+ /**
+ * The callback object for local clients
+ */
+ protected Listener listener;
+
+ protected AtomicInteger nrofsubscriptions = new AtomicInteger(0);
+
+ protected ClientImpl(String id, boolean local) {
+ this.id = id;
+ this.local = local;
+ if (!local) messages = new LinkedList<Message>();
+ }
+
+ protected ClientImpl(String id, HttpEvent event) {
+ this(id,false);
+ events = new ConcurrentLinkedQueue<HttpEvent>();
+ addCometEvent(event);
+ }
+
+ public synchronized void deliver(Message message) {
+ deliverInternal(null,new MessageImpl[] {(MessageImpl)message});
+ }
+
+ public synchronized void deliver(Message[] message) {
+ deliverInternal(null,message);
+ }
+
+ protected synchronized void deliverInternal(ChannelImpl channel, MessageImpl message)
{
+ deliverInternal(channel,new MessageImpl[] {message});
+ }
+
+ protected synchronized void deliverInternal(ChannelImpl channel, Message[] msgs) {
+ if (isLocal()) {
+ //local clients must have a listener
+ ArrayList<Message> list = new ArrayList<Message>();
+ for (int i=0; msgs!=null && i<msgs.length; i++) {
+ if (this!=msgs[i].getClient()) list.add(msgs[i]);
+ }
+ if (getListener() != null) {
+ getListener().deliver(list.toArray(new Message[0]));
+ }
+ } else {
+ for (int i=0; msgs!=null && i<msgs.length; i++) {
+ MessageImpl message = (MessageImpl)msgs[i];
+ if (this==message.getClient()) {
+ //dont deliver to ourself
+ continue;
+ }
+ //we are not implementing forever responses, if the client is connected
+ //then we will fire off the message
+ //first we check to see if we have any existing connections we can piggy
back on
+ HttpEvent event = events.poll();
+ boolean delivered = false;
+ //TODO TODO - check on thread safety, for writing and for getting last
request.
+ if (event!=null) {
+ synchronized (event) {
+ RequestBase rq =
(RequestBase)event.getHttpServletRequest().getAttribute(RequestBase.LAST_REQ_ATTR);
+ if (rq!=null) {
+ Map map = new HashMap();
+ try {
+
map.put(Bayeux.CHANNEL_FIELD,message.getChannel().getId());
+ map.put(Bayeux.DATA_FIELD,message);
+ JSONObject json = new JSONObject(map);
+ /*if (log.isDebugEnabled()) {
+ log.debug("Message instantly delivered to remote
client["+this+"] message:"+json);
+ }*/
+ rq.addToDeliveryQueue(this, json);
+ //deliver the batch
+ if (i==(msgs.length-1)) {
+ rq.deliver(event, this);
+ event.close(); //todo, figure out a better way, this
means only one message gets delivered
+ removeCometEvent(event); //and delivered instantly
+ }
+ delivered = true;
+ } catch (Exception x) {
+ // TODO: fix
+ x.printStackTrace();
+ //log.error(x);
+ }
+ }
+ }
+ }
+ if (!delivered) {
+ /*if (log.isDebugEnabled()) {
+ log.debug("Message added to queue for remote
client["+this+"] message:"+message);
+ }*/
+ //queue the message for the next round
+ messages.add(message);
+ }
+ }
+ }
+ }
+
+ public String getId() {
+ return this.id;
+ }
+
+ protected Listener getListener() {
+ return listener;
+ }
+
+ public boolean hasMessages() {
+ if (isLocal()) return false;
+ else {
+ return messages.size() > 0;
+ }
+ }
+
+ public boolean isLocal() {
+ return local;
+ }
+
+ public int getSupportedConnTypes() {
+ return supportedConnTypes;
+ }
+
+ public int getDesirectConnType() {
+ return desirectConnType;
+ }
+
+ public boolean useJsonFiltered() {
+ return useJsonFiltered;
+ }
+
+ public void setListener(Listener listener) {
+ this.listener = listener;
+ }
+
+ public void setSupportedConnTypes(int supportedConnTypes) {
+ this.supportedConnTypes = supportedConnTypes;
+ }
+
+ public void setUseJsonFiltered(boolean useJsonFiltered) {
+ this.useJsonFiltered = useJsonFiltered;
+ }
+
+ public void setDesirectConnType(int desirectConnType) {
+ this.desirectConnType = desirectConnType;
+ }
+
+ public boolean supportsCallbackPoll() {
+ return (supportedConnTypes & SUPPORT_CALLBACK_POLL) ==
SUPPORT_CALLBACK_POLL;
+ }
+
+ public boolean supportsLongPoll() {
+ return (supportedConnTypes & SUPPORT_LONG_POLL) == SUPPORT_LONG_POLL;
+ }
+
+ public synchronized List<Message> takeMessages() {
+ if (isLocal()) return null;
+ if (messages.size()==0) return EMPTY_LIST;
+ List result = new LinkedList(messages);
+ messages.clear();
+ return result;
+ }
+
+ public String toString() {
+ StringBuffer buf = new StringBuffer(super.toString());
+ buf.append(" id=").append(getId());
+ return buf.toString();
+ }
+
+ public boolean isSubscribed() {
+ return nrofsubscriptions.get()>0;
+ }
+
+ protected synchronized boolean addCometEvent(HttpEvent event) {
+ boolean result = false;
+ if (!events.contains(event)) {
+ events.add(event);
+ result = true;
+ }
+ event.getHttpServletRequest().setAttribute(COMET_EVENT_ATTR,this);
+ return result;
+ }
+
+ protected synchronized boolean removeCometEvent(HttpEvent event) {
+ boolean result = events.remove(event);
+ event.getHttpServletRequest().removeAttribute(COMET_EVENT_ATTR);
+ return result;
+ }
+
+
+ protected void subscribed(ChannelImpl ch) {
+ nrofsubscriptions.addAndGet(1);
+ }
+
+ protected void unsubscribed(ChannelImpl ch) {
+ nrofsubscriptions.addAndGet(-1);
+ }
+
+ public void startBatch(){
+ //noop until improved
+ }
+ public void endBatch() {
+ //noop until improved
+ }
+
+}
Added: trunk/java/org/apache/tomcat/bayeux/HttpError.java
===================================================================
--- trunk/java/org/apache/tomcat/bayeux/HttpError.java (rev 0)
+++ trunk/java/org/apache/tomcat/bayeux/HttpError.java 2008-09-19 01:53:57 UTC (rev 784)
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.bayeux;
+
+public class HttpError {
+ private int code;
+ private String status;
+ private Throwable cause;
+ public HttpError(int code, String status, Throwable cause) {
+ this.code = code;
+ this.status = status;
+ this.cause = cause;
+ }
+
+ public void setCode(int code) {
+ this.code = code;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public void setCause(Throwable exception) {
+ this.cause = exception;
+ }
+
+ public int getCode() {
+ return code;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public Throwable getCause() {
+ return cause;
+ }
+
+ public String toString() {
+ if (cause != null)
+ return code + ":" + status + " - [" + cause +
"]";
+ else
+ return code + ":" + status;
+ }
+}
Added: trunk/java/org/apache/tomcat/bayeux/MessageImpl.java
===================================================================
--- trunk/java/org/apache/tomcat/bayeux/MessageImpl.java (rev 0)
+++ trunk/java/org/apache/tomcat/bayeux/MessageImpl.java 2008-09-19 01:53:57 UTC (rev
784)
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.bayeux;
+
+import java.util.HashMap;
+
+import org.apache.cometd.bayeux.Channel;
+import org.apache.cometd.bayeux.Client;
+import org.apache.cometd.bayeux.Message;
+
+public class MessageImpl extends HashMap<String,Object> implements Message {
+
+ protected Channel channel;
+ protected Client client;
+ protected String id;
+ private long TTL = 1000*60*5; //5min is the default TTL for a message
+ protected long creationTime = System.currentTimeMillis();
+
+ public Object clone() {
+ MessageImpl copy = new MessageImpl(id);
+ copy.putAll(this);
+ copy.channel = channel;
+ copy.client = client;
+ copy.id = id;
+ copy.creationTime = creationTime;
+ copy.TTL = TTL;
+ return copy;
+ }
+
+ protected MessageImpl(String id) {
+ assert id != null;
+ this.id = id;
+ }
+
+ public Channel getChannel() {
+ return channel;
+ }
+
+ public Client getClient() {
+ return client;
+ }
+
+ public long getCreationTime() {
+ return creationTime;
+ }
+
+ public long getTTL() {
+ return TTL;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ protected void setChannel(Channel channel) {
+ this.channel = channel;
+ }
+
+ protected void setClient(Client client) {
+ this.client = client;
+ }
+
+ public void setTTL(long TTL) {
+ this.TTL = TTL;
+ }
+}
\ No newline at end of file
Added: trunk/java/org/apache/tomcat/bayeux/RequestBase.java
===================================================================
--- trunk/java/org/apache/tomcat/bayeux/RequestBase.java (rev 0)
+++ trunk/java/org/apache/tomcat/bayeux/RequestBase.java 2008-09-19 01:53:57 UTC (rev
784)
@@ -0,0 +1,254 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.bayeux;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TimeZone;
+
+import javax.servlet.ServletException;
+
+import org.apache.cometd.bayeux.Bayeux;
+import org.apache.cometd.bayeux.Message;
+import org.apache.tomcat.util.json.JSONArray;
+import org.apache.tomcat.util.json.JSONException;
+import org.apache.tomcat.util.json.JSONObject;
+import org.jboss.servlet.http.HttpEvent;
+
+/**
+ * Common functionality and member variables for all Bayeux requests.
+ *
+ * @author Guy A. Molinari
+ * @author Filip Hanik
+ * @version 0.9
+ *
+ */
+public abstract class RequestBase implements BayeuxRequest {
+
+ protected static final SimpleDateFormat timestampFmt =
+ new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
+ static {
+ timestampFmt.setTimeZone(TimeZone.getTimeZone("GMT"));
+ }
+ //message properties, combined for all messages
+ protected TomcatBayeux tomcatBayeux;
+ protected String channel;
+ protected String id;
+ protected String clientId;
+ protected String version = null;
+ protected String[] suppConnTypes = null;
+ protected int suppConnTypesFlag = 0;
+ protected int desiredConnTypeFlag = 0;
+ protected String minVersion = null;
+ protected String subscription = null;
+ protected String data = null;
+ protected String conType = null;
+ protected LinkedHashMap<String, Object> ext = new LinkedHashMap<String,
Object> ();
+
+
+ protected HttpEvent event;
+
+ protected HashMap<String, Object> response = null;
+
+ protected int reconnectInterval;
+
+ protected RequestBase(TomcatBayeux tb, HttpEvent event, JSONObject jsReq) throws
JSONException {
+ this.tomcatBayeux = tb;
+ this.event = event;
+ channel = jsReq.optString(Bayeux.CHANNEL_FIELD);
+ id = jsReq.optString(Bayeux.ID_FIELD);
+ clientId = jsReq.optString(Bayeux.CLIENT_FIELD);
+ version = jsReq.optString(Bayeux.VERSION_FIELD);
+ minVersion = jsReq.optString(Bayeux.MIN_VERSION_FIELD);
+ conType = jsReq.optString(Bayeux.CONNECTION_TYPE_FIELD);
+ subscription = jsReq.optString(Bayeux.SUBSCRIPTION_FIELD);
+ data = jsReq.optString(Bayeux.DATA_FIELD);
+ reconnectInterval = tb.getReconnectInterval();
+ if (jsReq.has(Bayeux.EXT_FIELD)) {
+ JSONObject jext = jsReq.getJSONObject(Bayeux.EXT_FIELD);
+ for (Iterator<String> i = jext.keys(); i.hasNext(); ) {
+ String key = i.next();
+ ext.put(key, jext.get(key));
+ }//for
+ }//end if
+
+ if (jsReq.has(Bayeux.SUPP_CONNECTION_TYPE_FIELD)) {
+ JSONArray types = jsReq.getJSONArray(Bayeux.SUPP_CONNECTION_TYPE_FIELD);
+ suppConnTypes = new String[types.length()];
+ for (int i = 0; i < types.length(); i++) {
+ suppConnTypes[i] = types.getString(i);
+ if (Bayeux.TRANSPORT_CALLBACK_POLL.equals(suppConnTypes[i]))
+ suppConnTypesFlag =
suppConnTypesFlag|ClientImpl.SUPPORT_CALLBACK_POLL;
+ else if (Bayeux.TRANSPORT_LONG_POLL.equals(suppConnTypes[i]))
+ suppConnTypesFlag = suppConnTypesFlag|ClientImpl.SUPPORT_LONG_POLL;
+ }//for
+ }//end if
+
+ if (conType!=null) {
+ if (Bayeux.TRANSPORT_CALLBACK_POLL.equals(conType))
+ desiredConnTypeFlag = ClientImpl.SUPPORT_CALLBACK_POLL;
+ else if (Bayeux.TRANSPORT_LONG_POLL.equals(conType))
+ desiredConnTypeFlag = ClientImpl.SUPPORT_LONG_POLL;
+ }//end if
+
+ //due to the fact that the javascript doesn't send up a required field
+ //we have to fake it
+ suppConnTypesFlag = ClientImpl.SUPPORT_CALLBACK_POLL |
ClientImpl.SUPPORT_LONG_POLL;
+
+ }
+
+ public HttpError validate() {
+ HttpError result = null;
+// if (clientId == null) {
+// result = new HttpError(401,"No Client ID.", null);
+// }
+ return result;
+ }
+
+ public TomcatBayeux getTomcatBayeux() {
+ return tomcatBayeux;
+ }
+
+ public String getChannel() {
+ return channel;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public String getClientId() {
+ return clientId;
+ }
+
+ public LinkedHashMap getExt() {
+ return ext;
+ }
+
+ public HttpEvent getEvent() {
+ return event;
+ }
+
+ protected static void deliver(HttpEvent event, ClientImpl to) throws IOException,
ServletException, BayeuxException {
+ JSONArray jarray = getJSONArray(event,true);
+ if ( jarray == null ) throw new BayeuxException("No message to
send!");
+ String jsonstring = jarray.toString();
+ /*if (log.isDebugEnabled()) {
+ log.debug("["+Thread.currentThread().getName()+"] Delivering
message to[" + to + "] message:" + jsonstring);
+ }*/
+
+ if (to!=null) {
+ if (to.useJsonFiltered()) {
+ if (!event.getHttpServletResponse().isCommitted())
event.getHttpServletResponse().setContentType("text/json-comment-filtered");
+ }else {
+ if (!event.getHttpServletResponse().isCommitted())
event.getHttpServletResponse().setContentType("text/json");
+ }
+ }
+
+ PrintWriter out = event.getHttpServletResponse().getWriter();
+ if (to==null) {
+ //do nothing
+ }else if ( (to.getDesirectConnType() == 0 && to.supportsLongPoll()) ||
to.getDesirectConnType() == ClientImpl.SUPPORT_LONG_POLL) {
+ if (to.useJsonFiltered())
+ out.print("/*");
+ } else if ( (to.getDesirectConnType() == 0 && to.supportsCallbackPoll())
|| to.getDesirectConnType() == ClientImpl.SUPPORT_CALLBACK_POLL) {
+ String jsonp =
event.getHttpServletRequest().getParameter(Bayeux.JSONP_PARAMETER);
+ if (jsonp == null)
+ jsonp = Bayeux.JSONP_DEFAULT_NAME;
+ out.print(jsonp);
+ out.print('(');
+ } else {
+ throw new BayeuxException("Client doesn't support any appropriate
connection type.");
+ }
+ out.print(jsonstring);
+ if ( to == null ) {
+ //do nothing
+ } else if ( (to.getDesirectConnType() == 0 && to.supportsLongPoll()) ||
to.getDesirectConnType() == ClientImpl.SUPPORT_LONG_POLL) {
+ if (to.useJsonFiltered())
+ out.print("*/");
+ } else if ( (to.getDesirectConnType() == 0 && to.supportsCallbackPoll())
|| to.getDesirectConnType() == ClientImpl.SUPPORT_CALLBACK_POLL) {
+ out.print(");");
+ }
+ out.flush();
+ event.getHttpServletResponse().flushBuffer();
+
+
+ }
+
+ protected static JSONArray getJSONArray(HttpEvent event, boolean nullok) {
+ synchronized(event) {
+ JSONArray jarray = (JSONArray)
event.getHttpServletRequest().getAttribute(JSON_MSG_ARRAY);
+ if (jarray == null && (!nullok)) {
+ jarray = new JSONArray();
+ event.getHttpServletRequest().setAttribute(JSON_MSG_ARRAY, jarray);
+ }
+ return jarray;
+ }
+ }
+
+ protected JSONArray getJSONArray() {
+ return getJSONArray(event,false);
+ }
+
+ protected void addToDeliveryQueue(ClientImpl to, JSONObject msg) throws IOException,
ServletException, BayeuxException {
+ synchronized (event) {
+ getJSONArray().put(msg);
+ }
+ }
+
+ protected void flushMessages(ClientImpl client) throws BayeuxException {
+ List<Message> msgs = client.takeMessages();
+ synchronized (event) {
+ try {
+ for (Iterator<Message> it = msgs.iterator(); it.hasNext(); ){
+ MessageImpl msg = (MessageImpl)it.next();
+ Map map = new HashMap();
+ map.put(Bayeux.CHANNEL_FIELD,msg.getChannel().getId());
+ if (msg.getClient()!=null)
map.put(Bayeux.CLIENT_FIELD,msg.getClient().getId());
+ map.put(Bayeux.DATA_FIELD,msg);
+ JSONObject obj = new JSONObject(map);
+ addToDeliveryQueue(client, obj);
+ }
+ } catch (ServletException x) {
+ throw new BayeuxException(x);
+ } catch (IOException x) {
+ throw new BayeuxException(x);
+ }
+ }
+ }
+
+ public int process(int prevops) throws BayeuxException {
+ event.getHttpServletRequest().setAttribute(CURRENT_REQ_ATTR,this);
+ return prevops;
+ }
+
+ public int getReconnectInterval() {
+ return reconnectInterval;
+ }
+
+ public String getTimeStamp() {
+ return timestampFmt.format(new Date(System.currentTimeMillis()));
+ }
+
+}
Added: trunk/java/org/apache/tomcat/bayeux/RequestFactory.java
===================================================================
--- trunk/java/org/apache/tomcat/bayeux/RequestFactory.java (rev
0)
+++ trunk/java/org/apache/tomcat/bayeux/RequestFactory.java 2008-09-19 01:53:57 UTC (rev
784)
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.bayeux;
+
+import org.apache.cometd.bayeux.Bayeux;
+import org.apache.tomcat.bayeux.request.MetaConnectRequest;
+import org.apache.tomcat.bayeux.request.MetaDisconnectRequest;
+import org.apache.tomcat.bayeux.request.MetaHandshakeRequest;
+import org.apache.tomcat.bayeux.request.MetaSubscribeRequest;
+import org.apache.tomcat.bayeux.request.MetaUnsubscribeRequest;
+import org.apache.tomcat.bayeux.request.PublishRequest;
+import org.apache.tomcat.util.json.JSONException;
+import org.apache.tomcat.util.json.JSONObject;
+import org.jboss.servlet.http.HttpEvent;
+
+public class RequestFactory {
+
+ public static BayeuxRequest getRequest(TomcatBayeux tomcatBayeux, HttpEvent event,
JSONObject msg) throws JSONException {
+ String channel = msg.optString(Bayeux.CHANNEL_FIELD);
+ if (Bayeux.META_HANDSHAKE.equals(channel)) {
+ return new MetaHandshakeRequest(tomcatBayeux,event,msg);
+ }else if (Bayeux.META_CONNECT.equals(channel)) {
+ return new MetaConnectRequest(tomcatBayeux,event,msg);
+ }else if (Bayeux.META_DISCONNECT.equals(channel)) {
+ return new MetaDisconnectRequest(tomcatBayeux,event,msg);
+ }else if (Bayeux.META_SUBSCRIBE.equals(channel)) {
+ return new MetaSubscribeRequest(tomcatBayeux,event,msg);
+ }else if (Bayeux.META_UNSUBSCRIBE.equals(channel)) {
+ return new MetaUnsubscribeRequest(tomcatBayeux,event,msg);
+ } else {
+ return new PublishRequest(tomcatBayeux,event,msg);
+ }
+ }
+}
\ No newline at end of file
Added: trunk/java/org/apache/tomcat/bayeux/TomcatBayeux.java
===================================================================
--- trunk/java/org/apache/tomcat/bayeux/TomcatBayeux.java (rev 0)
+++ trunk/java/org/apache/tomcat/bayeux/TomcatBayeux.java 2008-09-19 01:53:57 UTC (rev
784)
@@ -0,0 +1,175 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.bayeux;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+
+import org.apache.cometd.bayeux.Bayeux;
+import org.apache.cometd.bayeux.Channel;
+import org.apache.cometd.bayeux.Client;
+import org.apache.cometd.bayeux.Listener;
+import org.apache.cometd.bayeux.Message;
+import org.apache.cometd.bayeux.SecurityPolicy;
+import org.jboss.servlet.http.HttpEvent;
+/**
+ *
+ * @author Filip Hanik
+ * @version 1.0
+ */
+public class TomcatBayeux implements Bayeux {
+
+
+ protected int reconnectInterval = 5000;
+ /**
+ * a list of all active clients
+ */
+ protected HashMap<String,Client> clients = new HashMap<String,Client>();
+
+ /**
+ * a list of all active channels
+ */
+ protected LinkedHashMap<String, Channel> channels = new
LinkedHashMap<String,Channel>();
+
+ /**
+ * security policy to be used.
+ */
+ protected SecurityPolicy securityPolicy = null;
+ /**
+ * default client to use when we need to send an error message but don't have a
client valid reference
+ */
+ protected static ClientImpl errorClient = new
ClientImpl("error-no-client",false);
+
+ /**
+ * returns the default error client
+ * @return ClientImpl
+ */
+ public static ClientImpl getErrorClient() {
+ return errorClient;
+ }
+
+ protected TomcatBayeux() {
+ }
+
+ /**
+ * should be invoked when the servlet is destroyed or when the context shuts down
+ */
+ public void destroy() {
+ throw new UnsupportedOperationException("TomcatBayeux.destroy() not yet
implemented");
+ }
+
+ public Channel getChannel(String channelId, boolean create) {
+ Channel result = channels.get(channelId);
+ if (result==null && create) {
+ result = new ChannelImpl(channelId);
+ channels.put(channelId,result);
+ }
+ return result;
+ }
+
+ public Channel remove(Channel channel) {
+ return channels.remove(channel.getId());
+ }
+
+ public Client remove(Client client) {
+ if (client==null) return null;
+ for (Channel ch : getChannels()) {
+ ch.unsubscribe(client);
+ }
+ return clients.remove(client.getId());
+ }
+
+ public Client getClient(String clientId) {
+ return clients.get(clientId);
+ }
+
+ public boolean hasClient(String clientId) {
+ return clients.containsKey(clientId);
+ }
+
+ public List<Client> getClients() {
+ return java.util.Arrays.asList(clients.entrySet().toArray(new Client[0]));
+ }
+
+ public SecurityPolicy getSecurityPolicy() {
+ return securityPolicy;
+ }
+
+ public int getReconnectInterval() {
+ return reconnectInterval;
+ }
+
+ public boolean hasChannel(String channel) {
+ return channels.containsKey(channel);
+ }
+
+ public Client newClient(String idprefix, Listener listener, boolean local, HttpEvent
event) {
+ String id = createUUID(idprefix);
+ ClientImpl client = new ClientImpl(id, local);
+ client.setListener(listener);
+ clients.put(id, client);
+ return client;
+ }
+
+ public Client newClient(String idprefix, Listener listener) {
+ assert listener!=null;
+ //if this method gets called, someone is using the API inside
+ //the JVM, this is a local client
+ return newClient(idprefix,listener,true, null);
+ }
+
+ protected ClientImpl getClientImpl(HttpEvent event) {
+ return
(ClientImpl)event.getHttpServletRequest().getAttribute(ClientImpl.COMET_EVENT_ATTR);
+ }
+
+ protected void remove(HttpEvent event) {
+ ClientImpl client = getClientImpl(event);
+ if (client!=null) {
+ client.removeCometEvent(event);
+ }
+ }
+
+ public String createUUID(String idprefix) {
+ if (idprefix==null) idprefix="";
+ return idprefix + Arrays.toString(UUIDGenerator.randomUUID(false));
+ }
+
+ public List<Channel> getChannels() {
+ return java.util.Arrays.asList(channels.entrySet().toArray(new Channel[0]));
+ }
+
+ protected Message newMessage() {
+ String id = createUUID("msg-");
+ return new MessageImpl(id);
+ }
+
+ public Message newMessage(Client from) {
+ MessageImpl msg = (MessageImpl)newMessage();
+ msg.setClient(from);
+ return msg;
+ }
+ public void setSecurityPolicy(SecurityPolicy securityPolicy) {
+ this.securityPolicy = securityPolicy;
+ }
+
+ public void setReconnectInterval(int reconnectTimeout) {
+ this.reconnectInterval = reconnectTimeout;
+ }
+
+}
Added: trunk/java/org/apache/tomcat/bayeux/UUIDGenerator.java
===================================================================
--- trunk/java/org/apache/tomcat/bayeux/UUIDGenerator.java (rev
0)
+++ trunk/java/org/apache/tomcat/bayeux/UUIDGenerator.java 2008-09-19 01:53:57 UTC (rev
784)
@@ -0,0 +1,76 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.bayeux;
+
+import java.security.SecureRandom;
+import java.util.Random;
+
+/**
+ * simple generation of a UUID
+ * @author Filip Hanik
+ * @version 1.0
+ */
+public class UUIDGenerator {
+ public static final int UUID_LENGTH = 16;
+ public static final int UUID_VERSION = 4;
+ public static final int BYTES_PER_INT = 4;
+ public static final int BITS_PER_BYTE = 8;
+
+ protected static SecureRandom secrand = null;
+ protected static Random rand = new Random(System.currentTimeMillis());
+ static {
+ secrand = new SecureRandom();
+ secrand.setSeed(rand.nextLong());
+ }
+
+ public static byte[] randomUUID(boolean secure) {
+ byte[] result = new byte[UUID_LENGTH];
+ return randomUUID(secure,result,0);
+ }
+
+ public static byte[] randomUUID(boolean secure, byte[] into, int offset) {
+ if ( (offset+UUID_LENGTH)>into.length )
+ throw new ArrayIndexOutOfBoundsException("Unable to fit
"+UUID_LENGTH+" bytes into the array. length:"+into.length+" required
length:"+(offset+UUID_LENGTH));
+ Random r = (secure&&(secrand!=null))?secrand:rand;
+ nextBytes(into,offset,UUID_LENGTH,r);
+ into[6+offset] &= 0x0F;
+ into[6+offset] |= (UUID_VERSION << 4);
+ into[8+offset] &= 0x3F; //0011 1111
+ into[8+offset] |= 0x80; //1000 0000
+ return into;
+ }
+
+ /**
+ * Same as java.util.Random.nextBytes except this one we dont have to allocate a new
byte array
+ * @param into byte[]
+ * @param offset int
+ * @param length int
+ * @param r Random
+ */
+ public static void nextBytes(byte[] into, int offset, int length, Random r) {
+ int numRequested = length;
+ int numGot = 0, rnd = 0;
+ while (true) {
+ for (int i = 0; i < BYTES_PER_INT; i++) {
+ if (numGot == numRequested) return;
+ rnd = (i == 0 ? r.nextInt() : rnd >> BITS_PER_BYTE);
+ into[offset+numGot] = (byte) rnd;
+ numGot++;
+ }
+ }
+ }
+
+}
Added: trunk/java/org/apache/tomcat/bayeux/request/MetaConnectRequest.java
===================================================================
--- trunk/java/org/apache/tomcat/bayeux/request/MetaConnectRequest.java
(rev 0)
+++ trunk/java/org/apache/tomcat/bayeux/request/MetaConnectRequest.java 2008-09-19
01:53:57 UTC (rev 784)
@@ -0,0 +1,126 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.bayeux.request;
+
+import java.io.IOException;
+import java.util.HashMap;
+
+import javax.servlet.ServletException;
+
+import org.apache.cometd.bayeux.Bayeux;
+import org.apache.tomcat.bayeux.BayeuxException;
+import org.apache.tomcat.bayeux.BayeuxRequest;
+import org.apache.tomcat.bayeux.ClientImpl;
+import org.apache.tomcat.bayeux.HttpError;
+import org.apache.tomcat.bayeux.RequestBase;
+import org.apache.tomcat.bayeux.TomcatBayeux;
+import org.apache.tomcat.util.json.JSONException;
+import org.apache.tomcat.util.json.JSONObject;
+import org.jboss.servlet.http.HttpEvent;
+
+/******************************************************************************
+ * Handshake request Bayeux message.
+ *
+ * @author Guy A. Molinari
+ * @author Filip Hanik
+ * @version 1.0
+ *
+ */
+public class MetaConnectRequest extends RequestBase implements BayeuxRequest {
+ protected static HashMap<String,Object> responseTemplate = new
HashMap<String,Object>();
+
+ static {
+ responseTemplate.put(Bayeux.CHANNEL_FIELD,Bayeux.META_CONNECT);
+ responseTemplate.put(Bayeux.SUCCESSFUL_FIELD,Boolean.TRUE);
+ responseTemplate.put(Bayeux.ADVICE_FIELD, new HashMap<String, Object>());
+ }
+
+ public MetaConnectRequest(TomcatBayeux tb, HttpEvent event, JSONObject jsReq) throws
JSONException {
+ super(tb, event, jsReq);
+ if (clientId!=null && getTomcatBayeux().hasClient(clientId)) {
+
event.getHttpServletRequest().setAttribute("client",getTomcatBayeux().getClient(clientId));
+ }
+ }
+
+
+ /**
+ * Check client request for validity.
+ *
+ * Per section 4.2.1 of the Bayuex spec a connect request must contain:
+ * 1) The "/meta/connect" channel identifier.
+ * 2) The clientId returned by the server after handshake.
+ * 3) The desired connectionType (must be one of the server's supported
+ * types returned by handshake response.
+ *
+ * @return HttpError This method returns null if no errors were found
+ */
+ public HttpError validate() {
+ if(clientId==null|| (!getTomcatBayeux().hasClient(clientId)))
+ return new HttpError(400,"Client Id not valid.", null);
+ if (! (Bayeux.TRANSPORT_LONG_POLL.equals(conType) ||
Bayeux.TRANSPORT_CALLBACK_POLL.equals(conType)))
+ return new HttpError(400,"Unsupported connection type.",null);
+ return null;//no error
+ }
+
+ /**
+ * Transition to connected state, flushing pending messages if
+ * available. If there are pending subscriptions and no messages to
+ * flush then the connection is held until there is a pending publish
+ * event to be delivered to this client (Section 4.2.2 of spec).
+ */
+ public int process(int prevops) throws BayeuxException {
+ prevops = super.process(prevops);
+ response = (HashMap<String, Object>)responseTemplate.clone();
+ ClientImpl client = (ClientImpl)getTomcatBayeux().getClient(clientId);
+ boolean success = false;
+ HttpError error = validate();
+ if (error == null) {
+ client.setDesirectConnType(desiredConnTypeFlag);
+ ((HashMap) response.get(Bayeux.ADVICE_FIELD)).put(Bayeux.RECONNECT_FIELD,
Bayeux.RETRY_RESPONSE);
+ ((HashMap) response.get(Bayeux.ADVICE_FIELD)).put(Bayeux.INTERVAL_FIELD,
getReconnectInterval());
+ success = true;
+ }else {
+ response.put(Bayeux.SUCCESSFUL_FIELD,Boolean.FALSE);
+ response.put(Bayeux.ERROR_FIELD, error.toString());
+ ((HashMap) response.get(Bayeux.ADVICE_FIELD)).put(Bayeux.RECONNECT_FIELD,
Bayeux.HANDSHAKE_RESPONSE);
+ if (client==null) client = TomcatBayeux.getErrorClient();
+ }
+ response.put(Bayeux.CLIENT_FIELD, client.getId());
+ response.put(Bayeux.TIMESTAMP_FIELD,getTimeStamp());
+ try {
+ JSONObject obj = new JSONObject(response);
+ addToDeliveryQueue(client, obj);
+ } catch (ServletException x) {
+ throw new BayeuxException(x);
+ } catch (IOException x) {
+ throw new BayeuxException(x);
+ }
+
+ //return immediately if there is no subscriptions
+ //so that we can process the next message
+ int result = client.isSubscribed()?1:0;
+
+ if (success && client!=null && client.hasMessages()) {
+ //send out messages
+ flushMessages(client);
+ result = 0; //flush out the messages
+ }
+
+ return result;
+ }
+}
+
Added: trunk/java/org/apache/tomcat/bayeux/request/MetaDisconnectRequest.java
===================================================================
--- trunk/java/org/apache/tomcat/bayeux/request/MetaDisconnectRequest.java
(rev 0)
+++ trunk/java/org/apache/tomcat/bayeux/request/MetaDisconnectRequest.java 2008-09-19
01:53:57 UTC (rev 784)
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.bayeux.request;
+
+import java.io.IOException;
+import java.util.HashMap;
+
+import javax.servlet.ServletException;
+
+import org.apache.cometd.bayeux.Bayeux;
+import org.apache.tomcat.bayeux.BayeuxException;
+import org.apache.tomcat.bayeux.BayeuxRequest;
+import org.apache.tomcat.bayeux.ClientImpl;
+import org.apache.tomcat.bayeux.HttpError;
+import org.apache.tomcat.bayeux.RequestBase;
+import org.apache.tomcat.bayeux.TomcatBayeux;
+import org.apache.tomcat.util.json.JSONException;
+import org.apache.tomcat.util.json.JSONObject;
+import org.jboss.servlet.http.HttpEvent;
+
+/******************************************************************************
+ * Handshake request Bayeux message.
+ *
+ * @author Guy A. Molinari
+ * @author Filip Hanik
+ * @version 1.0
+ *
+ */
+public class MetaDisconnectRequest extends RequestBase implements BayeuxRequest {
+
+ protected static HashMap<String,Object> responseTemplate = new
HashMap<String,Object>();
+
+ static {
+ responseTemplate.put(Bayeux.CHANNEL_FIELD,Bayeux.META_DISCONNECT);
+ responseTemplate.put(Bayeux.SUCCESSFUL_FIELD,Boolean.TRUE);
+ responseTemplate.put(Bayeux.ADVICE_FIELD, new HashMap<String, Object>());
+ }
+
+ public MetaDisconnectRequest(TomcatBayeux tb, HttpEvent event, JSONObject jsReq)
throws JSONException {
+ super(tb, event, jsReq);
+ }
+
+
+ /**
+ * Check client request for validity.
+ *
+ * Per section 4.4.1 of the Bayuex spec a connect request must contain:
+ * 1) The "/meta/disconnect" channel identifier.
+ * 2) The clientId.
+ *
+ * @return HttpError This method returns null if no errors were found
+ */
+ public HttpError validate() {
+ if(clientId==null|| (!this.getTomcatBayeux().hasClient(clientId)))
+ return new HttpError(400,"Client Id not valid.", null);
+// if (! (Bayeux.TRANSPORT_LONG_POLL.equals(conType) ||
Bayeux.TRANSPORT_CALLBACK_POLL.equals(conType)))
+// return new HttpError(400,"Unsupported connection type.",null);
+ return null;//no error
+ }
+
+ /**
+ * Disconnect a client session.
+ */
+ public int process(int prevops) throws BayeuxException {
+ prevops = super.process(prevops);
+ response = (HashMap<String, Object>)responseTemplate.clone();
+ ClientImpl client = (ClientImpl)getTomcatBayeux().getClient(clientId);
+ HttpError error = validate();
+ if (error == null) {
+ ((HashMap) response.get(Bayeux.ADVICE_FIELD)).put("reconnect",
"retry");
+ ((HashMap) response.get(Bayeux.ADVICE_FIELD)).put("interval",
getReconnectInterval());
+ }else {
+ getTomcatBayeux().remove(client);
+ response.put(Bayeux.SUCCESSFUL_FIELD,Boolean.FALSE);
+ response.put(Bayeux.ERROR_FIELD, error.toString());
+ ((HashMap) response.get(Bayeux.ADVICE_FIELD)).put("reconnect",
"none");
+ if (client==null) client = TomcatBayeux.getErrorClient();
+ }
+ response.put(Bayeux.CLIENT_FIELD, client.getId());
+ try {
+ JSONObject obj = new JSONObject(response);
+ addToDeliveryQueue(client, obj);
+ } catch (ServletException x) {
+ throw new BayeuxException(x);
+ } catch (IOException x) {
+ throw new BayeuxException(x);
+ }
+ return 0;
+ }
+}
+
Added: trunk/java/org/apache/tomcat/bayeux/request/MetaHandshakeRequest.java
===================================================================
--- trunk/java/org/apache/tomcat/bayeux/request/MetaHandshakeRequest.java
(rev 0)
+++ trunk/java/org/apache/tomcat/bayeux/request/MetaHandshakeRequest.java 2008-09-19
01:53:57 UTC (rev 784)
@@ -0,0 +1,117 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.bayeux.request;
+
+import java.io.IOException;
+import java.util.HashMap;
+
+import javax.servlet.ServletException;
+
+import org.apache.cometd.bayeux.Bayeux;
+import org.apache.tomcat.bayeux.BayeuxException;
+import org.apache.tomcat.bayeux.BayeuxRequest;
+import org.apache.tomcat.bayeux.ClientImpl;
+import org.apache.tomcat.bayeux.HttpError;
+import org.apache.tomcat.bayeux.RequestBase;
+import org.apache.tomcat.bayeux.TomcatBayeux;
+import org.apache.tomcat.util.json.JSONException;
+import org.apache.tomcat.util.json.JSONObject;
+import org.jboss.servlet.http.HttpEvent;
+
+/******************************************************************************
+ * Handshake request Bayeux message.
+ *
+ * @author Guy A. Molinari
+ * @author Filip Hanik
+ * @version 1.0
+ *
+ */
+public class MetaHandshakeRequest extends RequestBase implements BayeuxRequest {
+
+ protected static HashMap<String,Object> responseTemplate = new
HashMap<String,Object>();
+
+ static {
+ responseTemplate.put(Bayeux.CHANNEL_FIELD,Bayeux.META_HANDSHAKE);
+ responseTemplate.put(Bayeux.VERSION_FIELD,"1.0");
+ responseTemplate.put(Bayeux.SUPP_CONNECTION_TYPE_FIELD,new String[] {
Bayeux.TRANSPORT_LONG_POLL, Bayeux.TRANSPORT_CALLBACK_POLL });
+ responseTemplate.put(Bayeux.SUCCESSFUL_FIELD,Boolean.TRUE);
+ responseTemplate.put(Bayeux.ADVICE_FIELD, new HashMap<String, Object>());
+ }
+
+ public MetaHandshakeRequest(TomcatBayeux tomcatBayeux, HttpEvent event, JSONObject
jsReq) throws JSONException {
+ super(tomcatBayeux, event, jsReq);
+ }
+
+
+ public String getVersion() { return version; }
+ public String getMinimumVersion() { return minVersion; }
+
+
+ /**
+ * Check client request for validity.
+ *
+ * Per section 4.1.1 of the Bayuex spec a handshake request must contain:
+ * 1) The "/meta/handshake" channel identifier.
+ * 2) The version of the protocol supported by the client
+ * 3) The client's supported connection types.
+ *
+ * @return HttpError This method returns null if no errors were found
+ */
+ public HttpError validate() {
+ boolean error = (version==null || version.length()==0);
+ if (!error) error = suppConnTypesFlag==0;
+ if (error) return new HttpError(400,"Invalid handshake request,
supportedConnectionType field missing.",null);
+ else return null;
+ }
+
+ /**
+ * Generate and return a client identifier. Return a list of
+ * supported connection types. Must be a subset of or identical to
+ * the list of types supported by the client. See section 4.1.2 of
+ * the Bayuex specification.
+ */
+ public int process(int prevops) throws BayeuxException {
+ prevops = super.process(prevops);
+ response = (HashMap<String, Object>)responseTemplate.clone();
+ ClientImpl client = null;
+ HttpError error = validate();
+ if (error == null) {
+ client = (ClientImpl) getTomcatBayeux().newClient("http-", null,
false,getEvent());
+ clientId = client.getId();
+ client.setSupportedConnTypes(suppConnTypesFlag);
+ client.setUseJsonFiltered(getExt().get(Bayeux.JSON_COMMENT_FILTERED_FIELD) !=
null);
+ response.put(Bayeux.CLIENT_FIELD, client.getId());
+ ((HashMap) response.get(Bayeux.ADVICE_FIELD)).put(Bayeux.RECONNECT_FIELD,
Bayeux.RETRY_RESPONSE);
+ ((HashMap) response.get(Bayeux.ADVICE_FIELD)).put(Bayeux.INTERVAL_FIELD,
getReconnectInterval());
+ }else {
+ response.put(Bayeux.SUCCESSFUL_FIELD,Boolean.FALSE);
+ response.put(Bayeux.ERROR_FIELD, error.toString());
+ client = TomcatBayeux.getErrorClient();
+ ((HashMap) response.get(Bayeux.ADVICE_FIELD)).put(Bayeux.RECONNECT_FIELD,
Bayeux.NONE_RESPONSE);
+ }
+ try {
+ JSONObject obj = new JSONObject(response);
+ addToDeliveryQueue(client, obj);
+ } catch (ServletException x) {
+ throw new BayeuxException(x);
+ } catch (IOException x) {
+ throw new BayeuxException(x);
+ }
+ return 0;
+ }
+}
+
Added: trunk/java/org/apache/tomcat/bayeux/request/MetaSubscribeRequest.java
===================================================================
--- trunk/java/org/apache/tomcat/bayeux/request/MetaSubscribeRequest.java
(rev 0)
+++ trunk/java/org/apache/tomcat/bayeux/request/MetaSubscribeRequest.java 2008-09-19
01:53:57 UTC (rev 784)
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.bayeux.request;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.servlet.ServletException;
+
+import org.apache.cometd.bayeux.Bayeux;
+import org.apache.cometd.bayeux.Channel;
+import org.apache.tomcat.bayeux.BayeuxException;
+import org.apache.tomcat.bayeux.BayeuxRequest;
+import org.apache.tomcat.bayeux.ChannelImpl;
+import org.apache.tomcat.bayeux.ClientImpl;
+import org.apache.tomcat.bayeux.HttpError;
+import org.apache.tomcat.bayeux.RequestBase;
+import org.apache.tomcat.bayeux.TomcatBayeux;
+import org.apache.tomcat.util.json.JSONException;
+import org.apache.tomcat.util.json.JSONObject;
+import org.jboss.servlet.http.HttpEvent;
+
+/******************************************************************************
+ * Handshake request Bayeux message.
+ *
+ * @author Guy A. Molinari
+ * @author Filip Hanik
+ * @version 1.0
+ */
+public class MetaSubscribeRequest extends RequestBase implements BayeuxRequest {
+
+ protected static HashMap<String,Object> responseTemplate = new
HashMap<String,Object>();
+
+ static {
+ responseTemplate.put(Bayeux.CHANNEL_FIELD,Bayeux.META_SUBSCRIBE);
+ responseTemplate.put(Bayeux.SUCCESSFUL_FIELD,Boolean.TRUE);
+ responseTemplate.put(Bayeux.ADVICE_FIELD, new HashMap<String, Object>());
+ }
+
+ public MetaSubscribeRequest(TomcatBayeux tb, HttpEvent event, JSONObject jsReq)
throws JSONException {
+ super(tb, event, jsReq);
+ }
+
+
+ /**
+ * Check client request for validity.
+ *
+ * Per section 4.5.1 of the Bayuex spec a connect request must contain:
+ * 1) The "/meta/subscribe" channel identifier.
+ * 2) The clientId.
+ * 3) The subscription. This is the name of the channel of interest,
+ * or a pattern.
+ *
+ * @return HttpError This method returns null if no errors were found
+ */
+ public HttpError validate() {
+ if(clientId==null|| (!this.getTomcatBayeux().hasClient(clientId)))
+ return new HttpError(400,"Client Id not valid.", null);
+ if (subscription==null||subscription.length()==0)
+ return new HttpError(400,"Subscription missing.",null);
+ return null;//no error
+ }
+
+ /**
+ * Register interest for one or more channels. Per section 2.2.1 of the
+ * Bayeux spec, a pattern may be specified. Assign client to matching
+ * channels and inverse client to channel reference.
+ */
+ public int process(int prevops) throws BayeuxException {
+ prevops = super.process(prevops);
+ response = (HashMap<String, Object>)this.responseTemplate.clone();
+ ClientImpl client = (ClientImpl)getTomcatBayeux().getClient(clientId);
+ HttpError error = validate();
+ if (error == null) {
+ boolean wildcard = subscription.indexOf('*')!=-1;
+ boolean subscribed = false;
+ if (wildcard) {
+ List<Channel> channels = getTomcatBayeux().getChannels();
+ Iterator<Channel> it = channels.iterator();
+ while (it.hasNext()) {
+ ChannelImpl ch = (ChannelImpl)it.next();
+ if (ch.matches(subscription)) {
+ ch.subscribe(client);
+ subscribed = true;
+ }
+ }
+ }else {
+ ChannelImpl ch =
(ChannelImpl)getTomcatBayeux().getChannel(subscription,true);
+ ch.subscribe(client);
+ subscribed = true;
+ }
+ response.put(Bayeux.SUCCESSFUL_FIELD, Boolean.valueOf(subscribed));
+ response.put(Bayeux.SUBSCRIPTION_FIELD,subscription);
+ ((HashMap) response.get(Bayeux.ADVICE_FIELD)).put("reconnect",
"retry");
+ ((HashMap) response.get(Bayeux.ADVICE_FIELD)).put("interval",
getReconnectInterval());
+ }else {
+ response.put(Bayeux.SUCCESSFUL_FIELD,Boolean.FALSE);
+ response.put(Bayeux.ERROR_FIELD, error.toString());
+ ((HashMap) response.get(Bayeux.ADVICE_FIELD)).put("reconnect",
"handshake");
+ if (client==null) client = TomcatBayeux.getErrorClient();
+ }
+ response.put(Bayeux.CLIENT_FIELD, client.getId());
+ response.put(Bayeux.TIMESTAMP_FIELD,getTimeStamp());
+ try {
+ JSONObject obj = new JSONObject(response);
+ addToDeliveryQueue(client, obj);
+ } catch (ServletException x) {
+ throw new BayeuxException(x);
+ } catch (IOException x) {
+ throw new BayeuxException(x);
+ }
+ return 0;
+ }
+}
+
Added: trunk/java/org/apache/tomcat/bayeux/request/MetaUnsubscribeRequest.java
===================================================================
--- trunk/java/org/apache/tomcat/bayeux/request/MetaUnsubscribeRequest.java
(rev 0)
+++ trunk/java/org/apache/tomcat/bayeux/request/MetaUnsubscribeRequest.java 2008-09-19
01:53:57 UTC (rev 784)
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.bayeux.request;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.servlet.ServletException;
+
+import org.apache.cometd.bayeux.Bayeux;
+import org.apache.cometd.bayeux.Channel;
+import org.apache.tomcat.bayeux.BayeuxException;
+import org.apache.tomcat.bayeux.BayeuxRequest;
+import org.apache.tomcat.bayeux.ChannelImpl;
+import org.apache.tomcat.bayeux.ClientImpl;
+import org.apache.tomcat.bayeux.HttpError;
+import org.apache.tomcat.bayeux.RequestBase;
+import org.apache.tomcat.bayeux.TomcatBayeux;
+import org.apache.tomcat.util.json.JSONException;
+import org.apache.tomcat.util.json.JSONObject;
+import org.jboss.servlet.http.HttpEvent;
+
+/******************************************************************************
+ * Handshake request Bayeux message.
+ *
+ * @author Guy A. Molinari
+ * @author Filip Hanik
+ * @version 1.0
+ *
+ */
+public class MetaUnsubscribeRequest extends RequestBase implements BayeuxRequest {
+
+ protected static HashMap<String,Object> responseTemplate = new
HashMap<String,Object>();
+
+ static {
+ responseTemplate.put(Bayeux.CHANNEL_FIELD,Bayeux.META_UNSUBSCRIBE);
+ responseTemplate.put(Bayeux.SUCCESSFUL_FIELD,Boolean.TRUE);
+ responseTemplate.put(Bayeux.ADVICE_FIELD, new HashMap<String, Object>());
+ }
+
+ public MetaUnsubscribeRequest(TomcatBayeux tb, HttpEvent event, JSONObject jsReq)
throws JSONException {
+ super(tb, event, jsReq);
+ }
+
+
+ /**
+ * Check client request for validity.
+ *
+ * Per section 4.6.1 of the Bayuex spec a connect request must contain:
+ * 1) The "/meta/unsubscribe" channel identifier.
+ * 2) The clientId.
+ * 3) The subscription. This is the name of the channel of interest,
+ * or a pattern.
+ *
+ * @return HttpError This method returns null if no errors were found
+ */
+ public HttpError validate() {
+ if(clientId==null|| (!this.getTomcatBayeux().hasClient(clientId)))
+ return new HttpError(400,"Client Id not valid.", null);
+ if (subscription==null||subscription.length()==0)
+ return new HttpError(400,"Subscription missing.",null);
+ return null;//no error
+ }
+
+ /**
+ * De-register interest for one or more channels. Per section 2.2.1 of the
+ * Bayeux spec, a pattern may be specified. Sever relationships.
+ */
+ public int process(int prevops) throws BayeuxException {
+ prevops = super.process(prevops);
+ response = (HashMap<String, Object>)responseTemplate.clone();
+ ClientImpl client = (ClientImpl)getTomcatBayeux().getClient(clientId);
+ HttpError error = validate();
+ if (error == null) {
+ boolean wildcard = subscription.indexOf('*')!=-1;
+ boolean unsubscribed = false;
+ if (wildcard) {
+ List<Channel> channels = getTomcatBayeux().getChannels();
+ Iterator<Channel> it = channels.iterator();
+ while (it.hasNext()) {
+ ChannelImpl ch = (ChannelImpl)it.next();
+ if (ch.matches(subscription)) {
+ ch.unsubscribe(client);
+ unsubscribed = true;
+ }
+ }
+ }else {
+ ChannelImpl ch =
(ChannelImpl)getTomcatBayeux().getChannel(subscription,true);
+ ch.unsubscribe(client);
+ unsubscribed = true;
+ }
+ response.put(Bayeux.SUCCESSFUL_FIELD, Boolean.valueOf(unsubscribed));
+ response.put(Bayeux.SUBSCRIPTION_FIELD,subscription);
+ ((HashMap) response.get(Bayeux.ADVICE_FIELD)).put("reconnect",
"retry");
+ ((HashMap) response.get(Bayeux.ADVICE_FIELD)).put("interval",
getReconnectInterval());
+ }else {
+ response.put(Bayeux.SUCCESSFUL_FIELD,Boolean.FALSE);
+ response.put(Bayeux.ERROR_FIELD, error.toString());
+ ((HashMap) response.get(Bayeux.ADVICE_FIELD)).put("reconnect",
"handshake");
+ if (client==null) client = TomcatBayeux.getErrorClient();
+ }
+ response.put(Bayeux.CLIENT_FIELD, client.getId());
+ response.put(Bayeux.TIMESTAMP_FIELD,getTimeStamp());
+ try {
+ JSONObject obj = new JSONObject(response);
+ addToDeliveryQueue(client, obj);
+ } catch (ServletException x) {
+ throw new BayeuxException(x);
+ } catch (IOException x) {
+ throw new BayeuxException(x);
+ }
+ return 0;
+ }
+}
+
Added: trunk/java/org/apache/tomcat/bayeux/request/PublishRequest.java
===================================================================
--- trunk/java/org/apache/tomcat/bayeux/request/PublishRequest.java
(rev 0)
+++ trunk/java/org/apache/tomcat/bayeux/request/PublishRequest.java 2008-09-19 01:53:57
UTC (rev 784)
@@ -0,0 +1,137 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.bayeux.request;
+
+import java.io.IOException;
+import java.util.HashMap;
+
+import javax.servlet.ServletException;
+
+import org.apache.cometd.bayeux.Bayeux;
+import org.apache.tomcat.bayeux.BayeuxException;
+import org.apache.tomcat.bayeux.BayeuxRequest;
+import org.apache.tomcat.bayeux.ChannelImpl;
+import org.apache.tomcat.bayeux.ClientImpl;
+import org.apache.tomcat.bayeux.HttpError;
+import org.apache.tomcat.bayeux.MessageImpl;
+import org.apache.tomcat.bayeux.RequestBase;
+import org.apache.tomcat.bayeux.TomcatBayeux;
+import org.apache.tomcat.util.json.JSONException;
+import org.apache.tomcat.util.json.JSONObject;
+import org.jboss.servlet.http.HttpEvent;
+
+/******************************************************************************
+ * Handshake request Bayeux message.
+ *
+ * @author Guy A. Molinari
+ * @author Filip Hanik
+ * @version 1.0
+ *
+ */
+public class PublishRequest extends RequestBase implements BayeuxRequest {
+
+ JSONObject msgData = null;
+
+ protected static HashMap<String,Object> responseTemplate = new
HashMap<String,Object>();
+
+ static {
+ responseTemplate.put(Bayeux.SUCCESSFUL_FIELD,Boolean.TRUE);
+ responseTemplate.put(Bayeux.ADVICE_FIELD, new HashMap<String, Object>());
+ }
+
+ public PublishRequest(TomcatBayeux tb, HttpEvent event, JSONObject jsReq) throws
JSONException {
+ super(tb, event, jsReq);
+ }
+
+
+ /**
+ * Check client request for validity.
+ *
+ * Per section 5.1.1 of the Bayuex spec a connect request must contain:
+ * 1) The channel identifier of the channel for publication.
+ * 2) The data to send.
+ *
+ * @return HttpError This method returns null if no errors were found
+ */
+ public HttpError validate() {
+ if(channel==null|| (!this.getTomcatBayeux().hasChannel(channel)))
+ return new HttpError(400,"Channel Id not valid.", null);
+ if(data==null || data.length()==0)
+ return new HttpError(400,"Message data missing.", null);
+ try {
+ this.msgData = new JSONObject(data);
+ }catch (JSONException x) {
+ return new HttpError(400,"Invalid JSON object in data
attribute.",x);
+ }
+ if(clientId==null|| (!this.getTomcatBayeux().hasClient(clientId)))
+ return new HttpError(400,"Client Id not valid.", null);
+ return null;//no error
+ }
+
+ /**
+ * Send the event message to all registered subscribers.
+ */
+ public int process(int prevops) throws BayeuxException {
+ prevops = super.process(prevops);
+ response = (HashMap<String, Object>)responseTemplate.clone();
+ ClientImpl client =
clientId!=null?(ClientImpl)getTomcatBayeux().getClient(clientId):
+
(ClientImpl)event.getHttpServletRequest().getAttribute("client");
+ boolean success = false;
+ HttpError error = validate();
+ if (error == null) {
+ ChannelImpl chimpl =
(ChannelImpl)getTomcatBayeux().getChannel(channel,false);
+ MessageImpl mimpl = (MessageImpl)getTomcatBayeux().newMessage(client);
+
+ try {
+ String[] keys = JSONObject.getNames(msgData);
+ for (int i = 0; i < keys.length; i++) {
+ mimpl.put(keys[i], msgData.get(keys[i]));
+ }
+ success = true;
+ ((HashMap) response.get(Bayeux.ADVICE_FIELD)).put(Bayeux.RECONNECT_FIELD,
Bayeux.RETRY_RESPONSE);
+ ((HashMap) response.get(Bayeux.ADVICE_FIELD)).put(Bayeux.INTERVAL_FIELD,
getReconnectInterval());
+ }catch (JSONException x) {
+ throw new BayeuxException(x);
+ }
+ chimpl.publish(mimpl);
+ }
+ if(!success) {
+ response.put(Bayeux.SUCCESSFUL_FIELD,Boolean.FALSE);
+ response.put(Bayeux.ERROR_FIELD, error.toString());
+ ((HashMap) response.get(Bayeux.ADVICE_FIELD)).put(Bayeux.RECONNECT_FIELD,
Bayeux.HANDSHAKE_RESPONSE);
+ if (client==null) client = TomcatBayeux.getErrorClient();
+ }
+ response.put(Bayeux.CHANNEL_FIELD,channel);
+ response.put(Bayeux.CLIENT_FIELD, client.getId());
+ try {
+ JSONObject obj = new JSONObject(response);
+ addToDeliveryQueue(client, obj);
+ } catch (ServletException x) {
+ throw new BayeuxException(x);
+ } catch (IOException x) {
+ throw new BayeuxException(x);
+ }
+
+ if (success && client!=null && client.hasMessages()) {
+ //send out messages
+ flushMessages(client);
+ }
+
+ return 0;
+ }
+}
+
Added: trunk/java/org/apache/tomcat/util/json/JSONArray.java
===================================================================
--- trunk/java/org/apache/tomcat/util/json/JSONArray.java (rev 0)
+++ trunk/java/org/apache/tomcat/util/json/JSONArray.java 2008-09-19 01:53:57 UTC (rev
784)
@@ -0,0 +1,936 @@
+package org.apache.tomcat.util.json;
+
+/*
+Copyright (c) 2002
JSON.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+The Software shall be used for Good, not Evil.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+*/
+
+import java.io.IOException;
+import java.io.Writer;
+import java.lang.reflect.Array;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * A JSONArray is an ordered sequence of values. Its external text form is a
+ * string wrapped in square brackets with commas separating the values. The
+ * internal form is an object having <code>get</code> and
<code>opt</code>
+ * methods for accessing the values by index, and <code>put</code> methods
for
+ * adding or replacing values. The values can be any of these types:
+ * <code>Boolean</code>, <code>JSONArray</code>,
<code>JSONObject</code>,
+ * <code>Number</code>, <code>String</code>, or the
+ * <code>JSONObject.NULL object</code>.
+ * <p>
+ * The constructor can convert a JSON text into a Java object. The
+ * <code>toString</code> method converts to JSON text.
+ * <p>
+ * A <code>get</code> method returns a value if one can be found, and throws
an
+ * exception if one cannot be found. An <code>opt</code> method returns a
+ * default value instead of throwing an exception, and so is useful for
+ * obtaining optional values.
+ * <p>
+ * The generic <code>get()</code> and <code>opt()</code> methods
return an
+ * object which you can cast or query for type. There are also typed
+ * <code>get</code> and <code>opt</code> methods that do type
checking and type
+ * coersion for you.
+ * <p>
+ * The texts produced by the <code>toString</code> methods strictly conform
to
+ * JSON syntax rules. The constructors are more forgiving in the texts they will
+ * accept:
+ * <ul>
+ * <li>An extra
<code>,</code> <small>(comma)</small> may appear just
+ * before the closing bracket.</li>
+ * <li>The <code>null</code> value will be inserted when there
+ * is <code>,</code> <small>(comma)</small>
elision.</li>
+ * <li>Strings may be quoted with
<code>'</code> <small>(single
+ * quote)</small>.</li>
+ * <li>Strings do not need to be quoted at all if they do not begin with a quote
+ * or single quote, and if they do not contain leading or trailing spaces,
+ * and if they do not contain any of these characters:
+ * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like
numbers
+ * and if they are not the reserved words <code>true</code>,
+ * <code>false</code>, or <code>null</code>.</li>
+ * <li>Values can be separated by <code>;</code>
<small>(semicolon)</small> as
+ * well as by <code>,</code>
<small>(comma)</small>.</li>
+ * <li>Numbers may have the <code>0-</code>
<small>(octal)</small> or
+ * <code>0x-</code> <small>(hex)</small> prefix.</li>
+ * <li>Comments written in the slashshlash, slashstar, and hash conventions
+ * will be ignored.</li>
+ * </ul>
+
+ * @author
JSON.org
+ * @version 2008-09-18
+ */
+public class JSONArray {
+
+
+ /**
+ * The arrayList where the JSONArray's properties are kept.
+ */
+ private ArrayList myArrayList;
+
+
+ /**
+ * Construct an empty JSONArray.
+ */
+ public JSONArray() {
+ this.myArrayList = new ArrayList();
+ }
+
+ /**
+ * 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();
+ char c = x.nextClean();
+ char q;
+ if (c == '[') {
+ q = ']';
+ } else if (c == '(') {
+ q = ')';
+ } else {
+ throw x.syntaxError("A JSONArray text must start with
'['");
+ }
+ if (x.nextClean() == ']') {
+ return;
+ }
+ x.back();
+ for (;;) {
+ if (x.nextClean() == ',') {
+ x.back();
+ this.myArrayList.add(null);
+ } else {
+ x.back();
+ this.myArrayList.add(x.nextValue());
+ }
+ c = x.nextClean();
+ switch (c) {
+ case ';':
+ case ',':
+ if (x.nextClean() == ']') {
+ return;
+ }
+ x.back();
+ break;
+ case ']':
+ case ')':
+ if (q != c) {
+ throw x.syntaxError("Expected a '" + new Character(q) +
"'");
+ }
+ return;
+ default:
+ throw x.syntaxError("Expected a ',' or ']'");
+ }
+ }
+ }
+
+
+ /**
+ * Construct a JSONArray from a source JSON text.
+ * @param source A string that begins with
+ * <code>[</code> <small>(left bracket)</small>
+ * and ends with <code>]</code> <small>(right
bracket)</small>.
+ * @throws JSONException If there is a syntax error.
+ */
+ public JSONArray(String source) throws JSONException {
+ this(new JSONTokener(source));
+ }
+
+
+ /**
+ * 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 collection of beans.
+ * The collection should have Java Beans.
+ *
+ * @throws JSONException If not an array.
+ */
+
+ public JSONArray(Collection collection,boolean includeSuperClass) {
+ this.myArrayList = new ArrayList();
+ if(collection != null) {
+ for (Iterator iter = collection.iterator(); iter.hasNext();) {
+ this.myArrayList.add(new JSONObject(iter.next(),includeSuperClass));
+ }
+ }
+ }
+
+
+ /**
+ * Construct a JSONArray from an array
+ * @throws JSONException If not an array.
+ */
+ public JSONArray(Object array) throws JSONException {
+ this();
+ if (array.getClass().isArray()) {
+ int length = Array.getLength(array);
+ for (int i = 0; i < length; i += 1) {
+ this.put(Array.get(array, i));
+ }
+ } else {
+ throw new JSONException("JSONArray initial value should be a string or
collection or array.");
+ }
+ }
+
+ /**
+ * Construct a JSONArray from an array with a bean.
+ * The array should have Java Beans.
+ *
+ * @throws JSONException If not an array.
+ */
+ public JSONArray(Object array,boolean includeSuperClass) throws JSONException {
+ this();
+ if (array.getClass().isArray()) {
+ int length = Array.getLength(array);
+ for (int i = 0; i < length; i += 1) {
+ this.put(new JSONObject(Array.get(array, i),includeSuperClass));
+ }
+ } else {
+ throw new JSONException("JSONArray initial value should be a string or
collection or array.");
+ }
+ }
+
+
+
+ /**
+ * Get the object value associated with an index.
+ * @param index
+ * The index must be between 0 and length() - 1.
+ * @return An object value.
+ * @throws JSONException If there is no value for the index.
+ */
+ 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.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The truth.
+ * @throws JSONException If there is no value for the index or if the
+ * value is not convertable to boolean.
+ */
+ public boolean getBoolean(int index) throws JSONException {
+ Object o = get(index);
+ 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"))) {
+ return true;
+ }
+ throw new JSONException("JSONArray[" + index + "] is not a
Boolean.");
+ }
+
+
+ /**
+ * Get the double value associated with an index.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The value.
+ * @throws JSONException If the key is not found or if the value cannot
+ * be converted to a number.
+ */
+ public double getDouble(int index) throws JSONException {
+ Object o = get(index);
+ try {
+ return o instanceof Number ?
+ ((Number)o).doubleValue() :
+ Double.valueOf((String)o).doubleValue();
+ } catch (Exception e) {
+ throw new JSONException("JSONArray[" + index +
+ "] is not a number.");
+ }
+ }
+
+
+ /**
+ * Get the int value associated with an index.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The value.
+ * @throws JSONException If the key is not found or if the value cannot
+ * be converted to a number.
+ * if the value cannot be converted to a number.
+ */
+ public int getInt(int index) throws JSONException {
+ Object o = get(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.
+ * @return A JSONArray value.
+ * @throws JSONException If there is no value for the index. or if the
+ * value is not a JSONArray
+ */
+ public JSONArray getJSONArray(int index) throws JSONException {
+ Object o = get(index);
+ if (o instanceof JSONArray) {
+ return (JSONArray)o;
+ }
+ throw new JSONException("JSONArray[" + index +
+ "] is not a JSONArray.");
+ }
+
+
+ /**
+ * Get the JSONObject associated with an index.
+ * @param index subscript
+ * @return A JSONObject value.
+ * @throws JSONException If there is no value for the index or if the
+ * value is not a JSONObject
+ */
+ public JSONObject getJSONObject(int index) throws JSONException {
+ Object o = get(index);
+ if (o instanceof JSONObject) {
+ return (JSONObject)o;
+ }
+ throw new JSONException("JSONArray[" + index +
+ "] is not a JSONObject.");
+ }
+
+
+ /**
+ * Get the long value associated with an index.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The value.
+ * @throws JSONException If the key is not found or if the value cannot
+ * be converted to a number.
+ */
+ public long getLong(int index) throws JSONException {
+ Object o = get(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.
+ * @return A string value.
+ * @throws JSONException If there is no value for the index.
+ */
+ public String getString(int index) throws JSONException {
+ return get(index).toString();
+ }
+
+
+ /**
+ * Determine if the value is null.
+ * @param index The index must be between 0 and length() - 1.
+ * @return true if the value at the index is null, or if there is no value.
+ */
+ public boolean isNull(int index) {
+ 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.
+ * Warning: This method assumes that the data structure is acyclical.
+ * @param separator A string that will be inserted between the elements.
+ * @return a string.
+ * @throws JSONException If the array contains an invalid number.
+ */
+ public String join(String separator) throws JSONException {
+ int len = length();
+ StringBuffer sb = new StringBuffer();
+
+ for (int i = 0; i < len; i += 1) {
+ 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.
+ *
+ * @return The length (or size).
+ */
+ public int length() {
+ return this.myArrayList.size();
+ }
+
+
+ /**
+ * Get the optional object value associated with an index.
+ * @param index The index must be between 0 and length() - 1.
+ * @return An object value, or null if there is no
+ * object at that index.
+ */
+ public Object opt(int 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,
+ * or if the value is not Boolean.TRUE or the String "true".
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The truth.
+ */
+ 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
+ * it is not a Boolean or the String "true" or "false" (case
insensitive).
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @param defaultValue A boolean default.
+ * @return The truth.
+ */
+ public boolean optBoolean(int index, boolean defaultValue) {
+ try {
+ return getBoolean(index);
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+
+ /**
+ * Get the optional double value associated with an index.
+ * NaN is returned if there is no value for the index,
+ * or if the value is not a number and cannot be converted to a number.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The value.
+ */
+ public double optDouble(int index) {
+ 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,
+ * or if the value is not a number and cannot be converted to a number.
+ *
+ * @param index subscript
+ * @param defaultValue The default value.
+ * @return The value.
+ */
+ public double optDouble(int index, double defaultValue) {
+ try {
+ return getDouble(index);
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+
+ /**
+ * Get the optional int value associated with an index.
+ * Zero is returned if there is no value for the index,
+ * or if the value is not a number and cannot be converted to a number.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The value.
+ */
+ public int optInt(int index) {
+ 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,
+ * or if the value is not a number and cannot be converted to a number.
+ * @param index The index must be between 0 and length() - 1.
+ * @param defaultValue The default value.
+ * @return The value.
+ */
+ public int optInt(int index, int defaultValue) {
+ try {
+ return getInt(index);
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+
+ /**
+ * Get the optional JSONArray associated with an index.
+ * @param index subscript
+ * @return A JSONArray value, or null if the index has no value,
+ * or if the value is not a JSONArray.
+ */
+ public JSONArray optJSONArray(int index) {
+ Object o = opt(index);
+ 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
+ * no value, or if the value is not a JSONObject.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return A JSONObject value.
+ */
+ public JSONObject optJSONObject(int index) {
+ Object o = opt(index);
+ 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,
+ * or if the value is not a number and cannot be converted to a number.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The value.
+ */
+ public long optLong(int index) {
+ 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,
+ * or if the value is not a number and cannot be converted to a number.
+ * @param index The index must be between 0 and length() - 1.
+ * @param defaultValue The default value.
+ * @return The value.
+ */
+ public long optLong(int index, long defaultValue) {
+ try {
+ return getLong(index);
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+
+ /**
+ * 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
+ * is not a string and is not null, then it is coverted to a string.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return A String value.
+ */
+ public String optString(int index) {
+ return optString(index, "");
+ }
+
+
+ /**
+ * Get the optional string associated with an index.
+ * The defaultValue is returned if the key is not found.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @param defaultValue The default value.
+ * @return A String value.
+ */
+ public String optString(int index, String defaultValue) {
+ Object o = opt(index);
+ return o != null ? o.toString() : defaultValue;
+ }
+
+
+ /**
+ * Append a boolean value. This increases the array's length by one.
+ *
+ * @param value A boolean value.
+ * @return this.
+ */
+ 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.
+ */
+ public JSONArray put(Collection value) {
+ put(new JSONArray(value));
+ return this;
+ }
+
+
+ /**
+ * Append a double value. This increases the array's length by one.
+ *
+ * @param value A double value.
+ * @throws JSONException if the value is not finite.
+ * @return this.
+ */
+ 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.
+ *
+ * @param value An int value.
+ * @return this.
+ */
+ public JSONArray put(int value) {
+ put(new Integer(value));
+ return this;
+ }
+
+
+ /**
+ * Append an long value. This increases the array's length by one.
+ *
+ * @param value A long value.
+ * @return this.
+ */
+ 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.
+ */
+ 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
+ * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
+ * JSONObject.NULL object.
+ * @return this.
+ */
+ 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
+ * necessary to pad it out.
+ * @param index The subscript.
+ * @param value A boolean value.
+ * @return this.
+ * @throws JSONException If the index is negative.
+ */
+ 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.
+ * @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
+ * it out.
+ * @param index The subscript.
+ * @param value A double value.
+ * @return this.
+ * @throws JSONException If the index is negative or if the value is
+ * not finite.
+ */
+ 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
+ * it out.
+ * @param index The subscript.
+ * @param value An int value.
+ * @return this.
+ * @throws JSONException If the index is negative.
+ */
+ 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
+ * it out.
+ * @param index The subscript.
+ * @param value A long value.
+ * @return this.
+ * @throws JSONException If the index is negative.
+ */
+ 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.
+ * @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
+ * necessary to pad it out.
+ * @param index The subscript.
+ * @param value The value to put into the array. The value should be a
+ * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
+ * JSONObject.NULL object.
+ * @return this.
+ * @throws JSONException If the index is negative or if the the value is
+ * an invalid number.
+ */
+ 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.
+ * @param names A JSONArray containing a list of key strings. These will be
+ * paired with the values.
+ * @return A JSONObject, or null if there are no names or if this JSONArray
+ * has no values.
+ * @throws JSONException If any of the names are null.
+ */
+ public JSONObject toJSONObject(JSONArray names) throws JSONException {
+ 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
+ * syntactically correct JSON text then null will be returned instead. This
+ * could occur if the array contains an invalid number.
+ * <p>
+ * Warning: This method assumes that the data structure is acyclical.
+ *
+ * @return a printable, displayable, transmittable
+ * representation of the array.
+ */
+ public String toString() {
+ try {
+ return '[' + join(",") + ']';
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+
+ /**
+ * Make a prettyprinted JSON text of this JSONArray.
+ * Warning: This method assumes that the data structure is acyclical.
+ * @param indentFactor The number of spaces to add to each level of
+ * indentation.
+ * @return a printable, displayable, transmittable
+ * representation of the object, beginning
+ * with <code>[</code> <small>(left
bracket)</small> and ending
+ * with <code>]</code> <small>(right
bracket)</small>.
+ * @throws JSONException
+ */
+ public String toString(int indentFactor) throws JSONException {
+ return toString(indentFactor, 0);
+ }
+
+
+ /**
+ * Make a prettyprinted JSON text of this JSONArray.
+ * Warning: This method assumes that the data structure is acyclical.
+ * @param indentFactor The number of spaces to add to each level of
+ * indentation.
+ * @param indent The indention of the top level.
+ * @return a printable, displayable, transmittable
+ * representation of the array.
+ * @throws JSONException
+ */
+ 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));
+ } 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('\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.
+ * <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;
+ int len = length();
+
+ writer.write('[');
+
+ for (int i = 0; i < len; i += 1) {
+ if (b) {
+ writer.write(',');
+ }
+ Object v = this.myArrayList.get(i);
+ if (v instanceof JSONObject) {
+ ((JSONObject)v).write(writer);
+ } else if (v instanceof JSONArray) {
+ ((JSONArray)v).write(writer);
+ } else {
+ writer.write(JSONObject.valueToString(v));
+ }
+ b = true;
+ }
+ writer.write(']');
+ return writer;
+ } catch (IOException e) {
+ throw new JSONException(e);
+ }
+ }
+}
\ No newline at end of file
Added: trunk/java/org/apache/tomcat/util/json/JSONException.java
===================================================================
--- trunk/java/org/apache/tomcat/util/json/JSONException.java (rev
0)
+++ trunk/java/org/apache/tomcat/util/json/JSONException.java 2008-09-19 01:53:57 UTC (rev
784)
@@ -0,0 +1,27 @@
+package org.apache.tomcat.util.json;
+
+/**
+ * The JSONException is thrown by the
JSON.org classes then things are amiss.
+ * @author
JSON.org
+ * @version 2008-09-18
+ */
+public class JSONException extends Exception {
+ private Throwable cause;
+
+ /**
+ * Constructs a JSONException with an explanatory message.
+ * @param message Detail about the reason for the exception.
+ */
+ public JSONException(String message) {
+ super(message);
+ }
+
+ public JSONException(Throwable t) {
+ super(t.getMessage());
+ this.cause = t;
+ }
+
+ public Throwable getCause() {
+ return this.cause;
+ }
+}
Added: trunk/java/org/apache/tomcat/util/json/JSONObject.java
===================================================================
--- trunk/java/org/apache/tomcat/util/json/JSONObject.java (rev
0)
+++ trunk/java/org/apache/tomcat/util/json/JSONObject.java 2008-09-19 01:53:57 UTC (rev
784)
@@ -0,0 +1,1550 @@
+package org.apache.tomcat.util.json;
+
+/*
+Copyright (c) 2002
JSON.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+The Software shall be used for Good, not Evil.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+*/
+
+import java.io.IOException;
+import java.io.Writer;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.TreeSet;
+
+/**
+ * A JSONObject is an unordered collection of name/value pairs. Its
+ * external form is a string wrapped in curly braces with colons between the
+ * names and values, and commas between the values and names. The internal form
+ * is an object having <code>get</code> and <code>opt</code>
methods for
+ * accessing the values by name, and <code>put</code> methods for adding or
+ * replacing values by name. The values can be any of these types:
+ * <code>Boolean</code>, <code>JSONArray</code>,
<code>JSONObject</code>,
+ * <code>Number</code>, <code>String</code>, or the
<code>JSONObject.NULL</code>
+ * object. A JSONObject constructor can be used to convert an external form
+ * JSON text into an internal form whose values can be retrieved with the
+ * <code>get</code> and <code>opt</code> methods, or to convert
values into a
+ * JSON text using the <code>put</code> and <code>toString</code>
methods.
+ * A <code>get</code> method returns a value if one can be found, and throws
an
+ * exception if one cannot be found. An <code>opt</code> method returns a
+ * default value instead of throwing an exception, and so is useful for
+ * obtaining optional values.
+ * <p>
+ * The generic <code>get()</code> and <code>opt()</code> methods
return an
+ * object, which you can cast or query for type. There are also typed
+ * <code>get</code> and <code>opt</code> methods that do type
checking and type
+ * coercion for you.
+ * <p>
+ * The <code>put</code> methods adds values to an object. For example,
<pre>
+ * myString = new JSONObject().put("JSON", "Hello,
World!").toString();</pre>
+ * produces the string <code>{"JSON": "Hello,
World"}</code>.
+ * <p>
+ * The texts produced by the <code>toString</code> methods strictly conform
to
+ * the JSON syntax rules.
+ * The constructors are more forgiving in the texts they will accept:
+ * <ul>
+ * <li>An extra
<code>,</code> <small>(comma)</small> may appear just
+ * before the closing brace.</li>
+ * <li>Strings may be quoted with
<code>'</code> <small>(single
+ * quote)</small>.</li>
+ * <li>Strings do not need to be quoted at all if they do not begin with a quote
+ * or single quote, and if they do not contain leading or trailing spaces,
+ * and if they do not contain any of these characters:
+ * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like
numbers
+ * and if they are not the reserved words <code>true</code>,
+ * <code>false</code>, or <code>null</code>.</li>
+ * <li>Keys can be followed by <code>=</code> or
<code>=></code> as well as
+ * by <code>:</code>.</li>
+ * <li>Values can be followed by <code>;</code>
<small>(semicolon)</small> as
+ * well as by <code>,</code>
<small>(comma)</small>.</li>
+ * <li>Numbers may have the <code>0-</code>
<small>(octal)</small> or
+ * <code>0x-</code> <small>(hex)</small> prefix.</li>
+ * </ul>
+ * @author
JSON.org
+ * @version 2008-09-18
+ */
+public class JSONObject {
+
+ /**
+ * 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 {
+
+ /**
+ * 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";
+ }
+ }
+
+
+ /**
+ * The map where the JSONObject's properties are kept.
+ */
+ private Map map;
+
+
+ /**
+ * 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>.
+ * <code>JSONObject.NULL.toString()</code> returns
<code>"null"</code>.
+ */
+ public static final Object NULL = new Null();
+
+
+ /**
+ * Construct an empty JSONObject.
+ */
+ public JSONObject() {
+ this.map = 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 names An array of strings.
+ * @exception JSONException If a value is a non-finite number or if a name is
duplicated.
+ */
+ public JSONObject(JSONObject jo, String[] names) throws JSONException {
+ this();
+ for (int i = 0; i < names.length; i += 1) {
+ putOnce(names[i], jo.opt(names[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
+ * or a duplicated key.
+ */
+ 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();
+ }
+
+ /*
+ * The key is followed by ':'. We will also tolerate '=' or
'=>'.
+ */
+
+ c = x.nextClean();
+ if (c == '=') {
+ if (x.next() != '>') {
+ x.back();
+ }
+ } else if (c != ':') {
+ throw x.syntaxError("Expected a ':' after a key");
+ }
+ putOnce(key, x.nextValue());
+
+ /*
+ * Pairs are separated by ','. We will also tolerate ';'.
+ */
+
+ switch (x.nextClean()) {
+ case ';':
+ case ',':
+ if (x.nextClean() == '}') {
+ return;
+ }
+ x.back();
+ break;
+ case '}':
+ return;
+ 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.map = (map == null) ? new HashMap() : map;
+ }
+
+ /**
+ * Construct a JSONObject from a Map.
+ *
+ * Note: Use this constructor when the map contains <key,bean>.
+ *
+ * @param map - A map with Key-Bean data.
+ * @param includeSuperClass - Tell whether to include the super class properties.
+ */
+ public JSONObject(Map map, boolean includeSuperClass) {
+ this.map = new HashMap();
+ if (map != null){
+ for (Iterator i = map.entrySet().iterator(); i.hasNext(); ) {
+ Map.Entry e = (Map.Entry)i.next();
+ this.map.put(e.getKey(), new JSONObject(e.getValue(),
includeSuperClass));
+ }
+ }
+ }
+
+
+ /**
+ * Construct a JSONObject from an Object using bean getters.
+ * It reflects on all of the public methods of the object.
+ * For each of the methods with no parameters and a name starting
+ * with <code>"get"</code> or
<code>"is"</code> followed by an uppercase letter,
+ * the method is invoked, and a key and the value returned from the getter method
+ * are put into the new JSONObject.
+ *
+ * The key is formed by removing the <code>"get"</code> or
<code>"is"</code> prefix. If the second remaining
+ * character is not upper case, then the first
+ * character is converted to lower case.
+ *
+ * For example, if an object has a method named
<code>"getName"</code>, and
+ * if the result of calling <code>object.getName()</code> is
<code>"Larry Fine"</code>,
+ * then the JSONObject will contain <code>"name": "Larry
Fine"</code>.
+ *
+ * @param bean An object that has getter methods that should be used
+ * to make a JSONObject.
+ */
+ public JSONObject(Object bean) {
+ this();
+ populateInternalMap(bean, false);
+ }
+
+
+ /**
+ * Construct JSONObject from the given bean. This will also create JSONObject
+ * for all internal object (List, Map, Inner Objects) of the provided bean.
+ *
+ * -- See Documentation of JSONObject(Object bean) also.
+ *
+ * @param bean An object that has getter methods that should be used
+ * to make a JSONObject.
+ * @param includeSuperClass - Tell whether to include the super class properties.
+ */
+ public JSONObject(Object bean, boolean includeSuperClass) {
+ this();
+ populateInternalMap(bean, includeSuperClass);
+ }
+
+ private void populateInternalMap(Object bean, boolean includeSuperClass){
+ Class klass = bean.getClass();
+
+ //If klass.getSuperClass is System class then includeSuperClass = false;
+
+ if (klass.getClassLoader() == null) {
+ includeSuperClass = false;
+ }
+
+ Method[] methods = (includeSuperClass) ?
+ klass.getMethods() : klass.getDeclaredMethods();
+ for (int i = 0; i < methods.length; i += 1) {
+ try {
+ Method method = methods[i];
+ String name = method.getName();
+ String key = "";
+ if (name.startsWith("get")) {
+ key = name.substring(3);
+ } else if (name.startsWith("is")) {
+ key = name.substring(2);
+ }
+ if (key.length() > 0 &&
+ Character.isUpperCase(key.charAt(0)) &&
+ method.getParameterTypes().length == 0) {
+ if (key.length() == 1) {
+ key = key.toLowerCase();
+ } else if (!Character.isUpperCase(key.charAt(1))) {
+ key = key.substring(0, 1).toLowerCase() +
+ key.substring(1);
+ }
+
+ Object result = method.invoke(bean, (Object[])null);
+ if (result == null){
+ map.put(key, NULL);
+ }else if (result.getClass().isArray()) {
+ map.put(key, new JSONArray(result,includeSuperClass));
+ }else if (result instanceof Collection) { //List or Set
+ map.put(key, new JSONArray((Collection)result,includeSuperClass));
+ }else if (result instanceof Map) {
+ map.put(key, new JSONObject((Map)result,includeSuperClass));
+ }else if (isStandardProperty(result.getClass())) { //Primitives,
String and Wrapper
+ map.put(key, result);
+ }else{
+ if
(result.getClass().getPackage().getName().startsWith("java") ||
+ result.getClass().getClassLoader() == null) {
+ map.put(key, result.toString());
+ } else { //User defined Objects
+ map.put(key, new JSONObject(result,includeSuperClass));
+ }
+ }
+ }
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ private boolean isStandardProperty(Class clazz) {
+ return clazz.isPrimitive() ||
+ clazz.isAssignableFrom(Byte.class) ||
+ clazz.isAssignableFrom(Short.class) ||
+ clazz.isAssignableFrom(Integer.class) ||
+ clazz.isAssignableFrom(Long.class) ||
+ clazz.isAssignableFrom(Float.class) ||
+ clazz.isAssignableFrom(Double.class) ||
+ clazz.isAssignableFrom(Character.class) ||
+ clazz.isAssignableFrom(String.class) ||
+ clazz.isAssignableFrom(Boolean.class);
+ }
+
+ /**
+ * 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
+ * with those keys in the object. If a key is not found or not visible,
+ * then it will not be copied into the new JSONObject.
+ * @param object An object that has fields that should be used to make a
+ * JSONObject.
+ * @param names An array of strings, the names of the fields to be obtained
+ * from the object.
+ */
+ public JSONObject(Object object, String names[]) {
+ this();
+ Class c = object.getClass();
+ for (int i = 0; i < names.length; i += 1) {
+ String name = names[i];
+ try {
+ putOpt(name, c.getField(name).get(object));
+ } catch (Exception e) {
+ /* forget about it */
+ }
+ }
+ }
+
+
+ /**
+ * Construct a JSONObject from a source JSON text string.
+ * This is the most commonly used JSONObject constructor.
+ * @param source 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 or a duplicated key.
+ */
+ public JSONObject(String source) throws JSONException {
+ this(new JSONTokener(source));
+ }
+
+
+ /**
+ * 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
+ * JSONArray is stored under the key to hold all of the accumulated values.
+ * If there is already a JSONArray, then the new value is appended to it.
+ * In contrast, the put method replaces the previous value.
+ * @param key A key string.
+ * @param value An object to be accumulated under the key.
+ * @return this.
+ * @throws JSONException If the value is an invalid number
+ * or if the key is null.
+ */
+ 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);
+ } else if (o instanceof JSONArray) {
+ ((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
+ * JSONArray containing the value parameter. If the key was already
+ * associated with a JSONArray, then the value parameter is appended to it.
+ * @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.
+ */
+ 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));
+ } else {
+ 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) {
+ if (Double.isInfinite(d) || Double.isNaN(d)) {
+ return "null";
+ }
+
+// Shave off trailing zeros and decimal point, if possible.
+
+ String s = Double.toString(d);
+ 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.
+ *
+ * @param key A key string.
+ * @return The object associated with the key.
+ * @throws JSONException if the key is not found.
+ */
+ public Object get(String key) throws JSONException {
+ Object o = opt(key);
+ if (o == null) {
+ throw new JSONException("JSONObject[" + quote(key) +
+ "] not found.");
+ }
+ return o;
+ }
+
+
+ /**
+ * Get the boolean value associated with a key.
+ *
+ * @param key A key string.
+ * @return The truth.
+ * @throws JSONException
+ * if the value is not a Boolean or the String "true" or
"false".
+ */
+ public boolean getBoolean(String key) throws JSONException {
+ Object o = get(key);
+ 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"))) {
+ return true;
+ }
+ throw new JSONException("JSONObject[" + quote(key) +
+ "] is not a Boolean.");
+ }
+
+
+ /**
+ * Get the double value associated with a key.
+ * @param key A key string.
+ * @return The numeric value.
+ * @throws JSONException if the key is not found or
+ * if the value is not a Number object and cannot be converted to a number.
+ */
+ public double getDouble(String key) throws JSONException {
+ Object o = get(key);
+ try {
+ 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.");
+ }
+ }
+
+
+ /**
+ * Get the int value associated with a key. If the number value is too
+ * large for an int, it will be clipped.
+ *
+ * @param key A key string.
+ * @return The integer value.
+ * @throws JSONException if the key is not found or if the value cannot
+ * be converted to an integer.
+ */
+ public int getInt(String key) throws JSONException {
+ Object o = get(key);
+ return o instanceof Number ?
+ ((Number)o).intValue() : (int)getDouble(key);
+ }
+
+
+ /**
+ * Get the JSONArray value associated with a key.
+ *
+ * @param key A key string.
+ * @return A JSONArray which is the value.
+ * @throws JSONException if the key is not found or
+ * if the value is not a JSONArray.
+ */
+ public JSONArray getJSONArray(String key) throws JSONException {
+ Object o = get(key);
+ if (o instanceof JSONArray) {
+ return (JSONArray)o;
+ }
+ throw new JSONException("JSONObject[" + quote(key) +
+ "] is not a JSONArray.");
+ }
+
+
+ /**
+ * Get the JSONObject value associated with a key.
+ *
+ * @param key A key string.
+ * @return A JSONObject which is the value.
+ * @throws JSONException if the key is not found or
+ * if the value is not a JSONObject.
+ */
+ public JSONObject getJSONObject(String key) throws JSONException {
+ Object o = get(key);
+ if (o instanceof JSONObject) {
+ return (JSONObject)o;
+ }
+ 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.
+ *
+ * @param key A key string.
+ * @return The long value.
+ * @throws JSONException if the key is not found or if the value cannot
+ * be converted to a long.
+ */
+ public long getLong(String key) throws JSONException {
+ Object o = get(key);
+ return o instanceof Number ?
+ ((Number)o).longValue() : (long)getDouble(key);
+ }
+
+
+ /**
+ * Get an array of field names from a JSONObject.
+ *
+ * @return An array of field names, or null if there are no names.
+ */
+ public static String[] getNames(JSONObject jo) {
+ int length = jo.length();
+ if (length == 0) {
+ return null;
+ }
+ Iterator i = jo.keys();
+ String[] names = new String[length];
+ int j = 0;
+ while (i.hasNext()) {
+ names[j] = (String)i.next();
+ j += 1;
+ }
+ return names;
+ }
+
+
+ /**
+ * Get an array of field names from an Object.
+ *
+ * @return An array of field names, or null if there are no names.
+ */
+ public static String[] getNames(Object object) {
+ if (object == null) {
+ return null;
+ }
+ Class klass = object.getClass();
+ Field[] fields = klass.getFields();
+ int length = fields.length;
+ if (length == 0) {
+ return null;
+ }
+ String[] names = new String[length];
+ for (int i = 0; i < length; i += 1) {
+ names[i] = fields[i].getName();
+ }
+ return names;
+ }
+
+
+ /**
+ * Get the string associated with a key.
+ *
+ * @param key A key string.
+ * @return A string which is the value.
+ * @throws JSONException if the key is not found.
+ */
+ public String getString(String key) throws JSONException {
+ return get(key).toString();
+ }
+
+
+ /**
+ * Determine if the JSONObject contains a specific key.
+ * @param key A key string.
+ * @return true if the key exists in the JSONObject.
+ */
+ public boolean has(String key) {
+ return this.map.containsKey(key);
+ }
+
+
+ /**
+ * Determine if the value associated with the key is null or if there is
+ * no value.
+ * @param key A key string.
+ * @return true if there is no value associated with the key or if
+ * the value is the JSONObject.NULL object.
+ */
+ public boolean isNull(String key) {
+ return JSONObject.NULL.equals(opt(key));
+ }
+
+
+ /**
+ * Get an enumeration of the keys of the JSONObject.
+ *
+ * @return An iterator of the keys.
+ */
+ public Iterator keys() {
+ return this.map.keySet().iterator();
+ }
+
+
+ /**
+ * Get the number of keys stored in the JSONObject.
+ *
+ * @return The number of keys in the JSONObject.
+ */
+ public int length() {
+ return this.map.size();
+ }
+
+
+ /**
+ * Produce a JSONArray containing the names of the elements of this
+ * JSONObject.
+ * @return A JSONArray containing the key strings, or null if the JSONObject
+ * is empty.
+ */
+ public JSONArray names() {
+ JSONArray ja = new JSONArray();
+ Iterator keys = keys();
+ while (keys.hasNext()) {
+ ja.put(keys.next());
+ }
+ return ja.length() == 0 ? null : ja;
+ }
+
+ /**
+ * Produce a string from a Number.
+ * @param n A Number
+ * @return A String.
+ * @throws JSONException If n is a non-finite number.
+ */
+ static public 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.
+
+ String s = n.toString();
+ 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.map.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
+ * Boolean.TRUE or the String "true".
+ *
+ * @param key A key string.
+ * @return The truth.
+ */
+ public boolean optBoolean(String key) {
+ 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
+ * a Boolean or the String "true" or "false" (case insensitive).
+ *
+ * @param key A key string.
+ * @param defaultValue The default.
+ * @return The truth.
+ */
+ public boolean optBoolean(String key, boolean defaultValue) {
+ try {
+ return getBoolean(key);
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+
+ /**
+ * 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.
+ * @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.
+ * If the value is a string, an attempt will be made to evaluate it as
+ * a number.
+ *
+ * @param key A string which is the key.
+ * @return An object which is the value.
+ */
+ public double optDouble(String key) {
+ 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.
+ * If the value is a string, an attempt will be made to evaluate it as
+ * a number.
+ *
+ * @param key A key string.
+ * @param defaultValue The default.
+ * @return An object which is the value.
+ */
+ public double optDouble(String key, double defaultValue) {
+ try {
+ Object o = opt(key);
+ 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.
+ * If the value is a string, an attempt will be made to evaluate it as
+ * a number.
+ *
+ * @param key A key string.
+ * @return An object which is the value.
+ */
+ public int optInt(String key) {
+ 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.
+ * If the value is a string, an attempt will be made to evaluate it as
+ * a number.
+ *
+ * @param key A key string.
+ * @param defaultValue The default.
+ * @return An object which is the value.
+ */
+ public int optInt(String key, int defaultValue) {
+ try {
+ return getInt(key);
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+
+ /**
+ * Get an optional JSONArray associated with a key.
+ * It returns null if there is no such key, or if its value is not a
+ * JSONArray.
+ *
+ * @param key A key string.
+ * @return A JSONArray which is the value.
+ */
+ public JSONArray optJSONArray(String key) {
+ Object o = opt(key);
+ 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
+ * JSONObject.
+ *
+ * @param key A key string.
+ * @return A JSONObject which is the value.
+ */
+ public JSONObject optJSONObject(String key) {
+ Object o = opt(key);
+ 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.
+ * If the value is a string, an attempt will be made to evaluate it as
+ * a number.
+ *
+ * @param key A key string.
+ * @return An object which is the value.
+ */
+ public long optLong(String key) {
+ 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.
+ * If the value is a string, an attempt will be made to evaluate it as
+ * a number.
+ *
+ * @param key A key string.
+ * @param defaultValue The default.
+ * @return An object which is the value.
+ */
+ public long optLong(String key, long defaultValue) {
+ try {
+ return getLong(key);
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+
+ /**
+ * Get an optional string associated with a key.
+ * It returns an empty string if there is no such key. If the value is not
+ * a string and is not null, then it is coverted to a string.
+ *
+ * @param key A key string.
+ * @return A string which is the value.
+ */
+ public String optString(String key) {
+ return optString(key, "");
+ }
+
+
+ /**
+ * Get an optional string associated with a key.
+ * It returns the defaultValue if there is no such key.
+ *
+ * @param key A key string.
+ * @param defaultValue The default.
+ * @return A string which is the value.
+ */
+ public String optString(String key, String defaultValue) {
+ Object o = opt(key);
+ return o != null ? o.toString() : defaultValue;
+ }
+
+
+ /**
+ * Put a key/boolean pair in the JSONObject.
+ *
+ * @param key A key string.
+ * @param value A boolean which is the value.
+ * @return this.
+ * @throws JSONException If the key is null.
+ */
+ 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.
+ *
+ * @param key A key string.
+ * @param value A double which is the value.
+ * @return this.
+ * @throws JSONException If the key is null or if the number is invalid.
+ */
+ public JSONObject put(String key, double value) throws JSONException {
+ put(key, new Double(value));
+ return this;
+ }
+
+
+ /**
+ * Put a key/int pair in the JSONObject.
+ *
+ * @param key A key string.
+ * @param value An int which is the value.
+ * @return this.
+ * @throws JSONException If the key is null.
+ */
+ public JSONObject put(String key, int value) throws JSONException {
+ put(key, new Integer(value));
+ return this;
+ }
+
+
+ /**
+ * Put a key/long pair in the JSONObject.
+ *
+ * @param key A key string.
+ * @param value A long which is the value.
+ * @return this.
+ * @throws JSONException If the key is null.
+ */
+ 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.
+ * @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.
+ * @param key A key string.
+ * @param value An object which is the value. It should be of one of these
+ * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
+ * or the JSONObject.NULL object.
+ * @return this.
+ * @throws JSONException If the value is non-finite number
+ * or if the key is null.
+ */
+ public JSONObject put(String key, Object value) throws JSONException {
+ if (key == null) {
+ throw new JSONException("Null key.");
+ }
+ if (value != null) {
+ testValidity(value);
+ this.map.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, and only if there is not already a member
+ * with that name.
+ * @param key
+ * @param value
+ * @return his.
+ * @throws JSONException if the key is a duplicate
+ */
+ public JSONObject putOnce(String key, Object value) throws JSONException {
+ if (key != null && value != null) {
+ if (opt(key) != null) {
+ throw new JSONException("Duplicate key \"" + key +
"\"");
+ }
+ put(key, value);
+ }
+ return this;
+ }
+
+
+ /**
+ * Put a key/value pair in the JSONObject, but only if the
+ * key and the value are both non-null.
+ * @param key A key string.
+ * @param value An object which is the value. It should be of one of these
+ * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
+ * or the JSONObject.NULL object.
+ * @return this.
+ * @throws JSONException If the value is a non-finite number.
+ */
+ public JSONObject putOpt(String key, Object value) throws JSONException {
+ 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
+ * text to be delivered in HTML. In JSON text, a string cannot contain a
+ * control character or an unescaped quote or backslash.
+ * @param string A String
+ * @return A String correctly formatted for insertion in a JSON text.
+ */
+ public static String quote(String string) {
+ if (string == null || string.length() == 0) {
+ return "\"\"";
+ }
+
+ char b;
+ char c = 0;
+ int i;
+ int len = string.length();
+ StringBuffer sb = new StringBuffer(len + 4);
+ 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 == '<') {
+ 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 < ' ' || (c >= '\u0080' && c <
'\u00a0') ||
+ (c >= '\u2000' && c <
'\u2100')) {
+ t = "000" + Integer.toHexString(c);
+ sb.append("\\u" + t.substring(t.length() - 4));
+ } else {
+ sb.append(c);
+ }
+ }
+ }
+ sb.append('"');
+ return sb.toString();
+ }
+
+ /**
+ * Remove a name and its value, if present.
+ * @param key The name to be removed.
+ * @return The value that was associated with the name,
+ * or null if there was no value.
+ */
+ public Object remove(String key) {
+ return this.map.remove(key);
+ }
+
+ /**
+ * Get an enumeration of the keys of the JSONObject.
+ * The keys will be sorted alphabetically.
+ *
+ * @return An iterator of the keys.
+ */
+ public Iterator sortedKeys() {
+ return new TreeSet(this.map.keySet()).iterator();
+ }
+
+ /**
+ * Try to convert a string into a number, boolean, or null. If the string
+ * can't be converted, return the string.
+ * @param s A String.
+ * @return A simple JSON value.
+ */
+ static public Object stringToValue(String s) {
+ if (s.equals("")) {
+ return s;
+ }
+ if (s.equalsIgnoreCase("true")) {
+ return Boolean.TRUE;
+ }
+ if (s.equalsIgnoreCase("false")) {
+ return Boolean.FALSE;
+ }
+ if (s.equalsIgnoreCase("null")) {
+ return JSONObject.NULL;
+ }
+
+ /*
+ * If it might be a number, try converting it. We support the 0- and 0x-
+ * conventions. If a number cannot be produced, then the value will just
+ * be a string. Note that the 0-, 0x-, plus, and implied string
+ * conventions are non-standard. A JSON parser is free to accept
+ * non-JSON forms as long as it accepts all correct JSON forms.
+ */
+
+ char b = s.charAt(0);
+ if ((b >= '0' && b <= '9') || b == '.' || b
== '-' || b == '+') {
+ if (b == '0') {
+ if (s.length() > 2 &&
+ (s.charAt(1) == 'x' || s.charAt(1) == 'X')) {
+ try {
+ 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) {
+ try {
+ return new Long(s);
+ } catch (Exception f) {
+ try {
+ return new Double(s);
+ } catch (Exception g) {
+ /* Ignore the error */
+ }
+ }
+ }
+ }
+ return s;
+ }
+
+
+ /**
+ * Throw an exception if the object is an NaN or infinite number.
+ * @param o The object to test.
+ * @throws JSONException If o is a non-finite number.
+ */
+ 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.");
+ }
+ } else if (o instanceof Float) {
+ 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.
+ * @param names A JSONArray containing a list of key strings. This
+ * determines the sequence of the values in the result.
+ * @return A JSONArray of values.
+ * @throws JSONException If any of the values are non-finite numbers.
+ */
+ public JSONArray toJSONArray(JSONArray names) throws JSONException {
+ 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;
+ }
+
+ /**
+ * Make a JSON text of this JSONObject. For compactness, no whitespace
+ * is added. If this would not result in a syntactically correct JSON text,
+ * then null will be returned instead.
+ * <p>
+ * Warning: This method assumes that the data structure is acyclical.
+ *
+ * @return a printable, displayable, portable, transmittable
+ * representation of the object, beginning
+ * with <code>{</code> <small>(left brace)</small>
and ending
+ * with <code>}</code> <small>(right
brace)</small>.
+ */
+ public String toString() {
+ try {
+ 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.map.get(o)));
+ }
+ sb.append('}');
+ return sb.toString();
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+
+ /**
+ * Make a prettyprinted JSON text of this JSONObject.
+ * <p>
+ * Warning: This method assumes that the data structure is acyclical.
+ * @param indentFactor The number of spaces to add to each level of
+ * indentation.
+ * @return a printable, displayable, portable, transmittable
+ * representation of the object, beginning
+ * with <code>{</code> <small>(left brace)</small>
and ending
+ * with <code>}</code> <small>(right
brace)</small>.
+ * @throws JSONException If the object contains an invalid number.
+ */
+ public String toString(int indentFactor) throws JSONException {
+ return toString(indentFactor, 0);
+ }
+
+
+ /**
+ * Make a prettyprinted JSON text of this JSONObject.
+ * <p>
+ * Warning: This method assumes that the data structure is acyclical.
+ * @param indentFactor The number of spaces to add to each level of
+ * indentation.
+ * @param indent The indentation of the top level.
+ * @return a printable, displayable, transmittable
+ * representation of the object, beginning
+ * with <code>{</code> <small>(left brace)</small>
and ending
+ * with <code>}</code> <small>(right
brace)</small>.
+ * @throws JSONException If the object contains an invalid number.
+ */
+ String toString(int indentFactor, int indent) throws JSONException {
+ int j;
+ int n = length();
+ if (n == 0) {
+ return "{}";
+ }
+ Iterator keys = sortedKeys();
+ StringBuffer sb = new StringBuffer("{");
+ int newindent = indent + indentFactor;
+ Object o;
+ if (n == 1) {
+ o = keys.next();
+ sb.append(quote(o.toString()));
+ sb.append(": ");
+ sb.append(valueToString(this.map.get(o), indentFactor,
+ indent));
+ } else {
+ while (keys.hasNext()) {
+ o = keys.next();
+ if (sb.length() > 1) {
+ sb.append(",\n");
+ } else {
+ sb.append('\n');
+ }
+ for (j = 0; j < newindent; j += 1) {
+ sb.append(' ');
+ }
+ sb.append(quote(o.toString()));
+ sb.append(": ");
+ sb.append(valueToString(this.map.get(o), indentFactor,
+ newindent));
+ }
+ if (sb.length() > 1) {
+ sb.append('\n');
+ for (j = 0; j < indent; j += 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
+ * the JSON text. The method is required to produce a strictly
+ * conforming text. If the object does not contain a toJSONString
+ * method (which is the most common case), then a text will be
+ * produced by other means. If the value is an array or Collection,
+ * then a JSONArray will be made from it and its toJSONString method
+ * will be called. If the value is a MAP, then a JSONObject will be made
+ * from it and its toJSONString method will be called. Otherwise, the
+ * value's toString method will be called, and the result will be quoted.
+ *
+ * <p>
+ * Warning: This method assumes that the data structure is acyclical.
+ * @param value The value to be serialized.
+ * @return a printable, displayable, transmittable
+ * representation of the object, beginning
+ * with <code>{</code> <small>(left brace)</small>
and ending
+ * with <code>}</code> <small>(right
brace)</small>.
+ * @throws JSONException If the value is or contains an invalid number.
+ */
+ static String valueToString(Object value) throws JSONException {
+ if (value == null || value.equals(null)) {
+ return "null";
+ }
+ if (value instanceof JSONString) {
+ Object o;
+ try {
+ o = ((JSONString)value).toJSONString();
+ } catch (Exception e) {
+ throw new JSONException(e);
+ }
+ if (o instanceof String) {
+ 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) {
+ return value.toString();
+ }
+ if (value instanceof Map) {
+ return new JSONObject((Map)value).toString();
+ }
+ if (value instanceof Collection) {
+ return new JSONArray((Collection)value).toString();
+ }
+ if (value.getClass().isArray()) {
+ return new JSONArray(value).toString();
+ }
+ return quote(value.toString());
+ }
+
+
+ /**
+ * Make a prettyprinted JSON text of an object value.
+ * <p>
+ * Warning: This method assumes that the data structure is acyclical.
+ * @param value The value to be serialized.
+ * @param indentFactor The number of spaces to add to each level of
+ * indentation.
+ * @param indent The indentation of the top level.
+ * @return a printable, displayable, transmittable
+ * representation of the object, beginning
+ * with <code>{</code> <small>(left brace)</small>
and ending
+ * 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)) {
+ return "null";
+ }
+ try {
+ if (value instanceof JSONString) {
+ Object o = ((JSONString)value).toJSONString();
+ if (o instanceof String) {
+ return (String)o;
+ }
+ }
+ } catch (Exception e) {
+ /* 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);
+ }
+ if (value instanceof JSONArray) {
+ return ((JSONArray)value).toString(indentFactor, indent);
+ }
+ if (value instanceof Map) {
+ return new JSONObject((Map)value).toString(indentFactor, indent);
+ }
+ if (value instanceof Collection) {
+ return new JSONArray((Collection)value).toString(indentFactor, indent);
+ }
+ if (value.getClass().isArray()) {
+ return new 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 {
+ try {
+ 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.map.get(k);
+ if (v instanceof JSONObject) {
+ ((JSONObject)v).write(writer);
+ } else if (v instanceof JSONArray) {
+ ((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
Added: trunk/java/org/apache/tomcat/util/json/JSONString.java
===================================================================
--- trunk/java/org/apache/tomcat/util/json/JSONString.java (rev
0)
+++ trunk/java/org/apache/tomcat/util/json/JSONString.java 2008-09-19 01:53:57 UTC (rev
784)
@@ -0,0 +1,18 @@
+package org.apache.tomcat.util.json;
+/**
+ * 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
+ * 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();
+}
Added: trunk/java/org/apache/tomcat/util/json/JSONStringer.java
===================================================================
--- trunk/java/org/apache/tomcat/util/json/JSONStringer.java (rev
0)
+++ trunk/java/org/apache/tomcat/util/json/JSONStringer.java 2008-09-19 01:53:57 UTC (rev
784)
@@ -0,0 +1,78 @@
+package org.apache.tomcat.util.json;
+
+/*
+Copyright (c) 2006
JSON.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+The Software shall be used for Good, not Evil.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+*/
+
+import java.io.StringWriter;
+
+/**
+ * JSONStringer provides a quick and convenient way of producing JSON text.
+ * The texts produced strictly conform to JSON syntax rules. No whitespace is
+ * added, so the results are ready for transmission or storage. Each instance of
+ * JSONStringer can produce one JSON text.
+ * <p>
+ * A JSONStringer instance provides a <code>value</code> method for
appending
+ * values to the
+ * text, and a <code>key</code>
+ * method for adding keys before values in objects. There are
<code>array</code>
+ * and <code>endArray</code> methods that make and bound array values, and
+ * <code>object</code> and <code>endObject</code> methods which
make and bound
+ * object values. All of these methods return the JSONWriter instance,
+ * permitting cascade style. For example, <pre>
+ * myString = new JSONStringer()
+ * .object()
+ * .key("JSON")
+ * .value("Hello, World!")
+ * .endObject()
+ * .toString();</pre> which produces the string <pre>
+ * {"JSON":"Hello, World!"}</pre>
+ * <p>
+ * The first method called must be <code>array</code> or
<code>object</code>.
+ * There are no methods for adding commas or colons. JSONStringer adds them for
+ * you. Objects and arrays can be nested up to 20 levels deep.
+ * <p>
+ * This can sometimes be easier than using a JSONObject to build a string.
+ * @author
JSON.org
+ * @version 2008-09-18
+ */
+public class JSONStringer extends JSONWriter {
+ /**
+ * Make a fresh JSONStringer. It can be used to build one JSON text.
+ */
+ public JSONStringer() {
+ super(new StringWriter());
+ }
+
+ /**
+ * Return the JSON text. This method is used to obtain the product of the
+ * JSONStringer instance. It will return <code>null</code> if there was
a
+ * problem in the construction of the JSON text (such as the calls to
+ * <code>array</code> were not properly balanced with calls to
+ * <code>endArray</code>).
+ * @return The JSON text.
+ */
+ public String toString() {
+ return this.mode == 'd' ? this.writer.toString() : null;
+ }
+}
Added: trunk/java/org/apache/tomcat/util/json/JSONTokener.java
===================================================================
--- trunk/java/org/apache/tomcat/util/json/JSONTokener.java (rev
0)
+++ trunk/java/org/apache/tomcat/util/json/JSONTokener.java 2008-09-19 01:53:57 UTC (rev
784)
@@ -0,0 +1,422 @@
+package org.apache.tomcat.util.json;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+
+/*
+Copyright (c) 2002
JSON.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+The Software shall be used for Good, not Evil.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+*/
+
+/**
+ * A JSONTokener takes a source string and extracts characters and tokens from
+ * it. It is used by the JSONObject and JSONArray constructors to parse
+ * JSON source strings.
+ * @author
JSON.org
+ * @version 2008-09-18
+ */
+public class JSONTokener {
+
+ private int index;
+ private Reader reader;
+ private char lastChar;
+ private boolean useLastChar;
+
+
+ /**
+ * Construct a JSONTokener from a string.
+ *
+ * @param reader A reader.
+ */
+ public JSONTokener(Reader reader) {
+ this.reader = reader.markSupported() ?
+ reader : new BufferedReader(reader);
+ this.useLastChar = false;
+ this.index = 0;
+ }
+
+
+ /**
+ * Construct a JSONTokener from a string.
+ *
+ * @param s A source string.
+ */
+ public JSONTokener(String s) {
+ this(new StringReader(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
+ * the next number or identifier.
+ */
+ public void back() throws JSONException {
+ if (useLastChar || index <= 0) {
+ throw new JSONException("Stepping back two steps is not
supported");
+ }
+ index -= 1;
+ useLastChar = true;
+ }
+
+
+
+ /**
+ * Get the hex value of a character (base16).
+ * @param c A character between '0' and '9' or between 'A'
and 'F' or
+ * between 'a' and 'f'.
+ * @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') {
+ return c - '0';
+ }
+ if (c >= 'A' && c <= 'F') {
+ return c - ('A' - 10);
+ }
+ if (c >= 'a' && c <= 'f') {
+ return c - ('a' - 10);
+ }
+ return -1;
+ }
+
+
+ /**
+ * Determine if the source string still contains characters that next()
+ * can consume.
+ * @return true if not yet at the end of the source.
+ */
+ public boolean more() throws JSONException {
+ char nextChar = next();
+ if (nextChar == 0) {
+ return false;
+ }
+ back();
+ return true;
+ }
+
+
+ /**
+ * Get the next character in the source string.
+ *
+ * @return The next character, or 0 if past the end of the source string.
+ */
+ public char next() throws JSONException {
+ if (this.useLastChar) {
+ this.useLastChar = false;
+ if (this.lastChar != 0) {
+ this.index += 1;
+ }
+ return this.lastChar;
+ }
+ int c;
+ try {
+ c = this.reader.read();
+ } catch (IOException exc) {
+ throw new JSONException(exc);
+ }
+
+ if (c <= 0) { // End of stream
+ this.lastChar = 0;
+ return 0;
+ }
+ this.index += 1;
+ this.lastChar = (char) c;
+ return this.lastChar;
+ }
+
+
+ /**
+ * Consume the next character, and check that it matches a specified
+ * character.
+ * @param c The character to match.
+ * @return The character.
+ * @throws JSONException if the character does not match.
+ */
+ public char next(char c) throws JSONException {
+ char n = next();
+ if (n != c) {
+ throw syntaxError("Expected '" + c + "' and instead
saw '" +
+ n + "'");
+ }
+ return n;
+ }
+
+
+ /**
+ * Get the next n characters.
+ *
+ * @param n The number of characters to take.
+ * @return A string of n characters.
+ * @throws JSONException
+ * Substring bounds error if there are not
+ * n characters remaining in the source string.
+ */
+ public String next(int n) throws JSONException {
+ if (n == 0) {
+ return "";
+ }
+
+ char[] buffer = new char[n];
+ int pos = 0;
+
+ if (this.useLastChar) {
+ this.useLastChar = false;
+ buffer[0] = this.lastChar;
+ pos = 1;
+ }
+
+ try {
+ int len;
+ while ((pos < n) && ((len = reader.read(buffer, pos, n - pos)) !=
-1)) {
+ pos += len;
+ }
+ } catch (IOException exc) {
+ throw new JSONException(exc);
+ }
+ this.index += pos;
+
+ if (pos < n) {
+ throw syntaxError("Substring bounds error");
+ }
+
+ this.lastChar = buffer[n - 1];
+ return new String(buffer);
+ }
+
+
+ /**
+ * Get the next char in the string, skipping whitespace.
+ * @throws JSONException
+ * @return A character, or 0 if there are no more characters.
+ */
+ public char nextClean() throws JSONException {
+ for (;;) {
+ char c = next();
+ 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
+ * allow strings in single quotes, but an implementation is allowed to
+ * accept them.
+ * @param quote The quoting character, either
+ * <code>"</code> <small>(double
quote)</small> or
+ * <code>'</code> <small>(single
quote)</small>.
+ * @return A String.
+ * @throws JSONException Unterminated string.
+ */
+ 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');
+ 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;
+ 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.
+ * @param d A delimiter character.
+ * @return A string.
+ */
+ public String nextTo(char d) throws JSONException {
+ StringBuffer sb = new StringBuffer();
+ for (;;) {
+ char c = next();
+ 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 delimiter
+ * characters or the end of line, whichever comes first.
+ * @param delimiters A set of delimiter characters.
+ * @return A string, trimmed.
+ */
+ public String nextTo(String delimiters) throws JSONException {
+ char c;
+ StringBuffer sb = new StringBuffer();
+ for (;;) {
+ c = next();
+ 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.
+ * @throws JSONException If syntax error.
+ *
+ * @return An object.
+ */
+ public Object nextValue() throws JSONException {
+ char c = nextClean();
+ String s;
+
+ switch (c) {
+ case '"':
+ case '\'':
+ return nextString(c);
+ case '{':
+ back();
+ return new JSONObject(this);
+ case '[':
+ case '(':
+ back();
+ return new JSONArray(this);
+ }
+
+ /*
+ * Handle unquoted text. This could be the values true, false, or
+ * null, or it can be a number. An implementation (such as this one)
+ * is allowed to also accept non-standard forms.
+ *
+ * Accumulate characters until we reach the end of the text or a
+ * formatting character.
+ */
+
+ StringBuffer sb = new StringBuffer();
+ while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c)
< 0) {
+ sb.append(c);
+ c = next();
+ }
+ back();
+
+ s = sb.toString().trim();
+ if (s.equals("")) {
+ throw syntaxError("Missing value");
+ }
+ return JSONObject.stringToValue(s);
+ }
+
+
+ /**
+ * Skip characters until the next character is the requested character.
+ * If the requested character is not found, no characters are skipped.
+ * @param to A character to skip to.
+ * @return The requested character, or zero if the requested character
+ * is not found.
+ */
+ public char skipTo(char to) throws JSONException {
+ char c;
+ try {
+ int startIndex = this.index;
+ reader.mark(Integer.MAX_VALUE);
+ do {
+ c = next();
+ if (c == 0) {
+ reader.reset();
+ this.index = startIndex;
+ return c;
+ }
+ } while (c != to);
+ } catch (IOException exc) {
+ throw new JSONException(exc);
+ }
+
+ back();
+ return c;
+ }
+
+ /**
+ * Make a JSONException to signal a syntax error.
+ *
+ * @param message The error message.
+ * @return A JSONException object, suitable for throwing
+ */
+ public JSONException syntaxError(String message) {
+ return new JSONException(message + toString());
+ }
+
+
+ /**
+ * Make a printable string of this JSONTokener.
+ *
+ * @return " at character [this.index]"
+ */
+ public String toString() {
+ return " at character " + index;
+ }
+}
\ No newline at end of file
Added: trunk/java/org/apache/tomcat/util/json/JSONWriter.java
===================================================================
--- trunk/java/org/apache/tomcat/util/json/JSONWriter.java (rev
0)
+++ trunk/java/org/apache/tomcat/util/json/JSONWriter.java 2008-09-19 01:53:57 UTC (rev
784)
@@ -0,0 +1,323 @@
+package org.apache.tomcat.util.json;
+
+import java.io.IOException;
+import java.io.Writer;
+
+/*
+Copyright (c) 2006
JSON.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+The Software shall be used for Good, not Evil.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+*/
+
+/**
+ * JSONWriter provides a quick and convenient way of producing JSON text.
+ * The texts produced strictly conform to JSON syntax rules. No whitespace is
+ * added, so the results are ready for transmission or storage. Each instance of
+ * JSONWriter can produce one JSON text.
+ * <p>
+ * A JSONWriter instance provides a <code>value</code> method for appending
+ * values to the
+ * text, and a <code>key</code>
+ * method for adding keys before values in objects. There are
<code>array</code>
+ * and <code>endArray</code> methods that make and bound array values, and
+ * <code>object</code> and <code>endObject</code> methods which
make and bound
+ * object values. All of these methods return the JSONWriter instance,
+ * permitting a cascade style. For example, <pre>
+ * new JSONWriter(myWriter)
+ * .object()
+ * .key("JSON")
+ * .value("Hello, World!")
+ * .endObject();</pre> which writes <pre>
+ * {"JSON":"Hello, World!"}</pre>
+ * <p>
+ * The first method called must be <code>array</code> or
<code>object</code>.
+ * There are no methods for adding commas or colons. JSONWriter adds them for
+ * you. Objects and arrays can be nested up to 20 levels deep.
+ * <p>
+ * This can sometimes be easier than using a JSONObject to build a string.
+ * @author
JSON.org
+ * @version 2008-09-18
+ */
+public class JSONWriter {
+ private static final int maxdepth = 20;
+
+ /**
+ * The comma flag determines if a comma should be output before the next
+ * value.
+ */
+ private boolean comma;
+
+ /**
+ * The current mode. Values:
+ * 'a' (array),
+ * 'd' (done),
+ * 'i' (initial),
+ * 'k' (key),
+ * 'o' (object).
+ */
+ protected char mode;
+
+ /**
+ * The object/array stack.
+ */
+ private JSONObject stack[];
+
+ /**
+ * The stack top index. A value of 0 indicates that the stack is empty.
+ */
+ private int top;
+
+ /**
+ * The writer that will receive the output.
+ */
+ protected Writer writer;
+
+ /**
+ * Make a fresh JSONWriter. It can be used to build one JSON text.
+ */
+ public JSONWriter(Writer w) {
+ this.comma = false;
+ this.mode = 'i';
+ this.stack = new JSONObject[maxdepth];
+ this.top = 0;
+ this.writer = w;
+ }
+
+ /**
+ * Append a value.
+ * @param s A string value.
+ * @return this
+ * @throws JSONException If the value is out of sequence.
+ */
+ private JSONWriter append(String s) throws JSONException {
+ if (s == null) {
+ throw new JSONException("Null pointer");
+ }
+ if (this.mode == 'o' || this.mode == 'a') {
+ try {
+ 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.");
+ }
+
+ /**
+ * Begin appending a new array. All values until the balancing
+ * <code>endArray</code> will be appended to this array. The
+ * <code>endArray</code> method must be called to mark the array's
end.
+ * @return this
+ * @throws JSONException If the nesting is too deep, or if the object is
+ * started in the wrong place (for example as a key or after the end of the
+ * outermost array or object).
+ */
+ public JSONWriter array() throws JSONException {
+ if (this.mode == 'i' || this.mode == 'o' || this.mode ==
'a') {
+ this.push(null);
+ this.append("[");
+ this.comma = false;
+ return this;
+ }
+ throw new JSONException("Misplaced array.");
+ }
+
+ /**
+ * End something.
+ * @param m Mode
+ * @param c Closing character
+ * @return this
+ * @throws JSONException If unbalanced.
+ */
+ private JSONWriter end(char m, char c) throws JSONException {
+ if (this.mode != m) {
+ 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;
+ }
+
+ /**
+ * End an array. This method most be called to balance calls to
+ * <code>array</code>.
+ * @return this
+ * @throws JSONException If incorrectly nested.
+ */
+ public JSONWriter endArray() throws JSONException {
+ return this.end('a', ']');
+ }
+
+ /**
+ * End an object. This method most be called to balance calls to
+ * <code>object</code>.
+ * @return this
+ * @throws JSONException If incorrectly nested.
+ */
+ public JSONWriter endObject() throws JSONException {
+ return this.end('k', '}');
+ }
+
+ /**
+ * Append a key. The key will be associated with the next value. In an
+ * object, every value must be preceded by a key.
+ * @param s A key string.
+ * @return this
+ * @throws JSONException If the key is out of place. For example, keys
+ * do not belong in arrays or if the key is null.
+ */
+ public JSONWriter key(String s) throws JSONException {
+ if (s == null) {
+ throw new JSONException("Null key.");
+ }
+ if (this.mode == 'k') {
+ try {
+ if (this.comma) {
+ this.writer.write(',');
+ }
+ stack[top - 1].putOnce(s, Boolean.TRUE);
+ 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
+ * <code>endObject</code> method must be called to mark the object's
end.
+ * @return this
+ * @throws JSONException If the nesting is too deep, or if the object is
+ * started in the wrong place (for example as a key or after the end of the
+ * outermost array or object).
+ */
+ public JSONWriter object() throws JSONException {
+ if (this.mode == 'i') {
+ this.mode = 'o';
+ }
+ if (this.mode == 'o' || this.mode == 'a') {
+ this.append("{");
+ this.push(new JSONObject());
+ 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) {
+ throw new JSONException("Nesting error.");
+ }
+ char m = this.stack[this.top - 1] == null ? 'a' : 'k';
+ if (m != c) {
+ throw new JSONException("Nesting error.");
+ }
+ this.top -= 1;
+ this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ?
'a' : 'k';
+ }
+
+ /**
+ * Push an array or object scope.
+ * @param c The scope to open.
+ * @throws JSONException If nesting is too deep.
+ */
+ private void push(JSONObject jo) throws JSONException {
+ if (this.top >= maxdepth) {
+ throw new JSONException("Nesting too deep.");
+ }
+ this.stack[this.top] = jo;
+ this.mode = jo == null ? 'a' : 'k';
+ this.top += 1;
+ }
+
+
+ /**
+ * Append either the value <code>true</code> or the value
+ * <code>false</code>.
+ * @param b A boolean.
+ * @return this
+ * @throws JSONException
+ */
+ public JSONWriter value(boolean b) throws JSONException {
+ return this.append(b ? "true" : "false");
+ }
+
+ /**
+ * Append a double value.
+ * @param d A double.
+ * @return this
+ * @throws JSONException If the number is not finite.
+ */
+ public JSONWriter value(double d) throws JSONException {
+ return this.value(new Double(d));
+ }
+
+ /**
+ * Append a long value.
+ * @param l A long.
+ * @return this
+ * @throws JSONException
+ */
+ public JSONWriter value(long l) throws JSONException {
+ return this.append(Long.toString(l));
+ }
+
+
+ /**
+ * Append an object value.
+ * @param o The object to append. It can be null, or a Boolean, Number,
+ * String, JSONObject, or JSONArray, or an object with a toJSONString()
+ * method.
+ * @return this
+ * @throws JSONException If the value is out of sequence.
+ */
+ public JSONWriter value(Object o) throws JSONException {
+ return this.append(JSONObject.valueToString(o));
+ }
+}
Modified: trunk/webapps/docs/changelog.xml
===================================================================
--- trunk/webapps/docs/changelog.xml 2008-09-18 15:57:52 UTC (rev 783)
+++ trunk/webapps/docs/changelog.xml 2008-09-19 01:53:57 UTC (rev 784)
@@ -31,10 +31,16 @@
<fix>
<bug>45419</bug>: Set Accept-Ranges for static resources served by
DefaultServlet. (markt)
</fix>
+ <add>
+ Bayeux support using a BayeuxServlet written as an event driven servlet. (remm,
fhanik)
+ </add>
</changelog>
</subsection>
<subsection name="Coyote">
<changelog>
+ <add>
+ Package renamed JSON library. (remm)
+ </add>
</changelog>
</subsection>
<subsection name="Jasper">