You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@shindig.apache.org by jo...@apache.org on 2008/01/03 02:20:37 UTC
svn commit: r608302 [2/3] - in /incubator/shindig/trunk: java/gadgets/
java/gadgets/src/main/java/org/apache/shindig/gadgets/
java/gadgets/src/main/java/org/apache/shindig/gadgets/http/
java/gadgets/src/main/java/org/apache/shindig/util/ java/gadgets/s...
Added: incubator/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/util/Check.java
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/util/Check.java?rev=608302&view=auto
==============================================================================
--- incubator/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/util/Check.java (added)
+++ incubator/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/util/Check.java Wed Jan 2 17:20:35 2008
@@ -0,0 +1,482 @@
+/*
+ * Licensed 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.shindig.util;
+
+import org.hamcrest.Description;
+import org.hamcrest.Matcher;
+import static org.hamcrest.Matchers.equalTo;
+import org.hamcrest.StringDescription;
+
+import java.util.Collection;
+import java.util.Map;
+
+/**
+ * Provides methods for checking conditions and arguments, throwing an
+ * appropriate {@code RuntimeException} when the checks fail.
+ * The main goal of this class is to ensure that appropriate exception types
+ * with clear messages are thrown while minimizing code duplication.
+ *
+ * <p>Use this class instead of {@code assert} when you want to enforce that
+ * the check is always performed. These are designed for testing arguments
+ * and preconditions that make up a method's contract.
+ *
+ * <p>Example:
+ *
+ * <pre class="code">public void setContentData(String contentData) {
+ * Check.eq(contentType, ContentType.HTML,
+ * "getContentData() only valid for HTML gadgets");
+ * Check.notNull(contentData);
+ * this.contentData = contentData;
+ *}</pre>
+ *
+ * <p>A generic check that can use any {@link org.hamcrest.Matcher} is provided
+ * a la JUnit. Various matchers can be created using static methods from
+ * {@link org.hamcrest.Matchers}.
+ *
+ * <pre class="code">Check.that(string, containsString("foo"));
+ *Check.that(string, anyOf(startsWith("foo"), endsWith("bar")));</pre>
+ */
+public final class Check {
+ /**
+ * Checks that {@code condition} is {@code true}.
+ *
+ * @throws IllegalStateException if the check fails.
+ */
+ public static void is(boolean condition, String message) {
+ if (!condition) {
+ throw new IllegalStateException(message);
+ }
+ }
+
+ /**
+ * Checks that {@code condition} is {@code true}.
+ *
+ * @throws IllegalStateException if the check fails.
+ */
+ public static void is(boolean condition, String message, Object... args) {
+ if (!condition) {
+ throw new IllegalStateException(String.format(message, args));
+ }
+ }
+
+ /**
+ * Checks that {@code first} equals {@code second} using
+ * {@link org.hamcrest.Matchers#equalTo}.
+ *
+ * @throws IllegalStateException if the check fails.
+ */
+ public static void eq(Object first, Object second, String message) {
+ that(first, equalTo(second), message);
+ }
+
+ /**
+ * Checks that {@code first} equals {@code second} using
+ * {@link org.hamcrest.Matchers#equalTo}.
+ *
+ * @throws IllegalStateException if the check fails.
+ */
+ public static void eq(Object first, Object second, String message,
+ Object... args) {
+ that(first, equalTo(second), String.format(message, args));
+ }
+
+ /**
+ * Checks that {@code actual} matches {@code matcher} from Hamcrest.
+ *
+ * @throws IllegalStateException if the check fails.
+ */
+ public static <T> void that(T actual, Matcher<T> matcher) {
+ that(actual, matcher, "");
+ }
+
+ /**
+ * Checks that {@code actual} matches {@code matcher} from Hamcrest.
+ *
+ * @throws IllegalStateException if the check fails.
+ */
+ public static <T> void that(T actual, Matcher<T> matcher, String message) {
+ if (!matcher.matches(actual)) {
+ Description description = new StringDescription();
+ if (message != null && message.length() > 0) {
+ description.appendText(message).appendText(" - ");
+ }
+ description.appendValue(actual).appendText(" must be ");
+ matcher.describeTo(description);
+ throw new IllegalStateException(matcher.toString());
+ }
+ }
+
+ /**
+ * Checks that {@code actual} matches {@code matcher} from Hamcrest.
+ *
+ * @throws IllegalStateException if the check fails.
+ */
+ public static <T> void that(T actual, Matcher<T> matcher, String message,
+ Object... args) {
+ that(actual, matcher, String.format(message, args));
+ }
+
+ /**
+ * Checks that {@code ref} is not {@code null}.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static void notNull(Object ref) {
+ if (ref == null) {
+ throw new IllegalArgumentException("Object must be non-null");
+ }
+ }
+
+ /**
+ * Checks that {@code ref} is not {@code null}.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static void notNull(Object ref, String message) {
+ if (ref == null) {
+ throw new IllegalArgumentException(message);
+ }
+ }
+
+ /**
+ * Checks that {@code ref} is not {@code null}.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static void notNull(Object ref, String message, Object... args) {
+ if (ref == null) {
+ throw new IllegalArgumentException(String.format(message, args));
+ }
+ }
+
+ /**
+ * Checks that {@code ref} is a (or a subclass of) {@code clazz}.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static void isA(Object ref, Class<?> clazz) {
+ if (ref != null && !(clazz.isAssignableFrom(ref.getClass()))) {
+ throw new IllegalArgumentException(
+ String.format("Object must be an instance of %s", clazz));
+ }
+ }
+
+ /**
+ * Checks that {@code ref} is a (or a subclass of) {@code clazz}.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static void isA(Object ref, Class<?> clazz, String message) {
+ if (ref != null && !(clazz.isAssignableFrom(ref.getClass()))) {
+ throw new IllegalArgumentException(message);
+ }
+ }
+
+ /**
+ * Checks that {@code ref} is a (or a subclass of) {@code clazz}.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static void isA(Object ref, Class<?> clazz, String message,
+ Object... args) {
+ if (ref != null && !(clazz.isAssignableFrom(ref.getClass()))) {
+ throw new IllegalArgumentException(String.format(message, args));
+ }
+ }
+
+ /**
+ * Checks that {@code string} is not {@code null} and not empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static void notEmpty(String string) {
+ if (string == null || string.length() == 0) {
+ throw new IllegalArgumentException("String must be non-empty");
+ }
+ }
+
+ /**
+ * Checks that {@code string} is not {@code null} and not empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static void notEmpty(String string, String message) {
+ if (string == null || string.length() == 0) {
+ throw new IllegalArgumentException(message);
+ }
+ }
+
+ /**
+ * Checks that {@code string} is not {@code null} and not empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static void notEmpty(String string, String message, Object... args) {
+ if (string == null || string.length() == 0) {
+ throw new IllegalArgumentException(String.format(message, args));
+ }
+ }
+
+ /**
+ * Checks that {@code array} is not {@code null} and not empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static void notEmpty(Object[] array) {
+ if (array == null || array.length == 0) {
+ throw new IllegalArgumentException("Array must be non-empty");
+ }
+ }
+
+ /**
+ * Checks that {@code array} is not {@code null} and not empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static void notEmpty(Object[] array, String message) {
+ if (array == null || array.length == 0) {
+ throw new IllegalArgumentException(message);
+ }
+ }
+
+ /**
+ * Checks that {@code array} is not {@code null} and not empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static void notEmpty(Object[] array, String message, Object... args) {
+ if (array == null || array.length == 0) {
+ throw new IllegalArgumentException(String.format(message, args));
+ }
+ }
+
+ /**
+ * Checks that {@code collection} is not {@code null} and not empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ * or empty.
+ */
+ public static void notEmpty(Collection<?> collection) {
+ if (collection == null || collection.isEmpty()) {
+ throw new IllegalArgumentException("Collection must be non-empty");
+ }
+ }
+
+ /**
+ * Checks that {@code collection} is not {@code null} and not empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ * or empty.
+ */
+ public static void notEmpty(Collection<?> collection, String message) {
+ if (collection == null || collection.isEmpty()) {
+ throw new IllegalArgumentException(message);
+ }
+ }
+
+ /**
+ * Checks that {@code collection} is not {@code null} and not empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ * or empty.
+ */
+ public static void notEmpty(Collection<?> collection, String message,
+ Object... args) {
+ if (collection == null || collection.isEmpty()) {
+ throw new IllegalArgumentException(String.format(message, args));
+ }
+ }
+
+ /**
+ * Checks that {@code map} is not {@code null} and not empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static void notEmpty(Map<?, ?> map) {
+ if (map == null || map.isEmpty()) {
+ throw new IllegalArgumentException("Map must be non-empty");
+ }
+ }
+
+ /**
+ * Checks that {@code map} is not {@code null} and not empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static void notEmpty(Map<?, ?> map, String message) {
+ if (map == null || map.isEmpty()) {
+ throw new IllegalArgumentException(message);
+ }
+ }
+
+ /**
+ * Checks that {@code map} is not {@code null} and not empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static void notEmpty(Map<?, ?> map, String message, Object... args) {
+ if (map == null || map.isEmpty()) {
+ throw new IllegalArgumentException(String.format(message, args));
+ }
+ }
+
+ /**
+ * Checks that {@code array} contains no {@code null} elements.
+ * It is not an error for the argument itself to be {@code null} or empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static void noNulls(Object[] array) {
+ if (array != null && array.length > 0) {
+ for (Object element : array) {
+ if (element == null) {
+ throw new IllegalArgumentException(
+ "Array must contain only non-null elements");
+ }
+ }
+ }
+ }
+
+ /**
+ * Checks that {@code array} contains no {@code null} elements.
+ * It is not an error for the argument itself to be {@code null} or empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static void noNulls(Object[] array, String message) {
+ if (array != null && array.length > 0) {
+ for (Object element : array) {
+ if (element == null) {
+ throw new IllegalArgumentException(message);
+ }
+ }
+ }
+ }
+
+ /**
+ * Checks that {@code array} contains no {@code null} elements.
+ * It is not an error for the argument itself to be {@code null} or empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static void noNulls(Object[] array, String message, Object... args) {
+ if (array != null && array.length > 0) {
+ for (Object element : array) {
+ if (element == null) {
+ throw new IllegalArgumentException(String.format(message, args));
+ }
+ }
+ }
+ }
+
+ /**
+ * Checks that {@code iterable} contains no {@code null} elements.
+ * It is not an error for {@code iterable} itself to be {@code null} or empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static <E> void noNulls(Iterable<E> iterable) {
+ if (iterable != null) {
+ for (E element : iterable) {
+ if (element == null) {
+ throw new IllegalArgumentException(
+ "Iterable must contain only non-null elements");
+ }
+ }
+ }
+ }
+
+ /**
+ * Checks that {@code iterable} contains no {@code null} elements.
+ * It is not an error for {@code iterable} itself to be {@code null} or empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static <E> void noNulls(Iterable<E> iterable, String message) {
+ if (iterable != null) {
+ for (E element : iterable) {
+ if (element == null) {
+ throw new IllegalArgumentException(message);
+ }
+ }
+ }
+ }
+
+ /**
+ * Checks that {@code iterable} contains no {@code null} elements.
+ * It is not an error for {@code iterable} itself to be {@code null} or empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static <E> void noNulls(Iterable<E> iterable, String message,
+ Object... args) {
+ if (iterable != null) {
+ for (E element : iterable) {
+ if (element == null) {
+ throw new IllegalArgumentException(String.format(message, args));
+ }
+ }
+ }
+ }
+
+ /**
+ * Checks that {@code map} contains no {@code null} keys or values.
+ * It is not an error for {@code map} itself to be {@code null} or empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static <K, V> void noNulls(Map<K, V> map) {
+ if (map != null) {
+ for (Map.Entry<K, V> entry : map.entrySet()) {
+ if (entry.getKey() == null || entry.getValue() == null) {
+ throw new IllegalArgumentException(
+ "Map must contain only non-null keys and values");
+ }
+ }
+ }
+ }
+
+ /**
+ * Checks that {@code map} contains no {@code null} elements.
+ * It is not an error for {@code map} itself to be {@code null} or empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static <K, V> void noNulls(Map<K, V> map, String message) {
+ if (map != null) {
+ for (Map.Entry<K, V> entry : map.entrySet()) {
+ if (entry.getKey() == null || entry.getValue() == null) {
+ throw new IllegalArgumentException(message);
+ }
+ }
+ }
+ }
+
+ /**
+ * Checks that {@code map} contains no {@code null} elements.
+ * It is not an error for {@code map} itself to be {@code null} or empty.
+ *
+ * @throws IllegalArgumentException if the check fails.
+ */
+ public static <K, V> void noNulls(Map<K, V> map, String message,
+ Object... args) {
+ if (map != null) {
+ for (Map.Entry<K, V> entry : map.entrySet()) {
+ if (entry.getKey() == null || entry.getValue() == null) {
+ throw new IllegalArgumentException(String.format(message, args));
+ }
+ }
+ }
+ }
+}
Modified: incubator/shindig/trunk/java/gadgets/src/main/webapp/WEB-INF/web.xml
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/java/gadgets/src/main/webapp/WEB-INF/web.xml?rev=608302&r1=608301&r2=608302&view=diff
==============================================================================
--- incubator/shindig/trunk/java/gadgets/src/main/webapp/WEB-INF/web.xml (original)
+++ incubator/shindig/trunk/java/gadgets/src/main/webapp/WEB-INF/web.xml Wed Jan 2 17:20:35 2008
@@ -25,7 +25,7 @@
<servlet>
<servlet-name>xml-to-html</servlet-name>
<servlet-class>
- org.apache.shindig.gadgets.http.BasicGadgetHttpServlet
+ org.apache.shindig.gadgets.http.GadgetRenderingServlet
</servlet-class>
</servlet>
@@ -42,11 +42,6 @@
org.apache.shindig.gadgets.http.ProxyServlet
</servlet-class>
</servlet>
-
- <servlet-mapping>
- <servlet-name>proxy</servlet-name>
- <url-pattern>/jsonp</url-pattern>
- </servlet-mapping>
<servlet-mapping>
<servlet-name>proxy</servlet-name>
Modified: incubator/shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/GadgetServerTest.java
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/GadgetServerTest.java?rev=608302&r1=608301&r2=608302&view=diff
==============================================================================
--- incubator/shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/GadgetServerTest.java (original)
+++ incubator/shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/GadgetServerTest.java Wed Jan 2 17:20:35 2008
@@ -19,8 +19,8 @@
import static org.apache.shindig.gadgets.GadgetSpecTestFixture.DATETIME_ID;
import static org.apache.shindig.gadgets.GadgetSpecTestFixture.DATETIME_SPEC;
-import static org.apache.shindig.gadgets.GadgetSpecTestFixture.DATETIME_URL;
-import static org.apache.shindig.gadgets.GadgetSpecTestFixture.DATETIME_URL_STRING;
+import static org.apache.shindig.gadgets.GadgetSpecTestFixture.DATETIME_URI;
+import static org.apache.shindig.gadgets.GadgetSpecTestFixture.DATETIME_URI_STRING;
import static org.apache.shindig.gadgets.GadgetSpecTestFixture.DATETIME_XML;
import static org.apache.shindig.gadgets.GadgetSpecTestFixture.EN_US_LOCALE;
import static org.easymock.EasyMock.eq;
@@ -50,9 +50,9 @@
public void testGadgetSpecNotInCache() throws Exception {
RemoteContent results = new RemoteContent(200, DATETIME_XML.getBytes(), null);
- expect(specCache.get(eq(DATETIME_URL_STRING))).andReturn(null);
- expect(fetcher.fetch(eq(DATETIME_URL))).andReturn(results);
- specCache.put(eq(DATETIME_URL_STRING), isA(GadgetSpec.class));
+ expect(specCache.get(eq(DATETIME_URI_STRING))).andReturn(null);
+ expect(fetcher.fetch(eq(DATETIME_URI.toURL()))).andReturn(results);
+ specCache.put(eq(DATETIME_URI_STRING), isA(GadgetSpec.class));
replay();
Gadget gadget = gadgetServer.processGadget(DATETIME_ID, UserPrefs.EMPTY, EN_US_LOCALE,
@@ -61,7 +61,7 @@
}
public void testGadgetSpecInCache() throws Exception {
- expect(specCache.get(eq(DATETIME_URL_STRING))).andReturn(DATETIME_SPEC);
+ expect(specCache.get(eq(DATETIME_URI_STRING))).andReturn(DATETIME_SPEC);
replay();
Gadget gadget = gadgetServer.processGadget(DATETIME_ID, UserPrefs.EMPTY, EN_US_LOCALE,
@@ -73,9 +73,9 @@
public void testBasicGadget() throws Exception {
RemoteContent results = new RemoteContent(200, DATETIME_XML.getBytes(), null);
- expect(specCache.get(eq(DATETIME_URL_STRING))).andReturn(null);
- expect(fetcher.fetch(eq(DATETIME_URL))).andReturn(results);
- specCache.put(eq(DATETIME_URL_STRING), isA(GadgetSpec.class));
+ expect(specCache.get(eq(DATETIME_URI_STRING))).andReturn(null);
+ expect(fetcher.fetch(eq(DATETIME_URI.toURL()))).andReturn(results);
+ specCache.put(eq(DATETIME_URI_STRING), isA(GadgetSpec.class));
replay();
Gadget gadget = gadgetServer.processGadget(DATETIME_ID, UserPrefs.EMPTY, EN_US_LOCALE,
Modified: incubator/shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/GadgetSpecTestFixture.java
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/GadgetSpecTestFixture.java?rev=608302&r1=608301&r2=608302&view=diff
==============================================================================
--- incubator/shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/GadgetSpecTestFixture.java (original)
+++ incubator/shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/GadgetSpecTestFixture.java Wed Jan 2 17:20:35 2008
@@ -17,8 +17,8 @@
*/
package org.apache.shindig.gadgets;
-import java.net.MalformedURLException;
-import java.net.URL;
+import java.net.URI;
+import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
@@ -34,8 +34,8 @@
private static final String DATETIME_TITLE = "Hello, World!";
private static final String DATETIME_CONTENT = "Goodbye, World!";
- static final String DATETIME_URL_STRING = "http://www.google.com/ig/modules/datetime.xml";
- static final URL DATETIME_URL;
+ static final String DATETIME_URI_STRING = "http://www.google.com/ig/modules/datetime.xml";
+ static final URI DATETIME_URI;
static final int DATETIME_MODULE_ID = 1;
static final GadgetView.ID DATETIME_ID;
static final String DATETIME_XML = "<?xml version=\"1.0\"?>" +
@@ -58,7 +58,7 @@
public String getContentData() {
return DATETIME_CONTENT;
}
- public URL getContentHref() {
+ public URI getContentHref() {
return null;
}
public ContentType getContentType() {
@@ -73,8 +73,8 @@
public List<Icon> getIcons() {
return null;
}
- public List<MessageBundle> getMessageBundles() {
- return new LinkedList<MessageBundle>();
+ public List<LocaleSpec> getLocaleSpecs() {
+ return new LinkedList<LocaleSpec>();
}
public List<String> getPreloads() {
return null;
@@ -91,7 +91,7 @@
public String getTitle() {
return DATETIME_TITLE;
}
- public URL getTitleURL() {
+ public URI getTitleURI() {
return null;
}
public List<UserPref> getUserPrefs() {
@@ -101,10 +101,10 @@
static {
try {
- DATETIME_URL = new URL(DATETIME_URL_STRING);
- } catch (MalformedURLException e) {
+ DATETIME_URI = new URI(DATETIME_URI_STRING);
+ } catch (URISyntaxException e) {
throw new RuntimeException("Cannot initialize fixture", e);
}
- DATETIME_ID = new Gadget.GadgetId(DATETIME_URL, DATETIME_MODULE_ID);
+ DATETIME_ID = new Gadget.GadgetId(DATETIME_URI, DATETIME_MODULE_ID);
}
}
Added: incubator/shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/util/CheckTest.java
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/util/CheckTest.java?rev=608302&view=auto
==============================================================================
--- incubator/shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/util/CheckTest.java (added)
+++ incubator/shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/util/CheckTest.java Wed Jan 2 17:20:35 2008
@@ -0,0 +1,634 @@
+/*
+ * Licensed 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.shindig.util;
+
+import junit.framework.JUnit4TestAdapter;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.fail;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class CheckTest {
+ static final String STATIC_MESSAGE = "message";
+
+ static final String MESSAGE_FORMAT = "the %s message";
+ static final int MESSAGE_VALUE = 42;
+ static final String FORMATTED_MESSAGE = "the 42 message";
+
+ static final String ARG_NAME = "arg";
+
+ public static junit.framework.Test suite() {
+ return new JUnit4TestAdapter(CheckTest.class);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void is_Message_ThrowsWhenFalse() {
+ Check.is(false, STATIC_MESSAGE);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void is_MessageArgs_ThrowsWhenFalse() {
+ Check.is(false, MESSAGE_FORMAT, MESSAGE_VALUE);
+ }
+
+ @Test public void is_Message_ReturnsWhenTrue() {
+ try {
+ Check.is(true, STATIC_MESSAGE);
+ } catch (IllegalStateException e) {
+ fail();
+ }
+ }
+
+ @Test public void is_MessageArgs_ReturnsWhenTrue() {
+ try {
+ Check.is(true, MESSAGE_FORMAT, MESSAGE_VALUE);
+ } catch (IllegalStateException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void eq_Message_ThrowsWhenNotEqual() {
+ Check.eq(2, 3, STATIC_MESSAGE);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void eq_MessageArgs_ThrowsWhenNotEqual() {
+ Check.eq("bob", "chuck", MESSAGE_FORMAT, MESSAGE_VALUE);
+ }
+
+ @Test public void eq_Message_ReturnsWhenEqual() {
+ try {
+ Check.eq("frank", "franko".substring(0, 5), STATIC_MESSAGE);
+ } catch (IllegalStateException e) {
+ fail();
+ }
+ }
+
+ @Test public void eq_MessageArgs_ReturnsWhenEqual() {
+ try {
+ Check.eq('c', 'c', MESSAGE_FORMAT, MESSAGE_VALUE);
+ } catch (IllegalStateException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void that_ThrowsWhenFalse() {
+ Check.that("bob", equalTo("frank"));
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void that_Message_ThrowsWhenFalse() {
+ Check.that("bob", equalTo("frank"), STATIC_MESSAGE);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void that_MessageArgs_ThrowsWhenFalse() {
+ Check.that("bob", equalTo("frank"), MESSAGE_FORMAT, MESSAGE_VALUE);
+ }
+
+ @Test public void that_ReturnsWhenTrue() {
+ try {
+ Check.that(23, equalTo(23), STATIC_MESSAGE);
+ } catch (IllegalStateException e) {
+ fail();
+ }
+ }
+
+ @Test public void that_Message_ReturnsWhenTrue() {
+ try {
+ Check.that(23, equalTo(23), STATIC_MESSAGE);
+ } catch (IllegalStateException e) {
+ fail();
+ }
+ }
+
+ @Test public void that_MessageArgs_ReturnsWhenTrue() {
+ try {
+ Check.that(23, equalTo(23), MESSAGE_FORMAT, MESSAGE_VALUE);
+ } catch (IllegalStateException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notNull_ThrowsWhenNotNull() {
+ Check.notNull(null);
+ }
+
+ @Test public void notNull_ReturnsWhenNull() {
+ try {
+ Check.notNull(24);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notNull_Message_ThrowsWhenNotNull() {
+ Check.notNull(null, STATIC_MESSAGE);
+ }
+
+ @Test public void notNull_Message_ReturnsWhenNull() {
+ try {
+ Check.notNull("bob", STATIC_MESSAGE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notNull_MessageArgs_ThrowsWhenNotNull() {
+ Check.notNull(null, MESSAGE_FORMAT, MESSAGE_VALUE);
+ }
+
+ @Test public void notNull_MessageArgs_ReturnsWhenNull() {
+ try {
+ Check.notNull("bob", MESSAGE_FORMAT, MESSAGE_VALUE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyString_ThrowsWhenNull() {
+ String string = null;
+ Check.notEmpty(string);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyString_ThrowsWhenEmpty() {
+ String string = "";
+ Check.notEmpty(string, ARG_NAME);
+ }
+
+ @Test public void notEmptyString_ReturnsWhenNotEmpty() {
+ try {
+ String string = "full";
+ Check.notEmpty(string, ARG_NAME);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyString_Message_ThrowsWhenNull() {
+ String string = null;
+ Check.notEmpty(string, STATIC_MESSAGE);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyString_Message_ThrowsWhenEmpty() {
+ String string = "";
+ Check.notEmpty(string, STATIC_MESSAGE);
+ }
+
+ @Test public void notEmptyString_Message_ReturnsWhenNotEmpty() {
+ try {
+ String string = "full";
+ Check.notEmpty(string, STATIC_MESSAGE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyString_MessageArgs_ThrowsWhenNull() {
+ String string = null;
+ Check.notEmpty(string, MESSAGE_FORMAT, MESSAGE_VALUE);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyString_MessageArgs_ThrowsWhenEmpty() {
+ String string = "";
+ Check.notEmpty(string, MESSAGE_FORMAT, MESSAGE_VALUE);
+ }
+
+ @Test public void notEmptyString_MessageArgs_ReturnsWhenNotEmpty() {
+ try {
+ String string = "full";
+ Check.notEmpty(string, MESSAGE_FORMAT, MESSAGE_VALUE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyObjectArray_ThrowsWhenNull() {
+ Object[] array = null;
+ Check.notEmpty(array);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyObjectArray_ThrowsWhenEmpty() {
+ Object[] array = new Object[0];
+ Check.notEmpty(array);
+ }
+
+ @Test public void notEmptyObjectArray_ReturnsWhenNotEmpty() {
+ try {
+ Object[] array = new Object[1];
+ Check.notEmpty(array);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyObjectArray_Message_ThrowsWhenNull() {
+ Object[] array = null;
+ Check.notEmpty(array, STATIC_MESSAGE);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyObjectArray_Message_ThrowsWhenEmpty() {
+ Object[] array = new Object[0];
+ Check.notEmpty(array, STATIC_MESSAGE);
+ }
+
+ @Test public void notEmptyObjectArray_Message_ReturnsWhenNotEmpty() {
+ try {
+ Object[] array = new Object[1];
+ Check.notEmpty(array, STATIC_MESSAGE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyObjectArray_MessageArgs_ThrowsWhenNull() {
+ Object[] array = null;
+ Check.notEmpty(array, MESSAGE_FORMAT, MESSAGE_VALUE);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyObjectArray_MessageArgs_ThrowsWhenEmpty() {
+ Object[] array = new Object[0];
+ Check.notEmpty(array, MESSAGE_FORMAT, MESSAGE_VALUE);
+ }
+
+ @Test public void notEmptyObjectArray_MessageArgs_ReturnsWhenNotEmpty() {
+ try {
+ Object[] array = new Object[1];
+ Check.notEmpty(array, MESSAGE_FORMAT, MESSAGE_VALUE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyCollection_ThrowsWhenNull() {
+ Collection<String> collection = null;
+ Check.notEmpty(collection);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyCollection_ThrowsWhenEmpty() {
+ Collection<String> collection = new ArrayList<String>();
+ Check.notEmpty(collection);
+ }
+
+ @Test public void notEmptyCollection_ReturnsWhenNotEmpty() {
+ try {
+ Collection<String> collection = new ArrayList<String>();
+ collection.add(null);
+ Check.notEmpty(collection);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyCollection_Message_ThrowsWhenNull() {
+ Collection<String> collection = null;
+ Check.notEmpty(collection, STATIC_MESSAGE);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyCollection_Message_ThrowsWhenEmpty() {
+ Collection<String> collection = new ArrayList<String>();
+ Check.notEmpty(collection, STATIC_MESSAGE);
+ }
+
+ @Test public void notEmptyCollection_Message_ReturnsWhenNotEmpty() {
+ try {
+ Collection<String> collection = new ArrayList<String>();
+ collection.add(null);
+ Check.notEmpty(collection, STATIC_MESSAGE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyCollection_MessageArgs_ThrowsWhenNull() {
+ Collection<String> collection = null;
+ Check.notEmpty(collection, MESSAGE_FORMAT, MESSAGE_VALUE);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyCollection_MessageArgs_ThrowsWhenEmpty() {
+ Collection<String> collection = new ArrayList<String>();
+ Check.notEmpty(collection, MESSAGE_FORMAT, MESSAGE_VALUE);
+ }
+
+ @Test public void notEmptyCollection_MessageArgs_ReturnsWhenNotEmpty() {
+ try {
+ Collection<String> collection = new ArrayList<String>();
+ collection.add(null);
+ Check.notEmpty(collection, MESSAGE_FORMAT, MESSAGE_VALUE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyMap_ThrowsWhenNull() {
+ Map<String, String> map = null;
+ Check.notEmpty(map);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyMap_ThrowsWhenEmpty() {
+ Map<String, String> map = new HashMap<String, String>();
+ Check.notEmpty(map);
+ }
+
+ @Test public void notEmptyMap_ReturnsWhenNotEmpty() {
+ try {
+ Map<String, String> map = new HashMap<String, String>();
+ map.put(null, null);
+ Check.notEmpty(map);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyMap_Message_ThrowsWhenNull() {
+ Map<String, String> map = null;
+ Check.notEmpty(map, STATIC_MESSAGE);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyMap_Message_ThrowsWhenEmpty() {
+ Map<String, String> map = new HashMap<String, String>();
+ Check.notEmpty(map, STATIC_MESSAGE);
+ }
+
+ @Test public void notEmptyMap_Message_ReturnsWhenNotEmpty() {
+ try {
+ Map<String, String> map = new HashMap<String, String>();
+ map.put(null, null);
+ Check.notEmpty(map, STATIC_MESSAGE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyMap_MessageArgs_ThrowsWhenNull() {
+ Map<String, String> map = null;
+ Check.notEmpty(map, MESSAGE_FORMAT, MESSAGE_VALUE);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void notEmptyMap_MessageArgs_ThrowsWhenEmpty() {
+ Map<String, String> map = new HashMap<String, String>();
+ Check.notEmpty(map, MESSAGE_FORMAT, MESSAGE_VALUE);
+ }
+
+ @Test public void notEmptyMap_MessageArgs_ReturnsWhenNotEmpty() {
+ try {
+ Map<String, String> map = new HashMap<String, String>();
+ map.put(null, null);
+ Check.notEmpty(map, MESSAGE_FORMAT, MESSAGE_VALUE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test public void noNullsObjectArray_ReturnsWhenNull() {
+ try {
+ Object[] array = null;
+ Check.noNulls(array);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test public void noNullsObjectArray_ReturnsWhenEmpty() {
+ try {
+ Object[] array = new Object[0];
+ Check.noNulls(array);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test public void noNullsObjectArray_ReturnsWhenNotEmptyWithNoNulls() {
+ try {
+ Object[] array = new Object[] { "bob", "frank" };
+ Check.noNulls(array);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void noNullsObjectArray_ThrowsWhenHasANull() {
+ Object[] array = new Object[] { "bob", null };
+ Check.noNulls(array);
+ }
+
+ @Test public void noNullsObjectArray_Message_ReturnsWhenNull() {
+ try {
+ Object[] array = null;
+ Check.noNulls(array, STATIC_MESSAGE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test public void noNullsObjectArray_Message_ReturnsWhenEmpty() {
+ try {
+ Object[] array = new Object[0];
+ Check.noNulls(array, STATIC_MESSAGE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test public void noNullsObjectArray_Message_ReturnsWhenNotEmptyWithNoNulls() {
+ try {
+ Object[] array = new Object[] { "bob", "frank" };
+ Check.noNulls(array, STATIC_MESSAGE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void noNullsObjectArray_Message_ThrowsWhenHasANull() {
+ Object[] array = new Object[] { "bob", null };
+ Check.noNulls(array, STATIC_MESSAGE);
+ }
+
+ @Test public void noNullsObjectArray_MessageArgs_ReturnsWhenNull() {
+ try {
+ Object[] array = null;
+ Check.noNulls(array, MESSAGE_FORMAT, MESSAGE_VALUE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test public void noNullsObjectArray_MessageArgs_ReturnsWhenEmpty() {
+ try {
+ Object[] array = new Object[0];
+ Check.noNulls(array, MESSAGE_FORMAT, MESSAGE_VALUE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test public void noNullsObjectArray_MessageArgs_ReturnsWhenNotEmptyWithNoNulls() {
+ try {
+ Object[] array = new Object[] { "bob", "frank" };
+ Check.noNulls(array, MESSAGE_FORMAT, MESSAGE_VALUE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void noNullsObjectArray_MessageArgs_ThrowsWhenHasANull() {
+ Object[] array = new Object[] { "bob", null };
+ Check.noNulls(array, MESSAGE_FORMAT, MESSAGE_VALUE);
+ }
+
+ @Test public void noNullsIterable_ReturnsWhenNull() {
+ try {
+ List<String> iterable = null;
+ Check.noNulls(iterable);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test public void noNullsList_ReturnsWhenEmpty() {
+ try {
+ List<String> iterable = new ArrayList<String>();
+ Check.noNulls(iterable);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test public void noNullsList_ReturnsWhenNotEmptyWithNoNulls() {
+ try {
+ List<String> iterable = new ArrayList<String>();
+ iterable.add("bob");
+ Check.noNulls(iterable);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void noNullsList_ThrowsWhenHasANull() {
+ List<String> iterable = new ArrayList<String>();
+ iterable.add("bob");
+ iterable.add(null);
+ Check.noNulls(iterable);
+ }
+
+ @Test public void noNullsIterable_Message_ReturnsWhenNull() {
+ try {
+ List<String> iterable = null;
+ Check.noNulls(iterable, STATIC_MESSAGE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test public void noNullsList_Message_ReturnsWhenEmpty() {
+ try {
+ List<String> iterable = new ArrayList<String>();
+ Check.noNulls(iterable, STATIC_MESSAGE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test public void noNullsList_Message_ReturnsWhenNotEmptyWithNoNulls() {
+ try {
+ List<String> iterable = new ArrayList<String>();
+ iterable.add("bob");
+ Check.noNulls(iterable, STATIC_MESSAGE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void noNullsList_Message_ThrowsWhenHasANull() {
+ List<String> iterable = new ArrayList<String>();
+ iterable.add("bob");
+ iterable.add(null);
+ Check.noNulls(iterable, STATIC_MESSAGE);
+ }
+
+ @Test public void noNullsIterable_MessageArgs_ReturnsWhenNull() {
+ try {
+ List<String> iterable = null;
+ Check.noNulls(iterable, MESSAGE_FORMAT, MESSAGE_VALUE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test public void noNullsList_MessageArgs_ReturnsWhenEmpty() {
+ try {
+ List<String> iterable = new ArrayList<String>();
+ Check.noNulls(iterable, MESSAGE_FORMAT, MESSAGE_VALUE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test public void noNullsList_MessageArgs_ReturnsWhenNotEmptyWithNoNulls() {
+ try {
+ List<String> iterable = new ArrayList<String>();
+ iterable.add("bob");
+ Check.noNulls(iterable, MESSAGE_FORMAT, MESSAGE_VALUE);
+ } catch (IllegalArgumentException e) {
+ fail();
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void noNullsList_MessageArgs_ThrowsWhenHasANull() {
+ List<String> iterable = new ArrayList<String>();
+ iterable.add("bob");
+ iterable.add(null);
+ Check.noNulls(iterable, MESSAGE_FORMAT, MESSAGE_VALUE);
+ }
+}
Modified: incubator/shindig/trunk/javascript/container/cookies.js
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/javascript/container/cookies.js?rev=608302&r1=608301&r2=608302&view=diff
==============================================================================
--- incubator/shindig/trunk/javascript/container/cookies.js (original)
+++ incubator/shindig/trunk/javascript/container/cookies.js Wed Jan 2 17:20:35 2008
@@ -1,12 +1,20 @@
-// Copyright 2006 Google Inc.
-// All Rights Reserved.
+//
+// Licensed 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.
+//
/**
* @fileoverview Functions for setting, getting and deleting cookies
- *
- * @author arv@google.com (Erik Arvidsson) [Based on common.js]
*/
-
/**
* Namespace for cookie functions
Modified: incubator/shindig/trunk/javascript/container/gadgets.js
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/javascript/container/gadgets.js?rev=608302&r1=608301&r2=608302&view=diff
==============================================================================
--- incubator/shindig/trunk/javascript/container/gadgets.js (original)
+++ incubator/shindig/trunk/javascript/container/gadgets.js Wed Jan 2 17:20:35 2008
@@ -1,11 +1,19 @@
-// Copyright 2007 Google Inc.
-// All Rights Reserved.
+//
+// Licensed 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.
+//
/**
* @fileoverview Open Gadget Container
- *
- * @author jyang@google.com (Jun Yang)
- * @author wangz@google.com (Zhen Wang)
*/
// -----
Added: incubator/shindig/trunk/javascript/gadgets/core.js
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/javascript/gadgets/core.js?rev=608302&view=auto
==============================================================================
--- incubator/shindig/trunk/javascript/gadgets/core.js (added)
+++ incubator/shindig/trunk/javascript/gadgets/core.js Wed Jan 2 17:20:35 2008
@@ -0,0 +1 @@
+var gadgets = {};
Added: incubator/shindig/trunk/javascript/gadgets/ifpc.js
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/javascript/gadgets/ifpc.js?rev=608302&view=auto
==============================================================================
--- incubator/shindig/trunk/javascript/gadgets/ifpc.js (added)
+++ incubator/shindig/trunk/javascript/gadgets/ifpc.js Wed Jan 2 17:20:35 2008
@@ -0,0 +1,480 @@
+/**
+ * Licensed 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.
+ */
+
+var gadgets = gadgets || {};
+
+/**
+ * IFrame pool
+ */
+gadgets.IFramePool_ = function() {
+ this.pool_ = [];
+};
+
+/**
+ * Returns a newly created IFRAME with the locked state as specified
+ * @param {Boolean} locked whether the created IFRAME is locked by default
+ * @returns {HTMLElement} the created IFRAME element
+ * @private
+ */
+gadgets.IFramePool_.prototype.createIFrame_ = function(locked) {
+ var div = document.createElement("DIV");
+
+ // MSIE will reliably trigger an IFRAME onload event if the onload is defined
+ // inlined but not if it is defined via JS with element.onload = func;
+ // We create it within a DIV but eventually is moved directly into doc.body.
+ div.innerHTML = "<iframe onload='this.pool_locked=false'></iframe>";
+
+ var iframe = div.getElementsByTagName("IFRAME")[0];
+ iframe.style.visibility = 'hidden';
+ iframe.style.width = iframe.style.height = '0px';
+ iframe.style.border = '0px';
+ iframe.style.position = 'absolute';
+
+ iframe.pool_locked = locked;
+ this.pool_[this.pool_.length] = iframe;
+
+ // The div was only used to create the iframe. Now we disown and remove it.
+ div.removeChild(iframe);
+ div = null;
+ return iframe;
+};
+
+/**
+ * Retrieves an available IFrame and sets the URL to 'url'
+ * @param {String} url The URL the IFrame is pointed to
+ */
+gadgets.IFramePool_.prototype.iframe = function(url) {
+ // Reject weird urls
+ if (!url.match(/^http[s]?:\/\//)) {
+ return;
+ }
+ // We wrap this code in a setTimeout call to avoid tying the UI up too much
+ // with a series of repeated IFRAME creation calls.
+
+ var ifp = this;
+ window.setTimeout(function() {
+ var iframe = null;
+
+ // For MSIE, delete any iframes that are no longer being used. MSIE cannnot
+ // re-use the IFRAME because it will 'click' when we set the SRC.
+ // Other browsers scan the pool for a free iframe to re-use.
+ for (var i = ifp.pool_.length - 1; i >= 0; i--) {
+ var ifr = ifp.pool_[i];
+ if (ifr && !ifr.pool_locked) {
+ ifr.parentNode.removeChild(ifr);
+ if (window.ActiveXObject) { // MSIE
+ ifr = null;
+ ifp.pool_[i] = null;
+ ifp.pool_.splice(i,1); // Remove it from the array
+ } else {
+ ifr.pool_locked = true;
+ iframe = ifr;
+ break;
+ }
+ }
+ }
+
+ // If no iframe was found to re-use we create a new one
+ iframe = iframe ? iframe : ifp.createIFrame_(true);
+ iframe.src = url;
+
+ // We append to the body after setting the src otherwise MSIE will 'click'
+ document.body.appendChild(iframe);
+ }, 0);
+};
+
+/**
+ * Clears the pool and re-initializes it to empty
+ */
+gadgets.IFramePool_.prototype.clear = function() {
+ for (var i = 0; i < this.pool_.length; i++) {
+ this.pool_[i].onload = null;
+ this.pool_[i] = null;
+ }
+ this.pool_.length = 0;
+ this.pool_ = new Array();
+};
+
+/**
+ * Inter-frame procedure call
+ */
+gadgets.IFPC_ = function() {
+
+var CALLBACK_ID_PREFIX_ = "cbid";
+var CALLBACK_SERVICE_NAME_ = "ifpc_callback";
+var iframe_pool_ = new gadgets.IFramePool_();
+var packet_store_ = {};
+var services_ = {};
+var callbacks_ = {};
+var callback_counter_ = 0;
+var call_counter_ = 0;
+
+/**
+ * Registers a new service and associates it with 'handler'
+ * @param {String} name the id to used to identify this service when calling
+ * @param {Function} handler function to handle incoming requests
+ */
+function registerService(name, handler) {
+ services_[name] = handler;
+}
+
+/**
+ * Unregisters a registered service
+ * @param {String} name the id used to identify the service when calling
+ */
+function unregisterService(name) {
+ delete services_[name];
+}
+
+/**
+ * dispatches the call
+ * @param {String} iframe_id iframe ID to use for this request
+ * @param {String} service_name service name
+ * @param {Array} args_list array of arguments expected by this service
+ * @param {String} remote_relay_url remote relay URL of the relay HTML page
+ * @param {Function} callback callback function if a response is expected
+ * (can be null if no callback expected)
+ * @param {String} local_relay_url local relay URL of the relay HTML page
+ * (can be null if callback is also null)
+ */
+function call(iframe_id,
+ service_name,
+ args_list,
+ remote_relay_url,
+ callback,
+ local_relay_url,
+ opt_shouldThrowError) {
+ // We prepend some other arguments that the processRequest
+ // method is expecting and will shift off in reverse order
+ // once all the packets have been received
+ // First make a local copy of args_list
+ args_list = args_list.slice(0);
+ args_list.unshift(registerCallback_(callback));
+ args_list.unshift(local_relay_url);
+ args_list.unshift(service_name);
+ args_list.unshift(iframe_id);
+
+ // Figure out how much URL space is available for actual data.
+ // MSIE puts a limit of 4095 total chars including the # data.
+ // Other browsers have limits at least as large as 4095.
+ var max_data_len = 4095 - remote_relay_url.length;
+ // Because we encodeArgs twice we need to leave room for escape chars
+ max_data_len = parseInt(max_data_len / 3, 10);
+
+ if (typeof opt_shouldThrowError == "undefined") {
+ opt_shouldThrowError = true;
+ }
+
+ // Format of each packet is:
+ // #iframe_id&callId&num_packets&packet_num&block_of_data
+ var data = encodeArgs_(args_list);
+ var num_packets = parseInt(data.length / max_data_len, 10);
+ if (data.length % max_data_len > 0) {
+ num_packets += 1;
+ }
+ for (var i = 0; i < num_packets; i++) {
+ var data_slice = data.substr(i*max_data_len, max_data_len);
+ var packet = [iframe_id, call_counter_, num_packets, i,
+ data_slice, opt_shouldThrowError];
+ iframe_pool_.iframe(
+ remote_relay_url + "#" + encodeArgs_(packet));
+ }
+ call_counter_++;
+}
+
+/**
+ * Clears internal state.
+ * Should be called from an unload handler to avoid memory leaks.
+ */
+function clear() {
+ services_ = {};
+ callbacks_ = {};
+ iframe_pool_.clear();
+}
+
+/**
+ * Relays a request either from container to gadget, from gadget to container,
+ * or from gadget to gadget.
+ * @param {String} argsString encoded parameters
+ */
+function relayRequest(argsString) {
+ // Extract the iframe-id.
+ var iframeId = decodeArgs_(argsString)[0];
+ // Need to find the destination window to pass the request on to.
+ // We are in an IFPC relay iframe within the source window.
+ var win = null;
+ // If container-to-gadget communication, the window corresponding to
+ // 'iframeId' will be our sibling, ie. a child of the container page,
+ // and this child is the window we need.
+ try {
+ win = window.parent.frames[iframeId];
+ } catch (e) {
+ // Doesn't look like container-to-gadget communication.
+ // Just leave 'win' unset.
+ }
+ // If gadget-to-gadget communication, the window corresponding to
+ // 'iframeId' will be a sibling of our outer page, and this is the
+ // window we need.
+ try {
+ if (!win && window.parent.parent.frames[iframeId] != window.parent) {
+ win = window.parent.parent.frames[iframeId];
+ }
+ } catch (e) {
+ // Doesn't look like gadget-to-gadget communication.
+ // Just leave 'win' unset.
+ }
+ if (!win) {
+ // Wasn't container-to-gadget nor gadget-to-gadget communication.
+ // If gadget-to-container communication, 'iframeId' will be our grandparent.
+ win = window.parent.parent;
+ }
+ // Now that 'win' is set appropriately, pass on the request.
+ // Obscure Firefox bug sometimes causes an exception when xmlhttp is
+ // utilized in an IFPC handler. Wrapping our handleRequest calls
+ // with a setTimeout in the target window's scope prevents this
+ // exception.
+ // See this Mozilla bug for more info:
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=249843
+ // Also see this blogged account of the bug:
+ // http://the-stickman.com/web-development/javascript/iframes-xmlhttprequest-bug-in-firefox
+ var fn = function() {
+ win.gadgets.IFPC_.handleRequest(argsString);
+ };
+
+ if (window.ActiveXObject) { // MSIE
+ // call the relay synchronously in IE
+ // this is required because the iframe (and its relay closure)
+ // may otherwise be deleted/invalidated before this call is made
+ fn();
+ } else {
+ // all other browsers call with timeout, particularly FF. See
+ // above comment regarding FF bug for why it's done this way
+ win.setTimeout(fn, 0);
+ }
+}
+
+/**
+ * Internal function that processes the request
+ * @param {String} packet encoded parameters
+ */
+function handleRequest(packet) {
+ var packet = decodeArgs_(packet);
+
+ var iframeId = packet.shift();
+ var callId = packet.shift();
+ var numPackets = packet.shift();
+ var packetNum = packet.shift();
+ var data = packet.shift();
+ var shouldThrowError = packet.shift();
+ // If you see fit to add a parameter here, don't.
+ // If you must, be sure to add it to the END of the list!
+ // If you don't, lots of problems will occur in situations where
+ // IFPC versions mismatch, because ordered arguments will no longer
+ // match up, causing all manner of breakages and odd behavior.
+
+ // We store incoming packets in the packet_store object.
+ // The key is the iframeId + the unique callId.
+ // The value is an array to hold all the packets for the request.
+ // The elements in the array are a 2-element array: packetNum and data.
+ // When all packets are received, we sort based on the packetNum and then
+ // re-create the original data block before passing to the Service Handler.
+ var key = iframeId + "_" + callId;
+ if (!packet_store_[key]) packet_store_[key] = [];
+ packet_store_[key].push([packetNum, data]);
+
+ if (packet_store_[key].length == numPackets) {
+ // All packets have been received
+ packet_store_[key].sort(function(a,b){
+ return parseInt(a[0], 10) - parseInt(b[0], 10);
+ });
+
+ data = "";
+ for (var i = 0; i < numPackets; i++) {
+ data += packet_store_[key][i][1];
+ }
+ // Clear this entry from the packet_store
+ packet_store_[key] = null;
+
+ var args = decodeArgs_(data);
+
+ var iframeId = args.shift();
+ var serviceName = args.shift();
+ var remote_relay_url = args.shift();
+ var callbackId = args.shift();
+
+ var handler = getServiceHandler_(serviceName);
+ if (handler) {
+ var args_list_result = handler.apply(null, args);
+ if (isCallbackIdWellFormed_(callbackId)) {
+ args_list_result.unshift(callbackId);
+ call(iframeId,
+ CALLBACK_SERVICE_NAME_,
+ args_list_result,
+ remote_relay_url,
+ null, // no callback from the callback
+ ""); // no callback, no relay needed
+ }
+ } else if (shouldThrowError) {
+ throw new Error("Service " + serviceName + " not registered.");
+ }
+ }
+}
+
+/**
+ * Returns the service handler given a specific service name
+ * @param {String} name service name
+ * @returns {Function} service
+ * @private
+ */
+function getServiceHandler_(name) {
+ if(services_.hasOwnProperty(name)) {
+ return services_[name];
+ } else {
+ return null;
+ }
+}
+
+/**
+ * Registers a new callback
+ * @param {Function} callback callback function
+ * @returns {String} a callback ID to use with call()
+ * @private
+ */
+function registerCallback_(callback) {
+ var callbackId = "";
+ if (callback && typeof callback == "function") {
+ callbackId = getNewCallbackId_();
+ callbacks_[callbackId] = callback;
+ }
+ return callbackId;
+}
+
+/**
+ * Unregisters an existing callback
+ * @param {String} callback_id callback ID
+ */
+function unregisterCallback(callback_id) {
+ if (callbacks_.hasOwnProperty(callback_id)) {
+ callbacks_[callback_id] = null;
+ }
+}
+
+/**
+ * Returns the callback given a specific callback id
+ * @param {String} callback_id callback ID
+ * @returns {Function|null} callback function
+ * @private
+ */
+function getCallback_(callback_id) {
+ if (callback_id &&
+ callbacks_.hasOwnProperty(callback_id)) {
+ return callbacks_[callback_id];
+ }
+ return null;
+}
+
+/**
+ * Gets a new callback ID
+ * @returns {String} a callback ID string
+ * @private
+ */
+function getNewCallbackId_() {
+ return CALLBACK_ID_PREFIX_ + (callback_counter_++);
+}
+
+/**
+ * Return the decoded arguments a a list. First element is the service name.
+ * @param {String} argsString Encoded argument string
+ * @returns {Array} decoded argument list
+ * @private
+ */
+function decodeArgs_(argsString) {
+ var args = argsString.split('&');
+ for(var i = 0; i < args.length; i++) {
+ var arg = decodeURIComponent(args[i]);
+ try {
+ arg = gadgets.JSON.parse(arg);
+ } catch (e) {
+ // unexpected, but ok - treat as a string
+ }
+ args[i] = arg;
+ }
+ return args;
+}
+
+/**
+ * Determines whether a callbackId is well-formed.
+ * @param {String} callbackId callback ID
+ * @returns {Boolean} whether the callbackId is well-formed
+ * @private
+ */
+function isCallbackIdWellFormed_(callbackId) {
+ return (callbackId+"").indexOf(CALLBACK_ID_PREFIX_) == 0;
+}
+
+/**
+ * Private handler for the built-in callback service
+ * @param {String} callbackId callback ID
+ * @private
+ */
+function callbackServiceHandler_(callbackId) {
+ var callback = getCallback_(callbackId);
+ if (callback) {
+ var args = [];
+ for (var i = 1; i < arguments.length; i++) {
+ args[args.length] = arguments[i]; // append the extra arguments
+ }
+ callback.apply(null, args);
+
+ // Once the callback is triggered, we remove it.
+ unregisterCallback_(callbackId);
+ } else {
+ throw new Error("Invalid callbackId");
+ }
+}
+
+/**
+ * Return the encoded argument string.
+ * @param {Array} args list of arguments to encode
+ * @returns {String} encoded argument string
+ * @private
+ */
+function encodeArgs_(args) {
+ var argsEscaped = [];
+ for(var i = 0; i < args.length; i++) {
+ var arg = gadgets.JSON.stringify(args[i]);
+ argsEscaped.push(encodeURIComponent(arg));
+ }
+ return argsEscaped.join('&');
+}
+
+// Register the built-in callback handler
+registerService(CALLBACK_SERVICE_NAME_, callbackServiceHandler_);
+
+// Public methods
+return {
+ registerService: registerService,
+ unregisterService: unregisterService,
+ call: call,
+ clear: clear,
+ relayRequest: relayRequest,
+ processRequest: relayRequest,
+ handleRequest: handleRequest
+};
+
+}();
+
+// Alias for legacy code
+var _IFPC = gadgets.IFPC_;
+
Added: incubator/shindig/trunk/javascript/gadgets/ifpc_relay.html
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/javascript/gadgets/ifpc_relay.html?rev=608302&view=auto
==============================================================================
--- incubator/shindig/trunk/javascript/gadgets/ifpc_relay.html (added)
+++ incubator/shindig/trunk/javascript/gadgets/ifpc_relay.html Wed Jan 2 17:20:35 2008
@@ -0,0 +1,11 @@
+<html>
+<head>
+<script src='json.js'></script>
+<script src='ifpc.js'></script>
+<script>
+var l=window.location.href;
+gadgets.IFPC_.processRequest(l.substring(l.indexOf('#')+1));
+</script>
+</head>
+</html>
+
Added: incubator/shindig/trunk/javascript/gadgets/io.js
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/javascript/gadgets/io.js?rev=608302&view=auto
==============================================================================
--- incubator/shindig/trunk/javascript/gadgets/io.js (added)
+++ incubator/shindig/trunk/javascript/gadgets/io.js Wed Jan 2 17:20:35 2008
@@ -0,0 +1,170 @@
+/*
+ * Licensed 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.
+ */
+
+ var gadgets = gadgets || {};
+
+ /**
+ * Provides remote content retrieval facilities. Available to every gadget.
+ */
+ gadgets.IO = function() {
+
+ /**
+ * Holds configuration-related data such as proxy urls.
+ */
+ var config = {};
+
+ /**
+ * @enum
+ */
+ var ContentType = {
+ JSON: "json",
+ TEXT: "text",
+ XML: "xml"
+ };
+
+ /**
+ * Internal facility to create an xhr request.
+ */
+ function makeXhr() {
+ if (window.XMLHttpRequest) {
+ return new XMLHttpRequest();
+ } else if (window.ActiveXObject) {
+ var x = new ActiveXObject("Msxml2.XMLHTTP");
+ if (!x) {
+ x = new ActiveXObject("Microsoft.XMLHTTP");
+ }
+ return x;
+ }
+ }
+
+ var UNPARSEABLE_CRUFT = "throw 1; < don't be evil' >";
+
+ /**
+ * Handles XHR callback processing.
+ *
+ * @param {String} url
+ * @param {Function} callback
+ * @param {Object} params
+ * @param {Object} xobj
+ */
+ function processResponse(url, callback, params, xobj) {
+ if (xobj.readyState !== 4) {
+ return;
+ }
+ var txt = xobj.responseText;
+ // remove unparseable cruft.
+ // TODO: really remove this by eliminating it. It's not any real security
+ // to begin with, and we can solve this problem by using post requests
+ // and / or passing the url in the http headers.
+ txt = txt.substr(UNPARSEABLE_CRUFT.length);
+ // TODO: safe JSON parser.
+ var data = eval("(" + txt + ")");
+ data = data[url];
+ var resp = {
+ text: data.body,
+ errors: []
+ };
+ switch (params.type) {
+ case ContentType.JSON:
+ // TODO: safe JSON parser.
+ resp.data = eval("(" + resp.text + ")");
+ break;
+ case ContentType.XML:
+ // TODO: more robust xml parser.
+ resp.data = xobj.responseXML;
+ break;
+ default:
+ resp.data = resp.text;
+ break;
+ }
+ callback(resp);
+ }
+
+ /**
+ * Retrieves the content at the specified url.
+ *
+ * @param {String} url The url to fetch.
+ * @param {Function} callback Invoked when the request completes. The
+ * response object will be passed in as a parameter.
+ * @param {Object} opt_params Optional parameters. May be modified.
+ *
+ * <pre>
+ * gadgets.IO.makeRequest(url, fn, {type: gadgets.IO.ContentType.JSON});
+ * </pre>
+ */
+ function makeRequest(url, callback, opt_params) {
+ var xhr = makeXhr();
+ var params = opt_params || {};
+ var newUrl = config.jsonProxyUrl.replace("%url%", encodeURIComponent(url));
+ xhr.open(params.postData ? "POST" : "GET", newUrl, true);
+ if (callback) {
+ xhr.onreadystatechange = gadgets.Util.makeClosure(null, processResponse,
+ url,
+ callback,
+ params,
+ xhr);
+ }
+ xhr.send(params.postData);
+ }
+
+ /**
+ * Converts an input object into a url encoded data string (key=value&...)
+ *
+ * @param {Object} fields The post fields you wish to encode
+ * @return {String} The processed post data. This will include a trialing
+ * ampersand (&).
+ */
+ function encodeValues(fields) {
+ var buf = [];
+ for (var i in fields) {
+ buf.push(encodeURIComponent(i));
+ buf.push("=");
+ buf.push(encodeURIComponent(fields[i]));
+ buf.push("&");
+ }
+ return buf.join("");
+ }
+
+ /**
+ * @param {String} url The url to get the proxy url for.
+ * @return {String} The proxied version of the url.
+ */
+ function getProxyUrl(url) {
+ return config.proxyUrl.replace("%url%", encodeURIComponent(url));
+ }
+
+ /**
+ * Initializes fetchers
+ * @param {Object} configuration Configuration settings.
+ * Required:
+ * - proxyUrl: The url for content proxy requests. Include %url%
+ * as a placeholder for the actual url.
+ * - jsonProxyUrl: The url for dynamic proxy requests. Include %url%
+ * as a placeholder for the actual url.
+ */
+ function init(configuration) {
+ config = configuration;
+ if (!config.proxyUrl || !config.jsonProxyUrl) {
+ throw new Error("proxyUrl and jsonProxyUrl are required.");
+ }
+ }
+
+ return {
+ ContentType: ContentType,
+ makeRequest: makeRequest,
+ getProxyUrl: getProxyUrl,
+ encodeValues: encodeValues,
+ init: init
+ };
+ }();
\ No newline at end of file
Added: incubator/shindig/trunk/javascript/gadgets/json.js
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/javascript/gadgets/json.js?rev=608302&view=auto
==============================================================================
--- incubator/shindig/trunk/javascript/gadgets/json.js (added)
+++ incubator/shindig/trunk/javascript/gadgets/json.js Wed Jan 2 17:20:35 2008
@@ -0,0 +1,144 @@
+/*
+Copyright (c) 2005 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 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.
+*/
+
+/*
+ The global object JSON contains two methods.
+
+ gadgets.JSON.stringify(value)
+ takes a JavaScript value and produces a JSON text.
+ The value must not be cyclical.
+
+ gadgets.JSON.parse(text)
+ takes a JSON text and produces a JavaScript value. It will
+ return false if there is an error.
+*/
+var gadgets = gadgets || {};
+gadgets.JSON = function () {
+ var m = {
+ '\b': '\\b',
+ '\t': '\\t',
+ '\n': '\\n',
+ '\f': '\\f',
+ '\r': '\\r',
+ '"' : '\\"',
+ '\\': '\\\\'
+ },
+ s = {
+ 'boolean': function (x) {
+ return String(x);
+ },
+ number: function (x) {
+ return isFinite(x) ? String(x) : 'null';
+ },
+ string: function (x) {
+ if (/["\\\x00-\x1f]/.test(x)) {
+ x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
+ var c = m[b];
+ if (c) {
+ return c;
+ }
+ c = b.charCodeAt();
+ return '\\u00' +
+ Math.floor(c / 16).toString(16) +
+ (c % 16).toString(16);
+ });
+ }
+ return '"' + x + '"';
+ },
+ object: function (x) {
+ if (x) {
+ var a = [], b, f, i, l, v;
+ if (x instanceof Array) {
+ a[0] = '[';
+ l = x.length;
+ for (i = 0; i < l; i += 1) {
+ v = x[i];
+ f = s[typeof v];
+ if (f) {
+ v = f(v);
+ if (typeof v == 'string') {
+ if (b) {
+ a[a.length] = ',';
+ }
+ a[a.length] = v;
+ b = true;
+ }
+ }
+ }
+ a[a.length] = ']';
+ } else if (typeof x.hasOwnProperty === 'function') {
+ a[0] = '{';
+ for (i in x) {
+ if (x.hasOwnProperty(i)) {
+ v = x[i];
+ f = s[typeof v];
+ if (f) {
+ v = f(v);
+ if (typeof v == 'string') {
+ if (b) {
+ a[a.length] = ',';
+ }
+ a.push(s.string(i), ':', v);
+ b = true;
+ }
+ }
+ }
+ }
+ a[a.length] = '}';
+ } else {
+ return;
+ }
+ return a.join('');
+ }
+ return 'null';
+ }
+ };
+ return {
+ copyright: '(c)2005 JSON.org',
+ license: 'http://www.JSON.org/license.html',
+/*
+ Stringify a JavaScript value, producing a JSON text.
+*/
+ stringify: function (v) {
+ var f = s[typeof v];
+ if (f) {
+ v = f(v);
+ if (typeof v == 'string') {
+ return v;
+ }
+ }
+ return null;
+ },
+/*
+ Parse a JSON text, producing a JavaScript value.
+ It returns false if there is a syntax error.
+*/
+ parse: function (text) {
+ try {
+ return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
+ text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
+ eval('(' + text + ')');
+ } catch (e) {
+ return false;
+ }
+ }
+ };
+}();
Added: incubator/shindig/trunk/javascript/gadgets/legacy.js
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/javascript/gadgets/legacy.js?rev=608302&view=auto
==============================================================================
--- incubator/shindig/trunk/javascript/gadgets/legacy.js (added)
+++ incubator/shindig/trunk/javascript/gadgets/legacy.js Wed Jan 2 17:20:35 2008
@@ -0,0 +1,224 @@
+/*
+ * Licensed 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.
+ */
+
+ // All functions in this file should be treated as deprecated legacy routines.
+ // Gadget authors are explicitly discouraged from using any of them.
+
+var _IG_Prefs = gadgets.Prefs;
+
+// Yes, these technically modifiy gadget.Prefs as well. Unfortunately,
+// simply setting IG_Prefs.prototype to a new gadgets.Prefs object means
+// that we'd have to duplicate the gadgets.Prefs constructor.
+_IG_Prefs._parseURL = gadgets.Prefs.parseUrl;
+
+function _IG_Fetch_wrapper(callback, obj) {
+ callback(obj.data);
+}
+
+function _IG_FetchContent(url, callback, opt_params) {
+ var params = opt_params || {};
+ params.type = gadgets.IO.ContentType.TEXT;
+ var cb = gadgets.Util.makeClosure(null, _IG_Fetch_wrapper, callback);
+ gadgets.IO.makeRequest(url, cb, params);
+}
+
+function _IG_FetchXmlContent(url, callback, opt_params) {
+ var params = opt_params || {};
+ params.type = gadgets.IO.ContentType.XML;
+ var cb = gadgets.Util.makeClosure(null, _IG_Fetch_wrapper, callback);
+ gadgets.IO.makeRequest(url, cb, params);
+}
+
+function _IG_FetchFeedAsJSON_cb(callback, obj) {
+ if (obj.data.fr_1) {
+ callback(obj.data.fr_1);
+ } else {
+ callback(null);
+ }
+}
+
+// NOTE: this implementation does not batch calls as is the case on igoogle.
+function _IG_FetchFeedAsJSON(url, callback, numItems, getDescriptions,
+ opt_params) {
+ var params = opt_params || {};
+ // TODO: this no longer works. The proxy needs to support POST requests
+ // to make it work.
+ var finalUrl = "http://www.gmodules.com/ig/feedjson?fr_1=";
+ finalUrl += gadgets.IO.encodeValues({
+ url: encodeURIComponent(url),
+ val: numItems,
+ sum: getDescriptions ? 1 : 0
+ });
+ params.type = gadgets.IO.ContentType.JSON;
+ var cb = gadgets.Util.makeClosure(null, _IG_FetchFeedAsJSON_cb, callback);
+ gadgets.IO.makeRequest(finalUrl, cb, params);
+}
+
+function _IG_GetCachedUrl(url) {
+ return gadgets.IO.getProxyUrl(url);
+}
+function _IG_GetImageUrl(url) {
+ return gadgets.IO.getProxyUrl(url);
+}
+
+function _IG_RegisterOnloadHandler(callback) {
+ window.onload = callback;
+}
+
+var _args = gadgets.Util.getParameters;
+
+/**
+ * Fetches an object by document id.
+ *
+ * @param {String | Object} el The element you wish to fetch. You may pass
+ * an object in which allows this to be called regardless of whether or
+ * not the type of the input is known.
+ * @return {HTMLElement} The element, if it exists in the document, or null.
+ */
+function _gel(el) {
+ return document.getElementById ? document.getElementById(el) : null;
+}
+
+/**
+ * Fetches elements by tag name.
+ * This is functionally identical to document.getElementsByTagName()
+ *
+ * @param {String} tag The tag to match elements against.
+ * @return {Array.<HTMLElement>} All elements of this tag type.
+ */
+function _gelstn(tag) {
+ if (n === "*" && document.all) {
+ return document.all;
+ }
+ return document.getElementsByTagName ?
+ document.getElementsByTagName(n) : [];
+}
+
+/**
+ * Fetches elements with ids matching a given regular expression.
+ *
+ * @param {tagName} tag The tag to match elements against.
+ * @param {RegEx} regex The expression to match.
+ * @return {Array.<HTMLElement>} All elements of this tag type that match
+ * regex.
+ */
+function _gelsbyregex(tagName, regex) {
+ var matchingTags = _gelstn(tagName);
+ var matchingRegex = [];
+ for (var i = 0, j = matchingTags.length; i < j; ++i) {
+ if (regex.test(matchingTags[i].id)) {
+ matchingRegex.push(matchingTags[i]);
+ }
+ }
+ return matchingRegex;
+}
+
+/**
+ * URI escapes the given string.
+ * @param {String} str The string to escape.
+ * @return {String} The escaped string.
+ */
+function _esc(str) {
+ return window.encodeURIComponent ? encodeURIComponent(str) : escape(str);
+}
+
+/**
+ * URI unescapes the given string.
+ * @param {String} str The string to unescape.
+ * @return {String} The unescaped string.
+ */
+function _unesc(str) {
+ return window.decodeURIComponent ? decodeURIComponent(str) : unescape(str);
+}
+
+/**
+ * Encodes HTML entities such as <, " and >.
+ *
+ * @param {String} str The string to escape.
+ * @return The escaped string.
+ */
+function _hesc(str) {
+ // '<' and '>'
+ str = str.replace(/</g, "<").replace(/>/g, ">");
+ // '"' and '
+ str = str.replace(/"/g, """).replace(/'/g, "'");
+
+ return str;
+}
+
+/**
+ * Removes HTML tags from the given input string.
+ *
+ * @param {String} str The string to strip.
+ * @return The stripped string.
+ */
+function _striptags(str) {
+ return s.replace(/<\/?[^>]+>/g, "");
+}
+
+/**
+ * Trims leading & trailing whitespace from the given string.
+ *
+ * @param {String} str The string to trim.
+ * @return {String} The trimmed string.
+ */
+function _trim(str) {
+ return str.replace(/^\s+|\s+$/g, "");
+}
+
+/**
+ * Toggles the given element between being shown and block-style display.
+ *
+ * @param {String | HTMLElement} el The element to toggle.
+ */
+function _toggle(el) {
+ el = _gel(el);
+ if (el !== null) {
+ if (el.style.display.length === 0 || el.style.display === "block") {
+ el.style.display = "none";
+ } else if (el.style.display === "none") {
+ el.style.display = "block";
+ }
+ }
+}
+
+/**
+ * {Number} A counter used by uniqueId().
+ */
+var _global_legacy_uidCounter = 0;
+
+/**
+ * @return a unique number.
+ */
+function _uid() {
+ return _global_legacy_uidCounter++;
+}
+
+/**
+ * @param {Number} a
+ * @param {Number} b
+ * @return The lesser of a or b.
+ */
+function _min(a, b) {
+ return (a < b ? a : b);
+}
+
+/**
+ * @param {Number} a
+ * @param {Number} b
+ * @return The greater of a or b.
+ */
+function _max(a, b) {
+ return (a > b ? a : b);
+}